Home > front end >  I have a branchZ from where I created a branchA and from that branchA I created a branchB, can I mak
I have a branchZ from where I created a branchA and from that branchA I created a branchB, can I mak

Time:10-08

I currently have something like this:

a -- b                  <-- branchZ
      \
       d -- e           <-- branchA
             \
              f -- g    <-- branchB

and I want to have something like this:

       f -- g           <-- branchB
      /
a -- b                  <-- branchZ
      \
       d -- e           <-- branchA
             

Is this possible??

CodePudding user response:

There are multiple ways to accomplish this. Conceptually you are doing a hard reset of branchB to point to commit b and then cherry-picking commits f and g. So for example:

git switch branchB
git reset --hard b
git cherry-pick f
git cherry-pick g

There's a more efficient way using cherry-pick since you can use ranges if your commits are consecutive, which they are in this case. The trick for a range is that the first commit you specify is the parent of the first commit you wish to include, like this:

git switch branchB
git reset --hard b
git cherry-pick f~1..g

Note that f~1 is the parent of f, which in this case is e, and also branchA, so any of those will work.

Finally, there's an advanced version of rebase which is perhaps the best option here, since it does everything the above commands do, but all in a single command:

git rebase f~1 branchB --onto b

In words that says, take all commits on branchB that aren't reachable by commit f~1 and replay them, in order, onto commit b. In this case you'll be left with branchB checked out even if it wasn't when you started.

Note that branches are just pointers to commits making them interchangeable. It might be slightly easier to understand if we use branch names for the rebase instead of commits, so the equivalent rebase command would be:

git rebase branchA branchB --onto branchZ

In words that says, take all the commits on branchB that aren't reachable by branchA and replay them, one by one, onto branchZ.

  • Related