首页 > 解决方案 > Recursively ignore all files inside a specific directory except .json files

问题描述

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.

标签: gitgitignore

解决方案


gitignore文档中,他们声明:

如果排除了该文件的父目录,则无法重新包含该文件。

这为您的规则失败的原因提供了直觉。您可以使用一些 xargs 魔法手动添加丢失的 json 文件。每当添加新包时,您都必须运行它,但是一旦它们被跟踪,一切都会起作用。

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

我使用 Git 进行了测试,2.18.0并确认您忽略的目录中的文件在以这种方式添加后可以正常工作。对于您的规则排除的较深路径,上述-f参数是必需的。.gitignore


推荐阅读