DEV Community

jmau111⚡⚡⚡
jmau111⚡⚡⚡

Posted on

Git: debugging

Git can speed up debugging. When you have a regression or a bug in production despite CI/CD checking and other tests, identifying the potential bad commit(s) is a good approach.

The code used to work fine before recent deployments, so there's a reasonable chance to fix the situation by inspecting the Git history.

Sometimes, it's way more deeper than that, but let's assume a simple case here.

The manual approach

Simply checkout some sha or tag:

git checkout {LAST_TAG}
git checkout {SOME_SHA}
Enter fullscreen mode Exit fullscreen mode

You'll see if that works on your testing environment.

Note that many dev teams have automated scripts to rollback any bad release, but if that's not the case, you can still do it manually.

blame it!

Another approach consists of using git blame to mark any suspicious file, for example:

git blame -C -L 111,156 myscript.py
Enter fullscreen mode Exit fullscreen mode

Note that you can even restrict your annotation to specific lines and use -C for better analysis (especially if you are moving snippets of code from other files).

bisect it!

Binary search allows marking good and bad states to narrow down your researches and ultimately identify the bad commit:

git bisect start
git bisect bad # "broken state"
git bisect good {TAG} # last known "good state"
Enter fullscreen mode Exit fullscreen mode

Why doing that? The goal is to save time, as bisect will automate some checks (especially commits halfway between good and bad), allowing you to quickly determine "where" (I should probably say "when" instead) the bad commit probably is.

It's very handy when you have lots of commits to inspect.

Git can even run custom scripts during the inspection:

git bisect run test.sh
Enter fullscreen mode Exit fullscreen mode

Source: Git documentation

To close the inspection mode run git bisect reset.

Wrap up

Whether you use bisect or not, Git can speed up debugging, which is beneficial when you have an emergency in production.

Top comments (2)

Collapse
 
efrenmarin profile image
Efren Marin

The more I work with different devs, the more it's apparent that a lot of people struggle with using and understanding git. I think understanding some basics and trying them out is the best way to understand how they work.

I haven't had the opportunity to use bisect so this article might just be the push to try it out if I'm in that position again. Thanks for the reminder!

Collapse
 
jmau111 profile image
jmau111⚡⚡⚡

as I said in the post, you can also do it manually if you're not comfortable with bisect, but it can help you to narrow down results and save some time.