Search code examples
gitversion-controlgit-mergegit-rebase

Amalgamate two merges in Git


I have a Git branch which is a topic branch that shows the project master. I merged it with the master and resolved a conflict manually. After that, a critical bug was fixed in master and I merged again, this time without conflict. I did not commit anything myself between the two merges and I have not pushed the branch to anyone else. I would like to combine the two merges.

What I have now is:

master ----A---B-----C---------->
                \     \
topic   ---W-----X-----Y-------->

Where:

  • X is the merge where a conflict was fixed
  • C is the critical bug fix on master
  • Y is the merge incorporating this fix

I would like to make this into:

master  ----A---B---C----------->
                     \
topic   ----W---------X'-------->

Where X' is now a merge incorporating the conflict resolution and the bugfix in a single merge commit.

I know I could do it manually by checking out W and merging master, and copying the contents of the resolved files from X during the inevitable conflict. Is there a quicker way with less chance of messing it up (in the case that the conflict was large and ugly)?


Solution

  • If you truly haven't pushed anything since at least W, then this is probably the easiest way (outside of the actual conflict resolution - which may be painful, I guess) to accomplish it:

    git checkout topic
    git reset --hard W
    git merge master
    

    If you have pushed since W, though (in particular if either X or Y exist anywhere outside your repository), I'm not sure there is a clean solution to this - no matter what you do, you'll cause problems for any other repositories that have either X or Y in them.

    Of course, you'll have to re-do the conflict resolution, unless you have rerere enabled.