Search code examples
gitgitignore

Is there a way to have git ignore files in the root directory if they don't match a specific naming convention?


Ok, so I've already looked for some way to do this on Google and have searched on Stackoverflow but so far haven't seen anything yet that states how this could be done (or if it's jut not possible).

What I need to do is to be able to ignore all .txt files in the root directory, except for those with certain kind of naming pattern to them. For example the following files would be ones I'd want "seen" and able to be committed to the repository:

  • W1234_M01.txt
  • W4321_M99.txt
  • C9999_M00.txt
  • W4321R1_M49.txt
  • W1234_M1Z.txt
  • W1234_M1AA.txt
  • ReadMe.txt

Basically, if the file has a name that follows the pattern "[letter][4 numbers][(optional) letter followed by a number]_[M][any digit][at least 1 alphanumeric character].txt" or "ReadMe.txt" then I'd want it to not be ignored. Likewise, any .txt files that don't match this pattern in the root directory would need to be ignored. Is there any way to do this?


Solution

  • If you look at the docs, you can use this:

    An optional prefix "!" which negates the pattern; any matching file excluded by a previous pattern will become included again.

    As for patterns:

    An asterisk "*" matches anything except a slash. The character "?" matches any one character except "/". The range notation, e.g. [a-zA-Z], can be used to match one of the characters in a range. See fnmatch(3) and the FNM_PATHNAME flag for a more detailed description.

    This looks a bit wild, but should work:

    *.txt
    !W[0-9][0-9][0-9][0-9]_M[a-zA-Z0-9]?*.txt
    !W[0-9][0-9][0-9][0-9][a-zA-Z][0-9]_M[a-zA-Z0-9]*.txt
    

    As per above, it ignores all .txt files and then re-adds W, four decimal digits, _M, one letter or digit followed by optional anything. And the same for variant with letter and decimal digit preceding _.