Search code examples
gitgitignore

.gitignore -- track files AND specific subdirectories of directory


Before this is marked as a duplicate out of hand, I've looked at a dozen Stack Overflow questions and none of them have worked for my case.

root/
├── trackdir1/          # track directory and its subdirectories
├── trackdir2/          # track directory and its subdirectories
├── ignoreddir/         # ignore all other subdirectories of root
├── .../
└── *                   # keep all FILES within root

I have a directory (which is actually a couple directories in, but let's pretend it's root). I want to track all files within root and some specific subdirectories of root, but to ignore all other subdirectories.

All of the Stack Overflow questions I've looked at did one or the other: included files but ignored subdirectories, or included specific subdirectories and ignored files.

Based on my understanding of .gitignore (which is clearly lacking), I need to make an exception for the files in root, exceptions for the specific subdirectories I want to track, and then exclude the files under all subdirectories within root.

!/*
!/trackdir1/
!/trackdir1/**
!/trackdir2/
!/trackdir2/**
/*/**

However, this pattern still excludes trackdir1 and trackdir2. I've also tried things like !/trackdir1 and !/trackdir1/*.

What am I doing wrong?


Solution

  • The contents of the .gitignore file are processed in order, with later instructions overriding earlier ones. So here you have /*/** overriding !/trackdir2/**, for example.

    Simply putting /*/** first should work:

    /*/**
    !/*
    !/trackdir1/
    !/trackdir1/**
    !/trackdir2/
    !/trackdir2/**