Viewing changes: diff, log and blame

Intermediate

Introduction

Before committing, you want to see exactly what you are about to save; when a bug appears, you want to know what changed and who changed it. Git answers these questions with diff, log, show and blame. All of them rely on one algorithm, comparing two lists of lines, which you will write in this lesson.

How it works

A diff lists the lines of the old version and the new version: - for a line that was removed, + for a line that was added, and a space for an unchanged line kept as context. Changes are grouped into hunks, each starting with a header such as @@ -3,4 +3,5 @@: from line 3, 4 old lines became 5 new ones.

Which versions are compared depends on the command:

git diff                 # working tree against the index: changes not staged yet
git diff --staged        # index against HEAD: what the next commit will contain
git diff HEAD~1 HEAD     # two commits
git diff --stat          # a summary per file instead of the lines
git log --oneline        # one line per commit
git show abc1234         # one commit: its message and its diff
git blame app.py         # who last changed each line, and in which commit

How a diff is computed. The goal is to describe the change with as few removed and added lines as possible, which means keeping as many lines as possible. The lines kept form the longest common subsequence (LCS) of the two versions: the longest list of lines appearing in both, in the same order. A table L[i][j] holds the length of the LCS of the old lines from i onwards and the new lines from j onwards; it is filled from the end:

  • if old[i] equals new[j], L[i][j] = L[i + 1][j + 1] + 1;
  • otherwise L[i][j] = max(L[i + 1][j], L[i][j + 1]).

Walking from the start, equal lines are kept; otherwise we remove old[i] if that loses nothing (L[i + 1][j] ≥ L[i][j + 1]) and add new[j] if not. Git uses a faster algorithm (Myers' diff) with the same goal, so its output may group equal-cost changes differently.

Blame runs diffs through the history: a line keeps the commit that introduced it as long as each later diff keeps it unchanged.

Example

def diff(old, new):
    n, m = len(old), len(new)
    L = [[0] * (m + 1) for _ in range(n + 1)]
    for i in range(n - 1, -1, -1):
        for j in range(m - 1, -1, -1):
            L[i][j] = L[i + 1][j + 1] + 1 if old[i] == new[j] else max(L[i + 1][j], L[i][j + 1])
    out, i, j = [], 0, 0
    while i < n or j < m:
        if i < n and j < m and old[i] == new[j]:
            out.append(" " + old[i])
            i, j = i + 1, j + 1
        elif j == m or (i < n and L[i + 1][j] >= L[i][j + 1]):
            out.append("-" + old[i])
            i += 1
        else:
            out.append("+" + new[j])
            j += 1
    return out


old = ["def total(prices):", "    s = 0", "    for p in prices:", "        s += p", "    return s"]
new = ["def total(prices, tax=0):", "    s = 0", "    for p in prices:", "        s += p", "    return s * (1 + tax)"]
lines = diff(old, new)
for line in lines:
    print(line)
added = sum(1 for line in lines if line.startswith("+"))
removed = sum(1 for line in lines if line.startswith("-"))
print(f"1 file changed, {added} insertions(+), {removed} deletions(-)")
Open in compiler

Line by line

  1. L is filled backwards, so each entry knows the best that can still be kept from that point.
  2. The walk keeps equal lines, and prefers removing an old line when that does not shorten the common part.
  3. The function signature changed, so its old line is removed and the new one added.
  4. The three middle lines are the same in both versions and appear as context.
  5. The summary counts insertions and deletions, like git diff --shortstat.

Expected result

-def total(prices):
+def total(prices, tax=0):
     s = 0
     for p in prices:
         s += p
-    return s
+    return s * (1 + tax)
1 file changed, 2 insertions(+), 2 deletions(-)

In the real world

Code review on GitHub is reading diffs: every pull request shows its changes this way. git bisect finds the commit that introduced a bug by testing commits in a binary search, and git blame (shown in GitHub's "Blame" view) leads to the commit and discussion behind a line. The same LCS idea underlies tools that compare documents, DNA sequences and spreadsheets.

Common mistakes

  • Running git diff and seeing nothing after staging: staged changes need git diff --staged.
  • Reading a changed line as an edit: a diff shows it as one removal plus one addition.
  • Blaming the person who last touched a line for a bug that came from elsewhere; read the commit first.
  • Ignoring whitespace changes that make a diff noisy; git diff -w hides them.

Best practices

  • Review git diff --staged before every commit.
  • Keep commits small so their diffs are easy to read.
  • Use git log -p path to see the history of one file with its diffs.

Summary

A diff shows removed lines with -, added lines with + and context with a space, grouped into hunks. git diff and git diff --staged compare the working tree, the index and HEAD, while log, show and blame explore history. A line diff keeps the longest common subsequence of the two versions and reports everything else as removals and additions.

Quick check

1. In a diff, what does a line starting with - mean?
2. Which command shows what the next commit will contain?
3. What does a line diff keep unchanged?
4. What does git blame show?

Key takeaways

  • In a diff, lines starting with - were removed, + were added, and a space means unchanged.
  • git diff compares the working tree with the index; git diff --staged compares the index with HEAD.
  • A line diff keeps the longest common subsequence of lines and reports the rest as removals and additions.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.