patterngitTip
git bisect: binary search to find the commit that introduced a bug
Viewed 0 times
git bisectfind regressionbinary searchbug introductionbisect run
Error Messages
Problem
A bug exists in the current codebase but wasn't present months ago. Manually checking out commits to find the regression is tedious and slow.
Solution
Use git bisect to binary-search through history:
git bisect start
git bisect bad # current HEAD is broken
git bisect good v2.1.0 # last known good state
Git checks out the midpoint commit. Test it, then mark:
git bisect good # if this commit works
git bisect bad # if this commit is broken
Repeat until Git identifies the first bad commit. When done:
git bisect reset
Automate with a script:
git bisect run npm test -- --testNamePattern="payment flow"
git bisect start
git bisect bad # current HEAD is broken
git bisect good v2.1.0 # last known good state
Git checks out the midpoint commit. Test it, then mark:
git bisect good # if this commit works
git bisect bad # if this commit is broken
Repeat until Git identifies the first bad commit. When done:
git bisect reset
Automate with a script:
git bisect run npm test -- --testNamePattern="payment flow"
Why
Binary search finds the bad commit in O(log n) steps. For 1000 commits, that's at most 10 checkouts. Bisect manages the checkout logic automatically.
Gotchas
- The test used in
git bisect runmust exit 0 for good, non-zero for bad (125 means 'skip this commit') - Use
git bisect skipif a commit doesn't compile or is otherwise untestable - Bisect works on the working tree — ensure no local changes before starting with
git stash
Code Snippets
Finding a regression with git bisect
# Manual bisect
git bisect start
git bisect bad HEAD
git bisect good v3.0.0
# Test and mark each checkout
git bisect good # or: git bisect bad
# When done
git bisect reset
# Automated bisect with a test script
git bisect start
git bisect bad HEAD
git bisect good v3.0.0
git bisect run ./scripts/test-regression.shContext
When a regression was introduced at an unknown point in history and you need to find the exact commit
Revisions (0)
No revisions yet.