简体   繁体   中英

How to find and restore “rewritten” git commits?

For some reason I have git repo with commits of code which were rewritten to its previous state. Like this:

  • initial code was "Hello world!" and it was committed in repo;
  • on some day it was changed to "Bye-bye world!" and it was committed in repo;
  • on some day later this code was reverted on HDD to its initial state ("Hello world!") and committed in repo.

I need to find somehow such commits. It can be not sequential commits but the commits which "rewrites" code to its previous state.

How can I do this?

You can use git bisect .

git-bisect
Find by binary search the change that introduced a bug

gitbisect is a tool to search and fund out in which commit your code was changed. Its very simple to use it and its very powerful as well.


How does bisect works?

Bisect simply go over the history log and perform a binary search.

a binary search or half-interval search algorithm finds the position of a specified input value (the search "key") within an array sorted by key value.

More about Binary search


Git bisect sample

// Start the bisect operation
git bisect start 

// mark the current as bad or good depends on the content of your given
// file. In your case since you want to find the commit who modified your
// code to "Hello world!" lets assume the current file is the bad state
git bisect bad 

// Assume 100 commits ago it was before your change (or give a sha if you
// know where its was ok last time
git bisect good HEAD~100

// Now git will split the history and start looping over it.
... do your tests and decide if its good or bad (check the file content)

How to automate the bisect ?

Adding the run flag which allow you to automate the search.
The run gets a script which is being executed on each checkout commit.

git bisect run my_script arguments


Bisect run exit codes:

Note that the script (my_script in the above example) should exit with code 0 if the current source code is good, and exit with a code between 1 and 127 (inclusive), except 125, if the current source code is bad.

Any other exit code will abort the bisect process.

It should be noted that a program that terminates via "exit(-1)" leaves $? = 255, (see the exit(3) manual page), as the value is chopped with "& 0377".

The special exit code 125 should be used when the current source code cannot be tested. If the script exits with this code, the current revision will be skipped

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM