Roe
Roe

Reputation: 177

Unmerge a branch in Git with Sourcetree

I have merged my branch with a wrong branch and pushed, later I realized this mistake and merged again with correct branch (master).

Can you please suggest how I can unmerge that wrong branch now?

master

|

B (wrong one I have merged)

|

A (my branch)

Now I need to unmerge this B.

Upvotes: 2

Views: 1184

Answers (2)

LuFFy
LuFFy

Reputation: 9297

Solution 1:

You can reset your branch to the state it was in just before the merge if you find the commit it was on then.

Use git reflog, it will list all the HEADs you've had. I find that git reflog --relative-date is very useful as it shows how long ago each change happend.

Once you find that commit just do a git reset --hard <commit id> and your branch will be as it was before.


Solution 2:

you can simply git revert the merge commit like so:

git checkout BRANCH_NAME
git revert -m 1 <merge_commit_sha>

Note : It is possible that you will end up with some conflicts that you'll have to manually unmerge, just like when merging normally.

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521209

Ideally you could nuke the incorrect merge commit from the published branch since it does not belong there. However, doing this would be rewriting history, which is undesirable since the branch is public and others may have already pulled it.

Instead, a safer choice would be to use git revert to undo any changes which were introduced by the B merge commit.

Type git log and find the <SHA-1> hash of the B merge commit. Assuming that the merge commit has a hash of 1a3mj4w1 you would type:

git revert 1a3mj4w1

This will add a new commit on top of A which effectively undoes the merge commit B. Now your history will look like this:

master
      \
        B -- A -- C

where C is the commit introduced by git revert. Now you can simply push your branch to the remote with no issues.

Upvotes: 4

Related Questions