Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undoing accidental git merge without regressing history

Tags:

git

I did something stupid and accidently merged a topic branch into my master branch and then pushed it live to github (where others have pulled). Just to make sure it was a completely moronic mistake, I pulled it out to my production servers.

I've hung my head in shame for the appropriate amount of time and now I need to figure out how to effectively roll back the code commits while progressing the commit history.

To get my production code to the correct checkout, I ran git checkout hashoflettersandnumbers and that's the commit I want the production HEAD to be.

I run git reset hashoflettersandnumbers and then git clean to remove the changes from that commit going forward, but I can't seem to get that code to be the HEAD of the master branch and make a fresh commit.

like image 737
brycemcd Avatar asked May 16 '11 17:05

brycemcd


People also ask

How do I undo an accidental merge?

You can use the Git reset command to undo a merge. Firstly, you need to check for the commit hash (or id) so you can use it to go back to the previous commit. To check for the hash, run git log or git reflog . git reflog is a better option because things are more readable with it.

How do you undo a git merge after pushing the changes?

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.

How do I undo an unfinished merge?

Use git-reset or git merge --abort to cancel a merge that had conflicts. Please note that all the changes will be reset, and this operation cannot be reverted, so make sure to commit or git-stash all your changes before you start a merge.

Does git merge keep history?

In the Conceptual Overview section, we saw how a feature branch can incorporate upstream changes from main using either git merge or git rebase . Merging is a safe option that preserves the entire history of your repository, while rebasing creates a linear history by moving your feature branch onto the tip of main .


1 Answers

Use git revert on each of the branches. This will create a new commit that preserves your mistake for all eternity, but gives you back the same tree as you had before you merged.

For example, if 123456 is the merge commit...

$ git checkout master
$ git revert 123456
$ git checkout topic-branch
$ git revert 123456

This assumes that this wasn't a "fast-forward" merge.

like image 57
Dietrich Epp Avatar answered Nov 04 '22 21:11

Dietrich Epp