Git reverse merge commit and move master back to previous commit

1.2k views Asked by At

I have been facing some issues regarding my master branch. I accidentally pushed some commits to my master branch which were really old.

Now I want my master and source to go back to a previous commit (highlighted with blue color in the picture) and discard all the other commits after that from the source and history so that I can push my new commits after that. I am using bitbucket and SourceTree.

How would you do this?

enter image description here

1

There are 1 answers

7
VonC On

It is best to create a new commit which will be the exact image of the old 'Booking' one:

First:

 git checkout master
 git branch tmp                    # let's mark the current master (with wrong commit)

Then:

 git reset --hard <SHA1 'Booking'> # reset worktree and index of master
                                   # to Booking content
 git reset tmp                     # reset master HEAD and index to its original position 
                                   # (but keep working tree of Booking)

Now that the working tree represents the right content:

 git add .
 git commit -m "restore Booking"
 git push

That way, no filter-branch (which would rewrite the history), no revert (which might be complex when a merge is involved).


To know more about the "reset magic", read "Reset Demystified"

The first reset --hard restore the right content (but also moves HEAD and reset index)

https://git-scm.com/images/reset/reset-hard.png

The second reset (--mixed) will restore HEAD to its original place, and will restore the index as well. But it will leave the working tree untouched.

enter image description here

That way, there is a difference between master index and the working tree, which represents the content of the old commit.
Adding and committing are enough to create a new commit on top of the current master, with the old commit content.