Search code examples
git

How to detach a branch and reattach it to some different branch in Git


I have a master and topic branch forked from it as shown below:

A---B---C---D master
     \
      E---F topic

I want to detach this topic branch and attach it to my feature branch like shown below:

G---H---I---J feature
             \
              E---F topic

Here master and feature branches are present on both remote and local while the topic is only at my local. I want to push topic after reattaching it to feature.

Thanks


Solution

  • If feature contains B, then it's as simple as git rebase feature from the topic branch. If this is not the case, you'll need:

    git rebase --onto feature B
    

    The difference is because when B is not already contained in feature, the rebase command doesn't know how far to wind back before replaying.

    In general, git rebase --onto J B, means "replay all commits after B on top of J", going from the top graph to the bottom one:

    A---B---C---D master
         \
          E---F topic
    ______________________________
    
    G---H---I---J feature
                 \
                  E---F topic
    

    The shorthand git rebase XXX is useful in the scenario where HEAD (the current branch) and XXX contain a common ancestor like B below, which you can also find from git merge-base topic master:

    A---B---C---D master
         \
          E---F topic
    ______________________________
    
    A---B---C---D master
                 \
                  E---F topic
    

    Docs: https://git-scm.com/docs/git-rebase