Git bisect

How to quickly find an error by bisecting the Git commit log.

One good thing about repeatable builds - you can repeat them from the source code. Imagine if a software app you are building worked at some point in time. Then one day you came back and the build is broken. Some new change has introduced an error. You can find the breaking commit by building and testing working commit + 1 change, working commit + 2, etc.

Linearly progressing through the commits is slow. You might as well bisect the changes to quickly discard half of changes. At each step, pick the middle commit, test it, and if it works, then you have just eliminated half of the work!

1
2
3
4
5
6
7
8
9
10
11
commit    step 1     step 2
broken
...
... test again
...
...
four tests work!
three (good)
two (good)
one (good)
good (good)

You do not have to remember Git ids or keep track of the commit ranges. There is a built-in command git bisect that keeps track of these details.

How to use Git bisect

Find a commit that works for sure. You can even pick something far in the past. Bisect will discard half of the commits at each iteration, it will converge quickly even if the starting commit "overshoots" by a large number of commits .

1
2
git checkout 8468a7b
# run you test, ok works!

Switch to the root folder of your Git repository

1
cd $(git rev-parse --show-cdup)

Mark the current commit as good

1
git bisect good

Switch to the last commit and mark it as bad

1
2
git checkout master
git bisect bad

The Git tool immediately checks out a commit in the middle of the good - bad range. Test this commit and mark it again to eliminate half of commits

1
git bisect good

Repeat the process until you converge on the bad commit!

To cleanup the Git state after the bisection, run git bisect reset command.