Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git, undo merge commit on rebase

Tags:

git

merge

rebase

I have a history which looks somewhat as following

  * (TOPIC) topic 3
  |
| * merge master onto topic
|/|
* | master 3
| * topic 2
* | master 2
| | 
| * topic 1
|/
* master 1
|

I.e. the upstream branch is merged into topic once. Now I want to interactively rebase this topic branch on the same base, but undo the merge (merge commit itself and all the commits from master introduced by the merge). How is this possible?

like image 960
Tuomas Toivonen Avatar asked Sep 21 '25 09:09

Tuomas Toivonen


1 Answers

Lets use valid identifiers for the commits depicted in your drawing:

  * topic3          (TOPIC) topic 3
  |
| * topic2merge     merge master onto topic
|/|
* | master3
| * topic2
* | master2
| | 
| * topic1
|/
* master1
|

If you want to remove the merge commit (make topic2 the only parent of the first commit after merge master onto topic) you need to run the following git rebase command:

git rebase --onto topic2 topic2merge topic3

If the current branch is topic3 already you can omit topic3 from the command above (if it is present, the first thing that git rebase does it to it checkout, if it is not the current branch already).

After this operation, the graph look like this:

| * topic3      <-- (TOPIC) topic 3
| |
* | master3
| * topic2
* | master2
| | 
| * topic1
|/
* master1
|

The commits between and including topic2merge and topic3 are still present in the repository but they are not visible any more. They are still visible if they are reachable and this happens if there are branches that points to them. Even remote branches.

If you have already pushed topic3 to a remote repo you must run git push -f origin topic3 (replace origin with the name of your remote) and inform your coworkers about the fact that you have changed history. They need to know this; on their repositories topic3 still has topic2merge in its history and the change you did represents an alternative history line their repos do not take automatically. They have to use git reset --hard or git rebase or git cherry-pick to keep up.

like image 53
axiac Avatar answered Sep 23 '25 12:09

axiac