DEV Community

Cover image for Transplanting Git Branches
M Bellucci
M Bellucci

Posted on

Transplanting Git Branches

Surely in your life as a developer you have come to this situation. You've made changes to your branch then pushed, and your github branch shows a series of undesired "shared" commits.

shared-commits

It could be multiples causes to this problem but today we will focus on its solution.

quick-question: How do you often solve this problem?
(leave your comments 🙏)

Well, I used to solve this problem in one of these two ways:
1) Rebase interactive
2) New-Branch + cherry-pick

Any of those two process take between 5 and 15 minutes to complete depending on the number of commits and feels a bit tedious.

That was until get to know the --onto option of git rebase and I managed to do this task in 30 seconds with a single command 😎

This option allows you to cut a series of consecutive commits and paste them on top of the target branch.
The documentation in man git-rebase refers to this process as transplant a branch and this is the example shown there.

transplant-from

Where it indicates that initially topic depended on functionality introduced in next but then next was merged to master so we can now transplant topic on top of master

transplant-to

That can be done with this simple command:

transplant-command

For the case presented in the first image we can see that we want to put schexp-e2e-2 on top of schexp-e2e but we only want from 576c19ccd to 8812f12b3b (commits starting with 'test:' or 'fix:')

transplant-result

The command for applying this transplant would be:

$> git rebase —onto schexp-e2e 576c19ccd^ 812f12b3b
Enter fullscreen mode Exit fullscreen mode

Which would result in:
my-result

It is straightforward, but it has a caveat which is not clearly specified in the documentation.
If you want to include the initial commit (second argument) into the result, then you need to add ^ at the end because the command starts pruning from its child. So if we want to include foo commit we need to indicate foo^ which means parent of foo

Hope you find this useful, thanks for reading!
If you want to know more about me, visit my personal site or drop me an email, don't hesitate to reach out.
Happy coding!

Top comments (0)