Skip to content

Lesson 4 of 28Git in a team

Git Archaeology: Bisect, Blame and Reflog

Find out why code exists, which commit broke it, and how to get back work you thought you had lost, using log, blame, bisect and the reflog.

21 min read0/4 questions

It is Thursday afternoon and support says checkout totals are wrong by a few pence on some orders. Nobody remembers changing the pricing code, the release went out three days ago with 140 commits in it, and the person who wrote the function left last year. Half an hour later a teammate messages you in a panic: they ran git reset --hard on the wrong branch and a day of work has vanished. Both problems have the same answer. Git keeps far more history than most people use, and a few commands turn it from a backup into an investigation tool. This lesson covers how to ask the history why a line exists, how to let Git find the breaking commit for you, and how to get back work you think you have lost.

Ask the history why

When you meet a strange line, the question is rarely "who wrote this?". It is "what problem were they solving?". The commit message, the diff around it and the pull request it came from usually answer that. Your job is to find the right commit quickly. These are the commands that do it, in rough order of how often you will reach for them:

git log -p --follow checkout.py     # every change to this file, with diffs, across renamesgit show 512bb5a                     # one commit: message, author, full diffgit log -S 'round(' --oneline        # commits that added or removed the text round(git log -G 'round\(' --oneline       # commits whose changed lines match a regexgit log -L :total:checkout.py        # the history of one function, diff by diff

--follow matters more than it looks. Without it, git log checkout.py stops at the commit that renamed cart.py to checkout.py, and the interesting history is hidden on the other side of the rename. In the practice repo for this lesson, the plain log showed one commit and the --follow log showed all three.

