This is a post for appreciating “git bisect” and how it can be one of the most powerful tool to find out root cause of a broken build or a broken branch.
Here is simple example of how “git bisect” can be used to find a bad commit.
Lets assume that we have a git repository which has hundreds of commits and currently the HEAD of the master branch is broken i.e. has a bug. Our objective is to find out which commit introduced the bug in to the code base.
Before starting the git bisect process we need to know a couple of things. First we need know a good commit i.e. a old commit at which code worked as expected. This is not very difficult to find out as it is most likely the last release of the code. Also we need to know the steps to test the code and reproduce the issue. It will help us to find out if certain commits are good or bad during the git bisect process.
Git bisect uses binary search algorithm between the good and bad commit to find out the commit that introduced the bug.
Here are the commands to start the git bisect work flow. Lets call the current HEAD commit as “original HEAD”
$ git bisect start $ git bisect bad $ git bisect good <commit ID> Bisecting: 130 revisions left to test after this (roughly 4 steps)
Once the above commands are executed, git bisect will change the HEAD to the middle of the commits between the “original HEAD” and good commit. Read about binary search if you want to know how it decides to which commit the HEAD needs to be moved.
At this point we are expected to test the code and find out if we are able to reproduce the issue. After the testing we need to again tell git bisect if it is bad commit (see below) i.e. we are able to reproduce the issue else it is a good commit.
$git bisect bad Bisecting: 65 revisions left to test after this (roughly 3 steps)
$ git bisect good Bisecting: 65 revisions left to test after this (roughly 3 steps)
We need to continue the process few times and git bisect will give you the commit which introduced the issue/bug.
In my experience I always get to the commit (which introduced the issue) in 4 to 5 steps of git bisect. Which I think is an awesome thing.
So go ahead and try git bisect if you have not tried it yet and do not forget to use it when you broken builds.