•  hallettj   ( @hallettj@beehaw.org ) 
    link
    fedilink
    English
    11
    edit-2
    8 months ago

    git rebase --onto is great for stacked branches when you are merging each branch using squash & merge or rebase & merge.

    By “stacked branches” I mean creating a branch off of another branch, as opposed to starting all branches from main.

    For example imagine you create branch A with multiple commits, and submit a pull request for it. While you are waiting for reviews and CI checks you get onto the next piece of work - but the next task builds on changes from branch A so you create branch B off of A. Eventually branch A is merged to main via squash and merge. Now main has the changes from A, but from git’s perspective main has diverged from B. The squash & merge created a new commit so git doesn’t see it as the same history as the original commits from A that you still have in B’s branch history. You want to bring B up to date with main so you can open a PR for B.

    The simplest option is to git merge main into B. But you might end up resolving merge conflicts that you don’t have to. (Edit: This happens if B changes some of the same lines that were previously changed in A.)

    Since the files in main are now in the same as state as they were at the start of B’s history you can replay only the commits from B onto main, and get a conflict-free rebase (assuming there are no conflicting changes in main from some other merge). Like this:

    $ git rebase --onto main A B
    

    The range A B specifies which commits to replay: not everything after the common ancestor between B and main, only the commits in B that come after A.