Search code examples
gitgit-rebase

Rebase and move parent branches along


TLDR I want the parent branches (in a linear branch) to move along with the new commits during a rebase.


Initial setup: multiple feature branches (on top of each other) each one waiting to be merged into master

A--B--C--D <-master
   \
    E--F--G--H--I--J--K--L
       ^     ^     ^     ^
       |     |     |     feature_d
       |     |     feature_c
       |     feature_b
       feature_a

A review is made, a new commit M is added to feature_a, then it is merged into master:

A--B--C--D--N <-master
   \       /
    E--F--M <- feature_a
       \
        G--H--I--J--K--L
           ^     ^     ^
           |     |     feature_d
           |     feature_c
           feature_b

It's here where I want to do the rebase.

Desired result: rebase feature_d to master and move all parent branches along:

A--B--C--D--N <-master
   \       / \
    E--F--M   G'--H'--I'--J'--K'--L'
                  ^       ^       ^
                  |       |       feature_d
                  |       feature_c
                  feature_b

The way I know how to do this is "manual", i.e. normal rebase of feature_d followed by moving each branch pointer:

git checkout feature_d
git rebase master
git branch -f feature_b H'
git branch -f feature_c J'

This requires manually searching and referencing the new commits by their sha. It involves extra attention and is error prone. I am hoping for an automated process, something like this:

git checkout feature_d
git rebase master --magic-option-move-branches-to-new-commits

Solution

  • The magic option you're looking for was introduced in Git 2.38, it's --update-refs. In your example, you'd do:

    $ git checkout feature_d
    $ git rebase --update-refs master
    

    See https://github.blog/2022-10-03-highlights-from-git-2-38/ for more info, and https://stackoverflow.com/a/74256185 for an example.