guy777 guy777 - 1 month ago 17
Git Question

Rebase a merged commit

Here's my history:

* 8 [mybranch, origin/mybranch]
* 7
|\
| * 6 [master, origin/master]
* | 5
* | 4
|/
* 3
* 2
* 1


Since 3rd commit, a new branch was created, and after a few commits, I have merged my branch with the updated master (I should have rebase but I made a merge instead). So, to have a cleaner history, I want to achieve that (a linear history) :

* 8 [mybranch, origin/mybranch]
* 7
* 6 [master, origin/master]
* 5
* 4
* 3
* 2
* 1


Is it possible ?

Thanks

Answer

You have to make a new history. The most direct command sequence to create the history you wanted in the first place is

git rebase master 5                # for `5` sub in commit `5`'s id
git rebase --onto @ 7 mybranch     # for `7`, `7`'s id

It's not the history you created so far, it's a different one, so the id's on the new commits are all different, but it looks like

* 8'    mybranch
* 5'
* 4'
* 6     master origin/master
* 3
* 2
* 1

in your repo, with your origin/mybranch and the refs in every other repo that history was ever fetched or pushed into still referring to the old one you no longer love. If you've got good communications with everyone who's got a copy of that old history and they're fine doing a fetch and rebase to switch to the new one, git push -f origin newbranch is is by far the best way to handle this.

Getting as close as possible to the literal result you asked for, the 12345678 history, involves rewriting the master-branch history too, and producing a history you wouldn't have gotten if you'd done it right the first time.

Another option, especially if the existing mybranch history has found its way into repos you don't have much contact with, is to just leave it the way it is and carry on. Linearity is nice, but that's all it is.