Git & GitHub - Git Bisect
Using git bisect to find bugs
Git bisect is a powerful tool that helps you identify the commit that introduced a bug by performing a binary search through your commit history. This guide covers how to use git bisect to efficiently locate problematic commits.
Key Points:
- Git bisect performs a binary search to find the commit that introduced a bug.
- Mark a known good commit and a known bad commit to start the bisect process.
- Git bisect helps narrow down the commit range by repeatedly testing commits.
Starting a Bisect Session
Step 1: Mark the Bad Commit
Start the bisect session by marking the commit that introduced the bug as "bad":
# Start bisect and mark the bad commit
$ git bisect start
$ git bisect bad COMMIT_HASH
Step 2: Mark the Good Commit
Mark a known good commit where the bug did not exist:
# Mark the good commit
$ git bisect good COMMIT_HASH
Step 3: Bisecting
Git will now checkout a commit halfway between the good and bad commits. Test this commit to see if the bug is present or not:
# If the bug is present in the current commit
$ git bisect bad
# If the bug is not present in the current commit
$ git bisect good
Repeat the process of marking commits as good or bad based on whether the bug is present until Git identifies the first bad commit.
Completing the Bisect Session
Once Git identifies the first bad commit, the bisect session is complete:
# Reset bisect to return to the original HEAD
$ git bisect reset
Git will output the commit hash of the first bad commit, allowing you to review and address the problematic changes.
Automating Bisect with a Script
You can automate the bisect process by using a script to test each commit:
# Example bisect script (test_script.sh)
#!/bin/bash
# Return 0 if the commit is good, non-zero if the commit is bad
if make &>/dev/null; then
exit 0
else
exit 1
fi
# Run git bisect with the script
$ git bisect start
$ git bisect bad COMMIT_HASH
$ git bisect good COMMIT_HASH
$ git bisect run ./test_script.sh
Best Practices
Follow these best practices when using git bisect:
- Choose Clear Good and Bad Commits: Ensure you accurately identify commits where the bug is present and absent.
- Automate Tests When Possible: Use scripts to automate the testing process for consistent results.
- Review Changes Carefully: Once the bad commit is identified, review the changes carefully to understand and fix the bug.
Summary
This guide covered how to use git bisect to find bugs, including starting a bisect session, marking good and bad commits, automating the process with scripts, and best practices. Git bisect is a powerful tool that helps you efficiently locate problematic commits, saving time and effort in debugging.