gitignore all except file in sub-sub folder

白昼怎懂夜的黑 提交于 2019-12-06 07:28:06

问题


I already tried many combinations of the .gitignore but none worked for what I need. I have this tree:

jobs/
jobs/projecta/config.xml
jobs/projecta/garbage
jobs/projecta/more/garbage
jobs/projectb/config.xml
jobs/projectb/garbage
jobs/projectb/more/garbage

Garbage means any other file. I want to commit only the config.xml files, and ignore everything inside jobs/ except them. So I tried:

/jobs/*
!/jobs/*/config.xml

This way, everything inside jobs are ignored, including the config.xml file. With the inverse order, same happens. So, I can force add all config files and changes to them will be tracked, but if I add a new folder inside jobs, it's config.xml won't appear as a untracked file, so this way people can forgot to add them.

I already tried with **, but I got the same.

Any ideas? Thanks!


回答1:


The question I mentioned in the comments actually answers this scenario; the crucial part is the following:

If a directory is excluded, Git will never look at the contents of that directory.

Which is just a rephrasing of this snippet from the gitignore documentation, emphasis mine.

It is not possible to re-include a file if a parent directory of that file is excluded. Git doesn’t list excluded directories for performance reasons, so any patterns on contained files have no effect, no matter where they are defined.


Your pattern /jobs/* will ignore each file and folder in jobs. This means that git won't even look in this ignored folders to see if your !/jobs/*/config.xml pattern matches a file in them.

In turn you have to explicitly unignore the subfolders and then reignore the contents; after this you can again unignore your config.xml files. This might seem silly but that's how git handles ignores.

# Ignore everything in /jobs
/jobs/*
# Reinclude all folders in /jobs
!/jobs/*/
# Ignore everything in the subfolders of /jobs
/jobs/*/*
# Reinclude config.xml files in the first-level subfolders of /jobs
!/jobs/*/config.xml

This patterns will ignore everything but config.xml files in the first-level subfolders of jobs.



来源:https://stackoverflow.com/questions/29010443/gitignore-all-except-file-in-sub-sub-folder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!