Reading Code to Find BugsLesson 2.5
How to use git blame and git log to find when a bug was introduced
git blame, git log, git bisect, commit history investigation, blame workflow
Git as a Debugging Tool
When a bug exists in code you did not write, or appeared after a series of changes, git history is your roadmap. Three commands cover most cases: git blame, git log, and git bisect.
git blame and git log
# Find who last changed each line of a file
git blame src/cart.js
# See commits that touched a specific function
git log -p --all -S 'applyDiscount' src/cart.js
# Find commits that changed a specific line range
git log -L 42,55:src/cart.js
git bisect: Binary Search for Bugs
If you know a commit where the code worked and a commit where it broke, git bisect performs a binary search through history to find the exact commit that introduced the fault.
git bisect start
git bisect bad # current commit is broken
git bisect good v2.1.0 # this version worked
# Git checks out midpoint commit
# You test, then run:
git bisect good # or: git bisect bad
# Repeat until git identifies the fault commit
git bisect reset # restore HEAD when done
Once bisect identifies the commit, read that commit diff. The fault is in those changed lines. git show with the commit hash shows the full diff.