The two pickaxe options are the real power tools. -S 'text' finds commits where the number of occurrences of that text changed: it was added or removed. That is perfect for "when did we start calling round?". -G regex finds commits where any added or removed line matches the regex, even if the count did not change. So -G also catches a commit that only reformatted a line containing round(, which is noise when you hunt for an origin and gold when you hunt for every edit.

git log -L :total:checkout.py asks Git to track one function by name and show each commit that changed it, with only that function's part of the diff. For a long file with a busy history, it cuts an hour of scrolling to a minute. You can also give a line range, such as -L 40,60:checkout.py.

Predict the outputShell

Here is the history of checkout.py, oldest at the bottom. Commit d2de348 changed round(sum( to round( sum( on one line. Which short hashes does the command print? List them top to bottom, one per line.

$ git log --oneline
d2de348 Edit line with round
8b63ca1 Format: single quotes
d9c6b67 Rename cart module to checkout
512bb5a Round cart total for display
9998897 Add cart total

$ git log -S 'round(' --oneline
Need a nudge? Hints walk you through it.

Blame without being fooled

git blame file shows, for every line, the last commit that touched it. It is the fastest way from a line to a commit, but the last commit to touch a line is often not the one that matters. Three things fool it, and each has a fix.

  • Whitespace changes. Someone reindented the block. git blame -w ignores whitespace when deciding who changed a line.
  • Moved or copied code. Someone moved the function into util.py, so every line blames the move. -C looks for lines moved from other files changed in the same commit; -C -C also looks in files that existed when the new file was created. In the practice repo, plain blame on a copied function blamed the copy commit, and git blame -C -C util.py traced each line back to cart.py and the original commits.
  • Formatting commits. The team ran a formatter over the whole codebase. Now every line blames "Run Black on everything". List those commits in a file and tell blame to skip them:
# one full commit hash per line; lines starting with # are commentsecho "# Format: single quotes" >> .git-blame-ignore-revsgit rev-parse 8b63ca1 >> .git-blame-ignore-revs          # writes the full hashgit add .git-blame-ignore-revs && git commit -m "Ignore formatting commit in blame"git config blame.ignoreRevsFile .git-blame-ignore-revs   # each clone, oncegit blame checkout.py                                     # now skips the formatter

GitHub's blame view reads a .git-blame-ignore-revs file at the root of the repo automatically, so committing it helps everyone who browses the code online, too. Add one in the same pull request as any mass reformat. It is one of the small things that makes a senior engineer's teammates grateful.

Once blame gives you a hash, run git show <hash> and read the message. If the team squash-merges, the message usually links the pull request, and the PR discussion is often where the real reason lives. "Blame" is a poor name: you are looking for context, not a culprit. If the author is still around, a short "I am changing X, and I see you added it in March for Y, is Y still a concern?" is a normal, welcome question.

Bisect: binary search on history

Sometimes reading is not enough. You know the bug exists now, you know it did not exist in last month's release, and there are hundreds of commits in between. git bisect does a binary search: it checks out the commit halfway between a known good and a known bad commit, you test it, and it halves the range again. Each answer throws away half the suspects.

git bisect startgit bisect bad                  # the current commit has the buggit bisect good v2.3.0          # this release did not# Git checks out a commit in the middle. Test it, then say:git bisect good                 # or: git bisect bad# ...repeat until Git prints "<hash> is the first bad commit"git bisect reset                # go back to where you started

You can also give both ends at once: git bisect start HEAD v2.3.0. If a commit cannot be tested at all (it does not build for an unrelated reason), git bisect skip asks Git to pick a nearby commit instead.

Bisecting 13 commits
c0
0
↑good
c1
1
c2
2
c3
3
c4
4
c5
5
c6
6
c7
7
c8
8
c9
9
c10
10
c11
11
c12
12
↑bad

c0 is the old release (good). c12 is today (bad). The breaking commit is somewhere in c1 to c12.

1/5

That is exactly the run from the practice repo for this lesson, where c6 was a commit that wrapped the cart total in round(). The simulation below repeats the search and shows why bisect scales so well: the number of tests grows with the logarithm of the number of commits.

Python
import math def bisect(commits, is_bad): # commits[0] is known good, commits[-1] is known bad good, bad = 0, len(commits) - 1 tests = 0 while bad - good > 1: mid = (good + bad + 1) // 2 tests += 1 if is_bad(commits[mid]): bad = mid else: good = mid print(f"test {tests}: {commits[mid]} -> {'bad' if bad == mid else 'good'}") return commits[bad], tests history = [f"c{i}" for i in range(13)]culprit = 6 # the commit that broke checkoutfirst_bad, tests = bisect(history, lambda c: int(c[1:]) >= culprit)print("first bad commit:", first_bad, "after", tests, "tests") for n in [100, 1_000, 10_000, 100_000]: print(f"{n:>7} commits -> about {math.ceil(math.log2(n))} tests")
Output
Press Run (⌘ Enter) to see what happens.

Let a script do the testing

Testing by hand is fine for five steps and miserable for fifteen. git bisect run takes a command and runs it on each commit Git picks. The exit code is the answer: 0 means good, 1 to 127 means bad (except 125), 125 means skip this commit, and anything else aborts the bisect.

../check.sh
#!/bin/sh# Lives OUTSIDE the repo, so it exists on every old commit Git checks out.# make || exit 125                      # if a build step can fail, skip that commitpython -c 'from cart import total; assert total([{"price": 2.5, "qty": 3}]) == 7.5'
chmod +x ../check.shgit bisect start HEAD v2.3.0git bisect run ../check.sh# ... Git runs the script on each commit it picks ...# 512bb5ad5b6fe0ac60824f613730441601efdf82 is the first bad commitgit bisect reset

Two details catch people. First, keep the test script outside the working tree (or untracked), because Git checks out old commits where your new test file does not exist. Second, write a narrow test for the one bug. A full test suite will fail on old commits for unrelated reasons and send bisect down the wrong path.

Bisect is also the strongest argument for the commit habits in the next lesson. If every commit builds and does one thing, the first bad commit is a 20-line diff and the cause is obvious. If commits are "WIP" snapshots that do not compile, you skip half of them and land on a 900-line mixed commit. On teams that squash-merge, each commit on main is a whole PR, so bisect finds the PR. git bisect start --first-parent follows only the main line through merge commits, which helps on teams that keep merge commits.

Put it in order5 steps

Put an automated bisect session in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

The reflog: your safety net

Now the panicked teammate. They ran git reset --hard HEAD~2 and their two commits disappeared from git log. They are not gone. Every time HEAD or a branch moves, Git writes a line in the reflog: a local diary of where each ref pointed and why.

$ git reflog2b43beb HEAD@{0}: reset: moving to HEAD~2dc03091 HEAD@{1}: commit: Wire search to API28880f0 HEAD@{2}: commit: Add search box2b43beb HEAD@{3}: checkout: moving from main to feature$ git reset --hard 'HEAD@{1}'HEAD is now at dc03091 Wire search to API

HEAD@{1} means "where HEAD was one move ago". The quotes stop shells like PowerShell from reading the braces as syntax. Each branch also has its own reflog, git reflog show feature, where feature@{1} is where that branch pointed before its last move.

Losing and recovering two commits
ABCfeature

currentwaitingdone

feature points at C. B and C are a day of work.

1/4

The same trick undoes other accidents:

  • A rebase that went wrong. Before a rebase, reset or merge, Git saves the old tip in ORIG_HEAD, so git reset --hard ORIG_HEAD straight afterwards undoes it. If you have done other things since, use the branch reflog: git reset --hard 'feature@{1}' is where the branch was before the rebase rewrote it.
  • A deleted branch. git branch -D feature prints Deleted branch feature (was dc03091). Recreate it with git branch feature dc03091. Lost the terminal output? Deleting a branch deletes its own reflog, but HEAD's reflog still lists the commits you made on it.

Know the limits, because they are interview material. The reflog is local only: it is not pushed, and a fresh clone has an empty one. It records commits, not unsaved edits, so changes you never committed or stashed are not in it. And entries expire: by default after 90 days, or 30 days for entries no longer reachable from the branch, which is exactly the case after a hard reset. After that, git gc may delete the orphaned commits for good. Recover soon, not next quarter.

Quick check
A teammate force-pushed main and wiped out three commits that you had already pulled. They have no copy. Where is the best place to recover them?
Need a nudge? A hint rules out a wrong answer.

Lost stashes and dangling objects

A stash is a commit under the hood, so git stash drop or a mistaken git stash clear leaves it in the object database with nothing pointing at it. git fsck lists such dangling objects:

$ git stash dropDropped refs/stash@{0} (f7bc72d928c84371a9b19672d0af1a2cb0a1b851)$ git fsck --lost-founddangling commit f7bc72d928c84371a9b19672d0af1a2cb0a1b851$ git log --oneline --no-walk f7bc72df7bc72d On main: wip: login form$ git stash apply f7bc72d        # your changes are back

The drop message printed the hash, so if the terminal is still open you can skip fsck. --lost-found also writes each dangling object into .git/lost-found/. Even a file you only git add-ed and then lost to reset --hard shows up there as a dangling blob, and git show <hash> prints its content. This is why "stage it, even if you are not ready to commit" is a decent habit before anything risky.

The undo matrix

Most Git panic comes from not knowing which undo fits the situation. Sort it by where the mistake lives and whether anyone else has it yet.

SituationCommandRewrites history?
Unwanted edits in a file, not stagedgit restore fileNo (discards edits)
Staged a file by mistakegit restore --staged fileNo
Typo in the last commit, not pushedgit commit --amendYes, the last commit
Undo last commit, keep changes stagedgit reset --soft HEAD~1Yes
Undo last commit, keep changes unstagedgit reset HEAD~1 (--mixed, the default)Yes
Throw away commits and changesgit reset --hard <commit>Yes, and deletes edits
Undo a commit that is already on maingit revert <commit>No, adds a new commit

The rule behind the last row: once a commit is on a shared branch, do not rewrite it. git revert creates a new commit that applies the opposite diff, so everyone's history stays valid. Reverting a merge commit needs you to say which parent is the main line: git revert -m 1 <merge>. Without -m, Git refuses with "is a merge but no -m option was given".

Match the pairs0/5 matched

Match each situation to the right undo.

Choose an item, then its match on the other side.

Stash, or a second worktree

git stash is for short interruptions: put your half-done work aside, switch, come back.

git stash push -m "wip: login form"   # name it, or you will not know which is whichgit stash list                        # stash@{0}: On main: wip: login formgit stash pop                         # re-apply and remove from the listgit stash apply 'stash@{1}'           # re-apply but keep it in the list

pop removes the stash only if it applied cleanly. If it conflicts, the stash stays in the list and you resolve the conflict as usual.

For anything longer, such as an urgent production fix while your feature branch is mid-refactor, use a worktree instead. It is a second working folder attached to the same repo, on a different branch:

git worktree add -b hotfix/login ../shop-hotfix maincd ../shop-hotfix          # fix, test, commit, push, open the PRcd ../shopgit worktree remove ../shop-hotfix

Nothing is stashed, nothing is half-applied, and your editor, build cache and running dev server in the main folder are untouched. One branch can only be checked out in one worktree at a time, which stops you editing the same branch in two places by accident.

Key terms
pickaxe
git log -S and -G: search history for commits that added, removed or changed text matching a string or regex.
git blame
Shows the last commit that changed each line. Use -w, -C -C and an ignore-revs file to see past noise.
git bisect
A binary search through history to find the first commit where a test starts failing.
reflog
A local, expiring log of every position HEAD and each branch has pointed to. The main way to undo resets, rebases and deleted branches.
ORIG_HEAD
A ref Git sets to the old tip before a reset, rebase or merge, so you can jump straight back.
dangling commit
A commit no branch, tag or reflog entry points to, such as a dropped stash. git fsck finds them until garbage collection removes them.
worktree
An extra working folder attached to the same repository, checked out on a different branch.