Dat Tran
Dat Tran

Reputation: 1586

Git Undo Merge but Not delete later commits

My problem is:
I'm currently working on master branch.
My colleague merge his branch to master at B.
Then I continue my working with serveral commits C, D, E.
After that, I found that the merge should have not been there. And I want to revert the merge but still keep C, D, E.
Any suggestion???

Sample here:

0--A--B--C--D--E
      /
  G--H

And this is what I want it to be:

0--A--C--D--E

Upvotes: 1

Views: 164

Answers (1)

jeremija
jeremija

Reputation: 2528

Reverting

You should be able to do a git revert:

git checkout master
git revert B -m <mainline>

Where mainline is an integer which defines the branch to use as the main one. You can easily deduct which one to use by typing

git log B

You should see something like:

commit B
Merge: A H

And then your mainline is 1 if you want to revert to state A, or 2 if you want to revert to state H.

In this case you would write:

git revert B -m 1

This will create a new commit with the B commit removed. Your history will now look like:

0--A--B--C--D--E--F

Where the F commit is actually an undo of B.

As it says in the git-revert manpage, it is useful to check the Revert a faulty merge How-To.

Rebasing

Another option is to do:

git checkout master
git rebase -i A

however this will change you git history and might not be what you want, especially if other people are working on the same repository.

A new editor will popup with something like:

pick A
pick G
pick H
pick C
pick D
pick E

And you should change it to:

pick A
drop G
drop H
pick C
pick D
pick E

Save the file and exit the editor to continue the rebase process.

Your history should now look like 0--A--C--D--E.

Cherry-picking

Or you can create a new branch and cherry pick the commits you want:

git checkout A
git checkout -b new-master
git cherry-pick C..E 

Upvotes: 3

Related Questions