How to use Git Bisect to Find the Commit that introduced a Bug
What is Git Bisect ?
Git Bisect — use binary search to find the commit that introduced a bug.
Git Bisect is a handy tool used for debugging, it uses Binary Search to go through the previous commits to find out the exact commit that introduced the regression/bug in the code.
How to use Git Bisect
TL;DR version:
Start - Git Bisect you’ll need to provide it with a last known Good commit and a Bad commit. ( you can ignore the SHA for bad commit if the current HEAD is corrupted )
$ git bisect start
$ git bisect bad
$ git bisect good <sha_of_goodcommit>
Git Bisect has now begun and you’ll see a message that tells you roughly how many steps are remaining until you find the bad commit.
Bisecting: X revisions left to test after this (roughly Y steps)
Repeat - On every step you’ll need to tell git whether the bug still persists.
If Bug still persists, $ git bisect bad
If Code works fine, $ git bisect good
When all the steps are done, git will show the message with the SHA of the first bad commit
<sha_of_badcommit> is the first bad commit
Done - After you found the commit that introduced the issue/bug you can reset the git bisect using
$ git bisect reset
Longer Version:
Let’s understand how Git Bisect works visually,
Consider that there were 5 commits on the branch and one of the commit (say Commit 4 ) has introduced a breaking change in the code, when we start Git Bisect our initial state would be like this
Then, git automatically moves to a commit between our good and bad versions using binary search, we will then have to check whether this new state still has buggy code or not
If still buggy - $ git bisect bad
If it’s not - $ git bisect good
We repeat this process until we find the first commit that introduced the breaking change
Now that we’ve finally found the breaking commit, we can revert our code back to it’s original latest commit by
$ git bisect reset
which brings it back to Initial state ( as represented in git bisect figure — 2 )
If you have test script which can tell if the current source code is either good or bad then you can use $ git bisect run <script_file>
command.
Learn more about Git Bisect and its arguments from here.