Git - ignore files by extension and include a dir that contains only these files

StackOverflow https://stackoverflow.com/questions/23678710

  •  23-07-2023
  •  | 
  •  

Question

I want to exclude all the jar files from git but include a directory (and its subdirectories) that contains only files of that type

I tried this in .gitignore

*.jar

!/lib/

but it doesn't work.

I see that it works with

*.jar

!/lib/
!/lib/*

or

*.jar

!/lib/**

but I don't understand why the first one doesn't work. Can someone explain me this behavior?

But refer to this, more in general, how can I be sure that all the files in a directory (and its subdirectories) will be included in git ignoring the previous exclusions in .gitignore?

Thanks for the help

Était-ce utile?

La solution

echo "!*" > lib/.gitignore

is the simplest way to make this work.

What's going on is that ! means "don't ignore something that a previous match to this pattern would tell you to ignore" -- and /lib/ matches only directories. No previous pattern tells git to ignore that directory.

An alternate way to explain it that I think is clearer is: excluding a directory tells git "don't even look here", which is subtly different to matching every file within. Perhaps most clearly, if you had told it /lib/, git would never check (never even see) the lib/.gitignore above. When you said '!/lib/' you told it to go ahead and look there, which it (would have anyway here, and) does.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top