Search code examples
gitgit-bashtortoisegit

How to git rebase a topic branch from a different topic branch?


I'm looking for a sequence of git commands to acquire changes that attempt to do something similar to my changes, but not from master/main, but from another contributor to the repo's branch.

I would normally use the following if rebasing from master:

git checkout TopicA
git rebase master
git push origin TopicA
git push --set-upstream origin TopicA

The setup for the repo is currently:

                F"---G"---H"---I TopicB
                |
A---B---C---D---E  master
                |
                F'---G'---H'---J   TopicA
                                

I need to replace the o' changes of TopicA with the o" changes of TopicB.

ETA: So the desired layout is:

               F"---G"---H"---I TopicB
               |
A---B---C---D--E  master
               |
               F"---G"---H"---J  TopicA
                               

My instinct is to replace 'master' with 'TopicB' in my sequence, but that was not the impression I got from the documentation on rebase.

My other thought would be to make a new branch (TopicC) forked off of TopicB, and then delete TopicA and then rename TopicC to TopicA.

I don't like the latter approach because I need to adapt some changes from TopicA into the changes that are present in TopicB.

So far I've read through the git-rebase(1) Man Page, and am left a bit confused and perplexed by it, and don't want to try too many things that could damage the repo or either my TopicA branch or the TopicB branch.

I'm wondering if

git rebase--onto TopicB 

will be all I'd need, especially after reviewing Merging changes from a branch based off a topic branch to a different topic branch in git though I'm a little unclear whether that case and my case are the same.

The other suggested question: Git rebase to a different branch while excluding a certain branch did not seem helpful.

I'm using Git Bash for handling my git commands. I also have TortoiseGit available, but Git Bash is my preferred tool.


Solution

  • Your proposed command

    git rebase --onto TopicB 
    

    would result in

    A---B---C---D---E---F"---G"---H"---I---F'---G'---H'---J TopicA
    

    You want

    git rebase --onto H" H'
    

    H" being the last commit you want to take from TopicB and H' being the last commit you don't want from TopicA. Run this while on the TopicA branch. You can get the commit ids for H" and H' from TortoiseGit as explained by this answer.


    Note that since you're concerned about damaging your repo you could first create a new branch from TopicA

    git branch TopicA-backup
    

    Then if you decide you don't like the state TopicA ends up in you can restore it with

    git reset TopicA-backup
    

    and delete the backup branch with

    git branch -d TopicA-backup
    

    For more detail on the syntax of the rebase command have a look at Matt's answer here.