willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

Gitignore a file if file with different extension exists

In a project where for instance a parser is involved, some source code is the product of a program. For instance yacc generates - based on a .yy file - a source code file that implements the parser.

Since small modifications in the .yy file can lead to large changes in the corresponding source code file after compilation and since the resulting source code is (almost) never altered after it is generated. Such source code files are perfect candidates for the .gitignore list.

Now one can of course write such files manually to the list:

lexer1.cpp
parser1.cpp
lexer2.cpp
parser2.cpp

But it is likely when one builds a new parser, he/she will forget to add the file to the list.

Is there a way to specify a pattern that acts as follows:

Given a file foo.ext1 exists, ignore foo.ext2.

Where one thus provides ext1 and ext2. In the case of the lexer/parser, this would mean applying this pattern for .xx/.cpp and .yy/.cpp.

This is probably not possible by .gitignore directly, but perhaps there are some hooks already implemented for this?

Upvotes: 12

Views: 1312

Answers (2)

jthill
jthill

Reputation: 60255

I can see three ways to do this -- to answer the question directly, no, ignore processing consults only the pathname in question, not anything else about the environment.

  1. Put your generated source in a generated folder you ignore.

    Me, I like this one best, I know I'm in a minority but I don't like build detritus in my source directories.

  2. Have your makefile targets also update the .gitignore, with

    grep -qs ^target$ .gitignore || echo target >>.gitignore
    

    where target is the generated source file, as part of the recipe.

  3. put some marker in the generated filenames themselves, scanner.generated.c or something.

For some reason I really dislike the pre-commit hook cleaning out unwanted source, git deleting things from a commit all by itself is just disturbing.

Upvotes: 9

suuuzi
suuuzi

Reputation: 622

My suggestion is create a script to update .gitignore. I don't know any, but you can look for a solution that runs this script automatically before a commit.

Edit: I Googled and found this: https://github.com/observing/pre-commit - Probably needs some tests.

Upvotes: 0

Related Questions