Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I undo a merge which does not produce a merge commit?

Tags:

git

merge

I created an experimental branch from master, and made four commits on the experimental branch. The master, in the mean time, still remains where it last was. Now, I want to merge my experimental branch in such a way that I will be able to easily undo this merge in future.

When I tried searching, the easiest way to undo a merge seems to me like git revert hash_of_merge_commit.

However, this only works when I get a merge commit hash when merging my master with experimental branch. In this case, since master's HEAD has not progressed, when I try to merge, I just get four new commits added to master, and this would mean that to undo this merge, I would need to manually remember and revert each of these individual commits in future.

Any better way to do this?

like image 729
jeffreyveon Avatar asked Nov 03 '11 15:11

jeffreyveon


People also ask

How do I undo a non committed merge?

You can undo a Git merge using the git reset –merge command. This command changes all files that are different between your current repository and a particular commit. There is no “git undo merge” command but the git reset command works well to undo a merge.

How do I undo a specific merge?

In case you are using the Tower Git client, undoing a merge is really simple: just press CMD+Z afterwards and Tower will undo the merge for you!

How do I get rid of unfinished merge?

You can use the git reset --merge command. You can also use the git merge --abort command.

How do I cancel a pushed merge?

Now, if you have already pushed the merged changes you want to undo to your remote repository, you can right-click on the merge commit and select Revert commit from the context menu.


1 Answers

The other answerers seem to be concerned with preventing this from happening in the first place. If a fast-forwarded merge has already occurred and been pushed, here's a solution:

  1. git checkout -b my-undo-branch
  2. git reflog show master - find the last commit before the merge
  3. git reset --keep SHA - using the SHA from the previous step

At this point, verify that this branch is in the state that you want master to be in. Now it's just a matter of taking the diff between those two branches and committing it to master:

  1. git checkout master
  2. git diff master my-undo-branch --no-prefix > patchfile
  3. patch -p0 < patchfile

Then, finally, delete patchfile, git add all the changes, and git commit them.

like image 96
Trevor Burnham Avatar answered Sep 27 '22 23:09

Trevor Burnham