Transplanting Git Branches
M Bellucci
Posted on December 16, 2023
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.
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.
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
That can be done with this simple 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:')
The command for applying this transplant would be:
$> git rebase βonto schexp-e2e 576c19ccd^ 812f12b3b
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!
Posted on December 16, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.