gitgitattributes

How to ignore multiple lines of code in the same file type using gitattribute and git config?


As an extension of this post: Can git ignore a specific line?, I am trying to ignore multiple lines in the same file type.

Is there a way to either;

*.rs filter=filterA
*.rs filter=filterB

 // to something like
*.rs filter=filterA + filterB
[filter "filterA"]
    clean = sed "/abc/d"
[filter "filterB"]
    clean = sed "/def/d"

 // to something like
[filter "filterC"]
    clean = sed "/abc/d"
    clean = sed "/def/d"

The above causes the last filter in .gitattributes to overwrite the changes made from the first filter. I have also attempted something like clean = sed "/abc*def/d", but this did not work.


Solution

  • If you want to ignore entire lines my advice is to use grep -v instead of sed //d. The answers at the linked question use sed because they hide only parts of lines, a task for which sed is exactly suitable.

    So 1st lets rewrite your two simple filters:

    [filter "filterA"]
        clean = grep -v "abc"
    [filter "filterB"]
        clean = grep -v "def"
    

    Please be warned that if your placeholders abc and def contain regular expression metacharacters you need to escape them using backslash. Like \*grep interprets this as a literal asterisk while * is a metacharacter. See man grep.

    Now to the more complex filter: combine the two expressions into one complex regular expression:

    [filter "filterC"]
        clean = grep -v "abc\|def"
    

    \| separates branches in regular expressions in basic (default) grep syntax. In case of extended RE the syntax is

    [filter "filterC"]
        clean = grep -Ev "abc|def"