Member-only story
Debug your code using git bisect
What’s git bisect?
A few days ago, I first learned about git bisect from this Tweet:
From the very first look of it, I was like — whoosh! This could be awesome. From the main
page, it says this -
TLDR; git-bisect — Use binary search to find the commit that introduced a bug
So, that’s kind of our day-to-day software engineering need, amirite? In the middle of our development of a particular feature, somehow we stumble upon a situation where an existing code fragment is broken, but it shouldn’t because we didn’t touch (or actually couldn’t remember) any related codes! What do we do then? Personally, I check out particular commits that I feel suspicious or check the file changes, but that’s a hell lot of work to actually narrow down the bug. To automate this process, we can use git bisect.
This command uses a binary search algorithm to find which commit in our project’s history introduced a bug. First, we have to tell which one is the “bad” commit that is known to contain the bug, most of the cases that’s where the HEAD is, but we can specify a commit hash also! Then, we have to mark a “good” commit where we specifically know everything was working fine. So, if you can remember the binary-search technique, we are marking the low and high indexes here! Then git bisect picks a commit between those two endpoints and asks us whether the selected commit is “good” or “bad”. It continues narrowing down the range until we find the exact commit that introduced the problem.
In fact, git bisect can be used to find the commit that changed any property of our project; e.g., the commit that fixed a bug, or the commit that caused a benchmark’s performance to improve. To support this more general usage, the terms “old” and “new” can be used in place of “good” and “bad”, or we can choose our own terms.
How to use git bisect?
First, we have to start a bisect session and mark the good and bad commit hashes i.e. defining the…