Remove a merge commit, keeping current changes

Spread the love

Question Description

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)
| /

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

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

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

Practice As Follows

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 squashsquash 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).

You may be interested in these books.


As an Amazon Associate I earn from qualifying purchases.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.