Breck
Breck

Reputation: 690

How do I make Git ignore a file by adding a comment inside that file, instead of adding the file to .gitignore?

Say I want to tell Git not to track any files that contain the string //ignoreMe!, how can I do that?

I specifically want to do this for files that are compiled artifacts of source files. I know how to do it with .gitignore, however, this doesn't scale well for a current project, where there are compiled files all over the place with many different file extensions, patterns, etc.

I can easily have the compilers add some content like //GITIGNORE, but it's harder to create rules that generalize well to match filenames in this particular project.

Upvotes: 0

Views: 209

Answers (3)

tmaj
tmaj

Reputation: 35135

Ignore build artifacts by folder.

If you setup doesn't build into an identifiable folder, change the configuration so it does.

Why not have a look at the VisualStudio's gitignore. Specifically:

# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/

Upvotes: 1

jthill
jthill

Reputation: 60557

Your compiler gives you enough control that you can compile arbitrary markers into the compiled output that aren't present in the source, but so little that you can't choose anything identifiable for the output files' names or locations? That's so obtuse I'm tempted to downvote in a feeble attempt to banish the thought, but it's too late, I'm going to have nightmares; and anyway I'd like to think sympathy for your possible plight would have stayed my hand.

No, Git's ignore processing checks only pathnames, nothing else.

Upvotes: 1

Scott Weldon
Scott Weldon

Reputation: 10227

AFAIK, there isn't a built-in way to do this in Git (probably do to the performance overhead this would require).

However, it should be possible to automate this. First, we want to find the files that need to be ignored:

grep --files-with-match --recursive '// GITIGNORE' .

For each result, we can check if it is already ignored with git check-ignore. If not, we add it to the local ignore file.

Putting this all together in a script:

#!/bin/bash

grep --files-with-match --recursive '// GITIGNORE' . | while read filename
  do
    if [ $(git check-ignore --quiet "$filename") -ne 0 ]
    then
      echo "$filename" >> .git/info/exclude
    fi
  done

If you add a build step to run that script at the end of the build, that should produce the result you desire. Depending on how often the ignored filenames change, you may want to truncate .git/info/exclude from time to time.

(If you don't have access to grep or bash, it should be possible to do a similar thing with other tools on your system of choice.)

Upvotes: 3

Related Questions