DEV Community

Maksim Nesterenko
Maksim Nesterenko

Posted on

Rebase a feature branch that is based on another feature branch which got merged

So imagine you have 3 branches, where F1 is based on master and F2 depends on F1

*-*-*               (master)
     \ %-%-%        (F1)
            \ x-x-x (F2) 
Enter fullscreen mode Exit fullscreen mode

To have F2 up-to-date with F1 you rebase it like

git checkout F2
git rebase F1
Enter fullscreen mode Exit fullscreen mode

or, if someone else is pushing to F1 besides you and your local F1 might be not up-to-date, you do:

git checkout F2
git fetch
git rebase origin/F1
Enter fullscreen mode Exit fullscreen mode

Now, the work in the F1 branch is done and it's finally been merged into the master.

The problem though, is that F2 is still based on top of F1 and contains its commits, so when you open a pull request for F2 against the master it will contain the changes that do not make sense (commits from F1 that got merged already).

The git tree looks like this now:

*-*-*-%-%-%        (master)
     \            
       %-%-%-x-x-x (F2) 
Enter fullscreen mode Exit fullscreen mode

What we want here is to have our remaining F2 feature branch to be up-to-date with the master and contain only the relevant commits.

This can be done with --onto rebase flag. So you can do this:

# just to make sure the F2 is up to date with the F1 first
git checkout F2
git rebase F1

# then change the base to be master
git rebase --onto master F1
Enter fullscreen mode Exit fullscreen mode

That'll turn your git tree to be like this instead:

*-*-*-%-%-%       (master)
           \            
            x-x-x (F2) 
Enter fullscreen mode Exit fullscreen mode

After this, the commits in your pull request for F2 -> master will make sense again.

Top comments (0)