Search code examples
gitrebasegit-commit

Git rebase --onto squashed branch


I need some help on how to use git rebase --onto to rebase a working branch effectively. I tried to follow this doc https://womanonrails.com/git-rebase-onto

Context

I branched branch-B from branch-A. In the meantime branch-A was merged into origin/main and his commits were squashed to I.

Old situation                             Current situation
A---B---C---F---G---I (origin/main)       A---B---C---F---G---I (branch)
         \         /                               \
          D---E---H (branch-A)                      D---E---H---J---K (branch-B)
                  \                                 
                   J---K (branch-B)                 

Expected result

I want to delete commits D,E,H and rebase on I

Expected result                                   
A---B---C---F---G---I (branch)
                     \
                      J'---K' (branch-B)               

I don't know which commit I need to use on the third argument...

git rebase --onto origin/main HERE

Thanks !


Solution

  • The way I remember it is as an English sentence:

    rebase (from) old_parent (up to) branch_tip onto new_parent

    That is:

    git rebase old_parent branch_tip --onto new_parent
    

    (Note that the arguments are in a different order to how some people write them; the --onto new_parent is an option, not a positional argument, so can go anywhere, and I just find it more logical at the end rather than the beginning.)

    In your case:

    • old_parent is the commit hash shown on your diagram as H
    • branch_tip is branch-B (and defaults to the currently checked out branch)
    • new_parent is I AKA origin/main

    So look up the actual commit hash for commit "H", and run:

    git rebase H branch-B --onto origin/main
    

    Or:

    git switch branch-B
    git rebase H --onto origin/main
    

    Or if you prefer to put the --onto first:

    git switch branch-B
    git rebase --onto origin/main H