How to move git commits common to multiple branches earlier in the main branch history?

150 Views Asked by At

I have a git repo that looks like this:

   /C''-D''-F (featureB)
A-B-C---D---E (main)
   \C'--D'--G (featureA)

I would like to move the common commits C and D earlier in the main branch history so that the repo looks like this:

       /F (featureB)
A-B-C-D-E (main)
       \G (featureA)

It is important to note that the C/C'/C'' and D/D'/D'' commits modify the code identically, but due to being in different branches, they all have different commit hashes.

2

There are 2 best solutions below

4
On BEST ANSWER

Let's rephrase the task at hand:

I want to take the changes of the N latest commits of a branch and move/copy them in a way that their parent commit becomes a different one.

This is what git rebase allows you to do. You can tell it which range of commits to copy and onto which parent commit you want to copy it:

git rebase --onto main^ featureA^ featureA
git rebase --onto main^ featureB^ featureB

will rebase the latest commit of featureA and featureB onto the second last commit of branch main. You can also use the commit hashes directly:

git rebase --onto D D' featureA
git rebase --onto D D'' featureB
2
On

[C and D]...modify the code identically but have different commit hashes across the three branches.

In that case you'll probably want to first remove the C and D commits from your two feature branches, and then rebase to the main branch. You can use git rebase -i to do the first part, using the drop option for the the commits you don't want. Then (from each branch) git rebase main to replay the commits in each branch on top of the current state of the main branch.