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??

2

1 Answer

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.