Leniaal
Leniaal

Reputation: 1737

.gitignore files based on their content

I'm looking for a way to ignore files in git that have a certain path in their file. These are XML files that are all stored together, but some reference folders that are in .gitignore. I want to exclude the XML files that reference these folders.

Is this possible purely with .gitignore? I can imagine other ways to achieve this, like force keeping these files with a script, but that would not be favorable.

Upvotes: 3

Views: 306

Answers (2)

rackpit
rackpit

Reputation: 13

To be honest, I don't quiet understand what you mean by "force keeping these files with a script", so maybe this is the way you do not favor: I suggest generating a (second) .gitignore file via the pre-commit hook and git add the wanted XML files automatically, like:

grep -l <referenceToFolderToAvoid_1> <pathToXmls>/*.xml > <pathToXmls>/.gitignore
...
grep -l <referenceToFolderToAvoid_N> <pathToXmls>/*.xml >> <pathToXmls>/.gitignore

git add <pathToXmls>/*.xml

Instead of putting all the paths in by hand, the second .gitignore file could be generated using the content of your already existing .gitignore file.

Upvotes: 1

bk2204
bk2204

Reputation: 76459

No, Git doesn't allow you to ignore files based on their contents. That would involve reading every file in your working tree to determine whether it had a particular string, and in many cases, you can have a large number of large generated files, so such an operation would be extremely expensive. One of the goals of .gitignore is to improve performance by not considering files which aren't interesting.

You'll need to adopt another solution, such as putting those files in a single folder or naming them with a certain convention so that you can ignore them with a path-based pattern.

Upvotes: 4

Related Questions