Today, while working with Git, I discovered a very nice feature. I was working on a dedicated feature
branch. Suddenly I discovered a bug which had to be fixed in order for that feature branch to make sense. However, the bug was not really connected with the feature I was working on. Well, it was connected in a sense, but it could affect other things as well, and I decided it should be fixed much earlier than I could possibly finish working on that feature – in other words, it deserved its own branch, based on the develop
branch.
So, I stashed my work, switched the current branch to develop
, created a fixbug
branch, fixed the bug, created a merge request and asked a colleague to review it.
But here’s the deal: I could not work on my feature without that particular bug fixed. On the other hand, I wanted my feature branch to be based on develop
and not on some other, random branch (well, that would work, but I like the history to be as clean as possible). What to do?
Here is what I have done. I cherry-picked the (sole) commit from the fixbug
branch to my feature
branch and continued working. When the colleague merged by fixbug
branch some time later, I pulled develop
and rebased feature
onto it. Since rebasing in Git means “replaying all commits on top of some other commit”, and my fix was already present on develop
, the cherry-picked commit was silently discarded as unnecessary (since I did not explicitly tell git rebase
to --keep-empty
commits). That was really nice – I didn’t have to manually delete the cherry-picked commit from where it didn’t really belong.
Tl;dr – here was the situation after I fixed the bug:
D---E---H'---I feature / A---B---C---F---G develop \ H fixbug
(H'
is the cherry-picked commit, identical to H
).
This was the state of the project after my merge request was approved:
D---E---H'---I feature / A---B---C---F---G---H develop
and this is what happened during the rebase:
D---E---I feature / A---B---C---F---G---H develop
Clever Git!