How to let gitignore track subdirectory instances

2019-08-05 09:36发布

问题:

Possible Duplicate:
Git - Whitelisting files in a complex directory structure

I'd like to have a git repository track only files named e.g. SOURCES while everything else shall be ignored (take e.g. a tree of pdf files where each SOURCES file lists their origins). The simplest shot would have been

*
!SOURCES

in .gitignore. However the exclusion of e.g. A/SOURCES is overridden by the *, requiring me to use git add -f. How can .gitignore be modified to ignore everything except files named SOURCES without requiring a forced add?

edit The solution posted here will not do since the directory structure is not fixed, i.e. new directories containing a SOURCES file should not have to be added to .gitignore by hand...

回答1:

You can't achieve this using just .gitignore

Git doesn't track paths. It tracks objects (~ files) only.

So, why don't you reverse the tables:

git add -f -- */*/SOURCES */SOURCES

or

shopt -s globstar
git add -f -- **/SOURCES

Or get out the big guns:

git add -f -- $(find -type f -name SOURCES)

or even

find -type f -name SOURCES -exec git add -f -- {} \+

Untested idea Perhaps something like this could be in a pre-commit hook?


Update An idea for more automation:

Add this to .git/config

[alias]
ac = "!_() { git add -f -- */*/SOURCES && git commit \"$@\"; }; _"

Now, you can just say

git commit -m 'like you usually work'

and it will automatically add the */*/SOURCES



标签: git gitignore