Recursively ignore all files inside a specific directory except .json files

荒凉一梦 提交于 2019-12-10 10:56:35

问题


I have a file structure similar to the one below:

foo/bar.foo
node_modules/foo/bar.json
node_modules/foo/bar/foo.bar

What I want to do is ignore all the files inside the node_modules folder except the json files so that I end up with the following file structure in my repo:

foo/bar.foo
node_modules/foo/bar.json

I tried to find a simple way to do that but I'm not quite there yet.

Here's what I came up with in my .gitignore:

# ignore everything inside node_modules
node_modules/*

# But descend into directories
!node_modules/**/*.json

What's the most elegant way to achieve the desired result?

P.S. I have no idea what I'm doing.


回答1:


In the gitignore documentation, they state:

It is not possible to re-include a file if a parent directory of that file is excluded.

This provides intuition for why your rule is failing. You can manually add the missing json files with some xargs magic. You'd have to run this whenever adding new packages, but once they're tracked everything will work.

 find node_modules/* -name *.json -print |xargs git add -f

I tested with Git 2.18.0 and confirmed that files in your ignored directory work fine after being added in this way. The -f parameter above is required for deeper paths that were excluded by your .gitignore rules.




回答2:


You must first not ignore (exclude) the subfolders of your ignored directory.

# ignore everything inside node_modules
node_modules/**

# exclude or whitelist subfolders: note the trailing /

!node_modules/**/

# But descend into directories
!node_modules/**/*.json

Do use git check-ignore -v -- afile to check which rule would still be ignoring your file.
And make sure those files were not added to the index (git rm --cached -r node_modules)




回答3:


Ok so I finally found a solution. Here's what did the trick:

# Ignore all the files inside the node_modules folder
node_modules/**/*.*

# Allow only json files inside the node_modules folder
!node_modules/**/*.json

The issue was that by doing node_modules/*, it would not just ignore files but also folders.

And as the git doc says:

It is not possible to re-include a file if a parent directory of that file is excluded.

So instead I did node_modules/**/*.* which only exclude files and not folders.

That way, !node_modules/**/*.json is actually able to white list the json files.



来源:https://stackoverflow.com/questions/52416391/recursively-ignore-all-files-inside-a-specific-directory-except-json-files

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