In a git diff, can I show only deletions that aren't followed by an addition?

Viewed 190

I'd like to be able to show deletions in git diff that aren't followed by an addition. That is, only show - lines that aren't followed by + lines. Is that possible?

3 Answers

With a little black magic, yes.

Step 1

We need to understand that

git diff

lists files, change sets, removals, additions and some lines around them

Step 2

We need to remove all superfluous lines, so that we get only the files and the changes inside them, like this:

git diff | grep '^\(+++\|---\|-\|+\)'

Step 3

Write a program that runs the command seen at Step 2 and displays the result. I know this is not yet the solution, but you will absolutely need this step to be performed first, so we know that the input and the output are working.

Step 4

Now, let's apply filtering. A very simple filter would be performed by this algorithm

deletedLines <- empty
for each line
    if (line starts with --- or +++) then add line to output
    else if (line starts with -) deletedLines.add(line)
    else
        if (line starts with + but not with +++) then clear deletedLines
        else add deletedLines to output
end for
git diff | awk '/^@/{ if(s) print p; s = 1; p="" } 
    s == 1 && /^\+/ { s = 0 } 1 {p = sprintf("%s\n%s", p, $0)} 
    END { if (s) print p }' s=2

An alternative solution, in a single line, and using just regular expressions. Here, I use rg, but any grep tool that supports multiline matching and inverse matching (-U and -v, respectively) will work.

git diff | rg '^(\+ |- ).*' | rg -vU '^-(.*)\n\+(.*)\n'
Related