Suppose I have this project with 5 commits. You can clone it from here.
Say, there’s a regression bug in the master branch but a lot has been added to
master after the feature was first inroduced. How would I go debugging this? Which commits break it?
Usually, we would go manually and see which commit would possibly do this but if the project is large and active, it’s a quite troulesome process.
Luckily, we have
git bisect for that.
- Go to the project and issue
git bisect start
- Mark the bad commit by
git bisect bad <commit-id>. You can ommit the commit id if you’re already on it.
- Mark the good commit by
git bisect good <commit-id>.
- Add the tests for the regression bug. In this case it’s
I’m gonna go ahead and add a fail test case for the regression bug I’m having. You may argue why not add test in the first place? Well, this is just an example so I have 0 test for it.
In actual scenario, you can have an extensive test cases but still can miss an edge case. In that scenario, you will need to add that fail test for that edge case here.
// test.js const assert = require('assert') const add = require('./add') assert(add(1,2) === 3, 'one plus two should equal to three')
git bisect run <test-command>. In this case, it would be
git bisect run node test.js.
git bisect logand see the result. It would look like this.
# bad: [addb180af061bbfbad298cd6a9ad2110df0f873e] feat: add multiply git bisect bad addb180af061bbfbad298cd6a9ad2110df0f873e # good: [7688391b1a9b133bef92198e376c9f5979260ade] feat: add add() function git bisect good 7688391b1a9b133bef92198e376c9f5979260ade # bad: [d504f94f1d71c93deb9d9bbdf87bfe333bbecff6] chore: add readme git bisect bad d504f94f1d71c93deb9d9bbdf87bfe333bbecff6 # bad: [d516aaf29331953382a8558f013b683427d7a390] feat: add subtract() function git bisect bad d516aaf29331953382a8558f013b683427d7a390 # first bad commit: [d516aaf29331953382a8558f013b683427d7a390] feat: add subtract() function
There you can see which first commit makes the test fail is
[d516aaf29331953382a8558f013b683427d7a390] feat: add subtract() function.
git bisect resetwhen you’re done.