Pagine

Friday 9 June 2017

How to use git bisect

The git bisect command allows you to run a binary search through the commit history to find a commit that has an issue. For example, you pulled the last commits and the website isn't working anymore. You know that before the last pull everything was okay. So you have to find the commit ID before it crashes and the last ID after the pull:
$ git bisect start
$ git bisect bad <commit_id_after_pull>
$ git bisect good <commit_id_before_pull>
Now, the bisecting loop begins and Git will check for an alternative commit.
Reset the given commit and tell Git whether the website is working:
$git bisect <bad_commit_id>
Git will search again and again to find which commit crashed the website:
$ git show <commit_id>
Instead of trying to locate a bug inside all your files, you have a shortened list of files.

How to reset a git commit via bash script 

If you don't want to reset to a given commit and test your software, you can create a bash script and tell Git to use it. The script has to return 0 if the condition is fulfilled, and nonzero if it isn't.
check_file.sh

#!/bin/bash
FILE=$1
If [ -f $FILE];
then
    exit 0;
else
    exit 1;
fi
Now it's time to run git bisect to specify the last 10 commits:
$ git bisect start HEAD HEAD~10
$ git bisect run ./check_file.sh MyFile.java

Bisect algorithm

The algorithm used by git bisect always returns the commit that is at the middle position of the array.
In the following diagram, you will see how the algorithm found the good commit in three steps:
  1. The Commit6 option is selected by Git. After checking it, you tell Git that it's good.
  2. Git reduces the array because if Commit6 is good, then every commit between Commit1 and Commit6 is good too.
  3. Then Git asks you to test Commit9, and you say that it's good too.
  4. So the error can only be inside Commit10 and Commit11.

No comments:

Post a Comment