Search code examples
gitgit-rebasegit-cherry-pickgit-history-rewrite

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


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.


Solution

  • 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