Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readGit

Pick a diff algorithm for git blame

Compare Myers and Histogram on a reordered file, then inspect the commit before attributing a line to the author of the move.

You run blame on a function and land on a commit that reordered a file. You want the commit that introduced the function, so compare how two diff algorithms follow its declaration through the reorder.

Git 2.53 added --diff-algorithm to blame. Blame compares revisions of the file to trace surviving lines back through history. Changing the algorithm changes which old and new lines it pairs.

Compare the same line twice

Create a scratch repository with the commands below. The second commit moves the whole gamma function to the top and leaves the bodies untouched.

git init blame-demo
cd blame-demo
git config user.name Original
git config user.email original@example.com

for name in alpha beta gamma; do
  printf 'function %s() {\n' "$name"
  printf '  check()\n  check()\n  check()\n  check()\n}\n'
  if [ "$name" != gamma ]; then printf '\n'; fi
done > steps.js
git add steps.js
git commit -m 'Add steps'

{ tail -n 6 steps.js; printf '\n'; head -n 13 steps.js; } > reordered.js
mv reordered.js steps.js
git -c user.name=Reorder commit -am 'Move gamma'

In steps.js, gamma now comes first and alpha starts on line 8.

git blame --diff-algorithm=myers -L '/^function alpha/,+1' -- steps.js
git blame --diff-algorithm=histogram -L '/^function alpha/,+1' -- steps.js

The -L argument selects the declaration alone. Myers credits Reorder for that line. Histogram credits Original and marks the first commit with a caret because it is a boundary.

Inspect the candidate commit

Histogram can use low-occurrence lines as anchors when it compares revisions. A named declaration gives it a more distinctive anchor than the repeated calls. The algorithm still has to pick an alignment, so a result on alpha says little about the result on gamma.

For a block moved within one file, the blame manual also describes -M. It looks for moved lines within the file and has a minimum score based on matching alphanumeric characters. Use -C when you need to look for a move across files, starting with other files changed in the same commit.

If the two algorithms disagree, open the suspect commit with git show and check what it did to the function. The change you care about might be a one-line edit in the same commit as the move. Read that hunk before you attribute the behavior to either author.