gitgithubversion-controlrebasebranching-and-merging

Git rebase a branch from a branch that's also been rebased


Let's say I have this situation where branch1 was created from master. After a few commits on branch1, I also created another branch off of that called branch2. After this, someone else committed (D) in master. Now I want to rebase branch1 with master. But what about branch2 since branch1's hashes have been rewritten and now branch2 is lost.

master:  A - B - C - D
                  \
branch1:           E - F
                        \
branch2:                 G - H             

After rebasing branch1 on top of master, branch2 is lost because rebasing rewrites the hash of branch 1.

master:   A - B - C - D
                       \
branch1:                E - F

branch2:                 G - H             

Is there a proper way to use git rebase branch 2 on top of branch1 again in a situation like this?


Solution

  • branch2 is not lost and your second ASCII art is not correct. After rebasing branch1, your history now actually looks like this:

    master:   A - B - C - D
                       \   \
    branch1:            \   E' - F'
                         \
    branch2:               E - F - G - H             
    

    Commits E and F were not moved, but copies of the commits were created. E and F still exist exactly the same as prior to the rebase (commits can never be modified, once created). G's parent still points to F, so F must exist.

    With that cleared up, let's look at two answers how to get G..H onto F':

    1. git rebase --onto "F'" F branch2. Works with older Git versions and can be executed after branch1 has been rebased.
    2. git rebase --update-refs master branch2. Only works with recent Git versions and must be done instead of rebasing branch1: it will rebase all commits while moving the refs, such as branches, to the new, rebased commits.