Git Binary Search
It sometimes happens that we test the code after more than a few commits and then realize there is something wrong with the state of the code. To find the root cause, one needs to go back in the git history one commit at a time and try to find the commit that causes the problem, but that's usually not easy:
- The commits might not have the best messages,
- There might be just too many commits.
This is why git comes with a binary search tool to help you find the "bad" commit that caused the issue.
Starting the Search
To start the search, enter the following command into your terminal:
git bisect start
Then you need to state that your current state of the code is bad:
git bisect bad
And then point out to a good version of the code:
git bisect good v1.2.0
The version used in this command can be anything:
- A tag
- A branch name
- A commit hash
After this step, git moves to a new version of the code (a version between the good and the bad version). You can look into the code (or probably run the tests) and decide if this version is good or bad. In the former case, you want to tell git that it's a good version:
git bisect good
Or if it's not, tell git that:
git bisect bad
After annotating the version as either good or bad, the binary search moves to another version so that you can test again. This process continues until you find the root cause of the problem.
Final Words
Although git has binary search capabilities, if you should use it, it usually means that there is something wrong with the coding processes. Try to:
- Have automated tests that run for every pull request
- Write good commit messages
- Have small changes per each commit / pull request
Checkout my other Git-Weekly issues to learn more about these topics.