Search code examples
gitgit-mergerebasegit-rebasegit-flow

Rebase or merge a branch onto another feature branch merged in master


I have a feature branching scenario that I'm working on, and I'm a little unsure which way to go as the "best solution."

a -- b -- c                               <-- Master
           \
            d  -- e  -- f                 <-- Branch 1 (in review)
             \            
              d -- e -- f -- g -- h       <-- Branch 2

I started working on Branch 1, finished the full implementation, and opened the pull request. However, I needed to create Branch 2 to start the second part of the feature implementation.

a -- b -- c               x               <-- Master
           \             /
            d  -- e  -- f                 <-- Branch 1 (Merged in Master)
             \            
              d -- e -- f -- g -- h       <-- Branch 2

With that, Branch 1 was merged by CI into the Master branch. The problem is that Branch 2 loads all the changes from Branch 1 and I don't know which way to merge the Master changes into my Branch 2.

Interactive Rebase or Merge?


Solution

  • Non-interractive rebase should be enough

    First, make sure your local master is up-to-date with "upstream"/master (upstream being the remote referencing the target repository, where your PR was merged)

    git switch master
    git fetch upstream
    git merge upstream/master
    

    Then replay every branch2 commit done after branch1 start, and replay them on top of your updated master.

    A git merge-base branch1 branch2 should give you commit d of branch1

    git rebase --onto master $(git merge-base branch1 branch2) branch2
    

    That way, you get:

                                d' -- e' -- f' -- g' -- h'   <-- Branch 2
                               /
    a -- b -- c               x               <-- Master
               \             /
                d  -- e  -- f                 <-- Branch 1 (Merged in Master)