How do .gitignore exclusion rules actually work?

Solution 1:

/a/b/c/*
!foo

Seems to work for me (git 1.7.0.4 on Linux). The * is important as otherwise you're ignoring the directory itself (so git won't look inside) instead of the files within the directory (which allows for the exclusion).

Think of the exclusions as saying "but not this one" rather than "but include this" - "ignore this directory (/a/b/c/) but not this one (foo)" doesn't make much sense; "ignore all files in this directory (/a/b/c/*) but not this one (foo)" does. To quote the man page:

An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again.

i.e., the file has to have been excluded already to be included again. Hope that sheds some light.

Solution 2:

I have a similar situation, my solution was to use:

/a/**/*
!/a/**/foo

That should work for an arbitrary number of intermediate directories if I read ** correctly.

Solution 3:

Here is another option:

*
!/a*
!/a/*
!/a/*/*
!/a/*/*/*

That would ignore every file and directory, except files/directories three levels deep within a.

Solution 4:

this is definitely not clear from the .gitignore man page. This works:

*
!/a
!/a/b
!/a/b/c
!/a/b/c/foo

# don't forget this one
!.gitignore

As mentioned by Chris a directory is not even opened if it is excluded. So if you want to be able to ignore * but some files, you have to build the path to those files as above. For me this is convenient, because I want to do a code review on 1 file of a library and if I want to do another later I just add it, and all else is ignored.

Solution 5:

On a more general note, git1.8.2 will include the patch (also in its v4, prompted by some Stack Overflow question) from Adam Spiers about determining which gitignore rule actually ignores your file.

See git1.8.2 release notes and the SO question "which gitignore rule is ignoring my file":
that will be the command git check-ignore.