Whitelisting and subdirectories in Git

Nate picture Nate · Feb 6, 2012 · Viewed 31.3k times · Source

I have created a white-list for text files only.

*
!*.txt

Now, I have an untracked text file in a sub-directory - sub/dir/file.txt, and this is NOT shown (it is ignored). Text files in the root directory are shown, however.

Why is that, and how do I fix it?

Answer

simont picture simont · Feb 10, 2012

If you try it that way, it'll fail, because you'll end up blacklisting the directories in your structure.

To solve, you want to blacklist everything that is not a directory, and is not one of the file-types you want to commit, while not blacklisting directories.

The .gitignore file that will do this:

# First, ignore everything
*
# Now, whitelist anything that's a directory
!*/
# And all the file types you're interested in.
!*.one
!*.two
!*.etc

Tested this in a three-level structure white-listing for .txt files in the presence of *.one, *.two and *.three files using a .gitignore located in the root directory of the repository - works for me. You won't have to add .gitignore files to all directories in your structure.

Information I used to figure out the answer came from, amongst other things, this (stackoverflow.com).