Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Find Bugs With git bisect

DZone 's Guide to

How to Find Bugs With git bisect

Here's how to narrow down your bad commits with git bisect so you can find the one that introduced a bug.

· Open Source Zone ·
Free Resource

In this post, I’m going to talk about git bisect and how it helps finding buggy commits or those that don’t meet some kind of requirement. By using it, git will suggest commits where a breaking change might be introduced. Let’s see how we can use it.

Let’s say we have a Go project in a git repo with this history:

$ git log --oneline
da86694 Change 4
081944f Change 3
eb62d12 Change 2
1d5d4fe Change 1
2d07264 Release 2.0


2d07264 Release 2.0  is working fine, but some tests are not passing in  da86694 Make change 4.

Let’s use git bisect to find the breaking commit.

First, we inform git of a "good" and a "bad" commit, so it can start bisecting between those boundaries.

$ git bisect start
$ git bisect good 2d07264 //Release 2.0
$ git bisect bad da86694 //Change 4
Bisecting: 1 revision left to test after this (roughly 1 step)
[eb62d12] Change 2


git suggests  eb62d12 Change 2  as the first candidate of a breaking commit. By default, git bisect will check out the suggested commit. Let's see if the tests are passing in this commit:

$ go test algorithm_test.go
--- FAIL: TestAlgorithm (0.45s)
FAIL _/home/johndoe/algorithm 0.451s


Tests are not passing. Indeed, this commit contains buggy code but it does not necessarily mean this is where it was introduced. Thus, we need to keep looking for more candidates. To do so, we mark this commit as “bad” and git will move on:

$ git bisect bad
Bisecting: 0 revisions left to test after this (roughly 0 steps)
1d5d4fe Change 1


git suggests a new candidate:  1d5d4fe Change 1 . Again, after running tests on this commit, we get an error. We mark it as bad again:

$ go test algorithm_test.go
--- FAIL: TestAlgorithm (0.45s)
FAIL _/home/johndoe/algorithm 0.451s
$ git bisect bad
1d5d4fe Change 1


After that, git has inferred that  1d5d4fe Change 1 is the root bad commit since the previous one `2d07264 Release 2.0` was marked as good. We are done.

This time, it took just two bisecting operations. In the worst case, it would take a maximum of log(n) bisecting operations where n is the number of commits between the good and the bad one.

Topics:
git ,bug detection ,open source ,git commands ,git bisect ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}