DevOps
Git
Git Bisect

Git Bisect

git bisect is the ultimate debugging tool for regressions. It uses a Binary Search algorithm to find the exact commit that introduced a bug or a performance drop in your project history.


🔍 How it Works (Binary Search)

If you have 1,000 commits between a "good" state and a "bad" state, git bisect will find the culprit in about 10 steps.

  1. It checks out a commit in the middle of the range.
  2. You test the code.
  3. If the bug is there, the bug was introduced in the first half.
  4. If the bug is NOT there, it was introduced in the second half.
  5. Repeat until only one commit remains.

1. The Manual Workflow

To start a hunt manually:

# 1. Initialize
git bisect start
 
# 2. Define the 'Bad' (now) and 'Good' (past) points
git bisect bad
git bisect good v1.0.0
 
# 3. Git checks out a middle commit. Run your tests.
# If it's broken:
git bisect bad
# If it's working:
git bisect good
 
# 4. Repeat until Git says "abcd123 is the first bad commit"
 
# 5. Return to your original branch
git bisect reset

2. The Pro Way: Automated Bisect

If you have a test script (or a single command like npm test) that exits with 0 for success and non-zero for failure, you can automate the entire search!

git bisect start
git bisect bad HEAD
git bisect good v1.0.0
 
# Git will now run the test on every step automatically
git bisect run npm test

[!TIP] This is incredibly powerful for catching performance regressions or subtle UI bugs that can be caught by an automated selector.


3. Best Practices

  • Atomic Commits: Bisect works best when your commits are small. If a commit changes 50 files, Bisect will find the commit, but you'll still have a lot of code to look through.
  • Linear History: Bisect is easiest to reason about in a linear (rebased) history, though it works with merges as well.
  • Save your Script: If you're hunting a hard-to-reproduce bug, write a small shell script to detect it and use bisect run.

[!IMPORTANT] Don't Forget to Reset Always run git bisect reset when you're finished to exit the "Bisecting" state and return your HEAD to your original branch.