Rebasing a Git merge commit

jipumarino picture jipumarino · Jan 24, 2011 · Viewed 101.5k times · Source

Take the following case:

I have some work in a topic branch and now I'm ready to merge back to master:

* eb3b733 3     [master] [origin/master]
| * b62cae6 2   [topic]
|/  
* 38abeae 1

I perform the merge from master, resolve the conflicts and now I have:

*   8101fe3 Merge branch 'topic'  [master]
|\  
| * b62cae6 2                     [topic]
* | eb3b733 3                     [origin/master]
|/  
* 38abeae 1

Now, the merge took me some time, so I do another fetch and notice that the remote master branch has new changes:

*   8101fe3 Merge branch 'topic'  [master]
|\  
| * b62cae6 2                     [topic]
| | * e7affba 4                   [origin/master]
| |/  
|/|   
* | eb3b733 3
|/  
* 38abeae 1

If I try git rebase origin/master from master, I'm forced to resolve all conflicts again, and I also lose the merge commit:

* d4de423 2       [master]
* e7affba 4       [origin/master]
* eb3b733 3
| * b62cae6 2     [topic]
|/  
* 38abeae 1

Is there a clean way to rebase the merge commit so I end up with a history like the one I show below?

*   51984c7 Merge branch 'topic'  [master]
|\  
| * b62cae6 2                     [topic]
* | e7affba 4                     [origin/master]
* | eb3b733 3
|/  
* 38abeae 1

Answer

siride picture siride · Jan 24, 2011

There are two options here.

One is to do an interactive rebase and edit the merge commit, redo the merge manually and continue the rebase.

Another is to use the --rebase-merges option on git rebase, which is described as follows from the manual:

By default, a rebase will simply drop merge commits from the todo list, and put the rebased commits into a single, linear branch. With --rebase-merges, the rebase will instead try to preserve the branching structure within the commits that are to be rebased, by recreating the merge commits. Any resolved merge conflicts or manual amendments in these merge commits will have to be resolved/re-applied manually."