Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a merge commit, keeping current changes

Tags:

git

merge

commit

We have had a small problem in our team. One dev had to include some changes in our development branch. Before doing so, he accidentally merged a feature branch (which shouldn't be merged then) and kept on working over those changes, generating a couple of commits after the merge.

Now we want to keep those changes, but apply them to the commit before the merge was done. To keep it clear:

A (+b, +a)
|
B (+a)
|
C (merge commit)
|\
D \
|  E (feature branch)
| /
|/
F

What we want to have his changes (+a,+b) applied over commit D . The equivalent to:

C (+a,+b)
|
D 
|  E (feature branch)
| /
|/
F

How can we commit a change to dismiss a previous merge keeping local changes?

like image 988
khose Avatar asked Jan 14 '14 14:01

khose


People also ask

Can I delete a merge commit?

How to Undo a Merge Commit in Git. 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 .

How do you delete one merge?

Do git rebase -i <sha before the branches diverged> this will allow you to remove the merge commit and the log will be one single line as you wanted. You can also delete any commits that you do not want any more.

How do I get rid of merge changes?

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.


1 Answers

This is a job for git rebase -i. Run:

git rebase -i F

You'll be presented with a list of commits in ${EDITOR}, like so:

pick 334ad92 D
pick fb54c42 E
pick 6901e51 B
pick 6c61a52 A

# Rebase eea2847..6c61a52 onto eea2847
#
# (more instructions here)

Delete the pick fb54c42 E line to remove that commit. (Also, if you want A and B to be combined into a single commit, you can change the pick command to squash -- squash 6c61a52 A). Save and close the file and your branches will be in the state you wish.

Note that this will change history. This means that you'll need to do a git push -f if you've already pushed the branch anywhere, and it'll mess with anyone else who's been collaborating on this branch. If that's an issue, you can git revert the merge commit instead:

git revert -m 1 C

The -m 1 argument tells git to revert against the first parent of the commit, which is the side that was merged into (D, in your diagram).

like image 67
Ash Wilson Avatar answered Sep 30 '22 21:09

Ash Wilson