Search code examples
gitrebase

How to rebase a branch onto an indirect parent branch?


I branched from master to feature1 and from feature1 to feature2. But I actually wanted to branch both features off of master. I tried git rebase master but that just yields Current branch feature2 is up to date.
Why doesn't it work as I expect it to?
How can I rebase feature2 to branch off of master?

git init
echo "masterstuff" >> file.txt
git add file.txt && git commit -m "initial commit"
git checkout -b feature1
echo "branch1 specific" >> file.txt 
git add file.txt && git commit -m "start of feature1"
git checkout -b feature2
echo "feature2 specific" >> file.txt
git add file.txt && git commit -m "start of feature2"

Now I have

* [master] -- * [feature1] -- * [feature2] 

and want

* [master] -- * [feature1]
           \- * [feature2]

Solution

  • Assume exactly the "narrative" you have given:

    git init
    echo "masterstuff" >> file.txt
    git add file.txt && git commit -m "initial commit"
    git checkout -b feature1
    echo "branch1 specific" >> file.txt 
    git add file.txt && git commit -m "start of feature1"
    git checkout -b feature2
    echo "feature2 specific" >> file.txt
    git add file.txt && git commit -m "start of feature2"
    

    At the point where you leave off your "narrative", where you are still on feature2, you would next say:

    git rebase --onto master feature1
    

    You will then (for this particular "narrative") have a conflict to resolve! Resolve it (perhaps by editing file.txt manually), and then

    git add file.txt
    git rebase --continue
    

    Result:

    * 72395ff (HEAD -> feature2) start of feature2
    | * b59e979 (feature1) start of feature1
    |/  
    * 2ab1296 (master) initial commit