Debugging with Git Bisect
Debugging can be hard. Git bisect can help. It'll help you narrow down where to look for the problem.
The Scenario
The impossible has happened. You have written a bug. Your program is broken, but your soul is not. You can seem the symptoms of your bug when you run your code.
How did this happen? Some daft misstep in the past has brought you to this point. When was that point?
Git bisect will be our shrink and show us when things went awry.
The Concept
Bisecting is going to incrementally cut the problem area in half until we find the commit that introduced the problem.
We identify a good commit and a bad commit. Likely, right now we're having a bad time; that's why we're debugging. Then we peek back far enough in the code history until we find a good point in time. Often we overshoot, but that's ok. We'll lean on git-bisect to do the hard work.
So, git log
, and identify what commits you'll try as your "good" and "bad" points. (alternatively, you can use "old" and "new" points; see man git-bisect
).
The Command
To begin a bisect session:
git bisect start
To mark the current commit as "bad":
git bisect bad
To mark some past commit as "good":
git bisect good d45de53
Then you're off to the races.
The Debugging
Once you mark "good" and "bad" points, you'll get some output like:
Bisecting: 1 revision left to test after this (roughly 1 step)
[42e0ca79bab0aba9b43f5c179909996e30c588ac] simple test
This means that git-bisect has checked out a commit that you now need to test and decide if it's good or bad. Maybe that means literally running your test suite. Or maybe manually running code and seeing some symptom.
If you see the (bad) symptom, you run git bisect bad
on this commit too.
If you don't see the symptom (good state), you run git bisect good
on this commit.
Eventually, git-bisect will be able to narrow in and show you the commit that introduced the bad state, something like:
42e0ca79bab0aba9b43f5c179909996e30c588ac is the first bad commit
commit 1cd4bcbc0bd9f597da6c058d78ae1fb8f73480e2
Author: jaketrent
Date: Tue May 23 07:56:00 2023 -0600
accidentally broke empty test
package.json | 3 ++-
src/index.js | 4 +++-
src/index.test.js | 4 ++++
3 files changed, 9 insertions(+), 2 deletions(-)
This tool can be helpful in narrowing in more quickly on where you've created your bugs.