I’ve mentioned before that I prefer Mercurial to Git, at least for my own work. That said, git has a nice feature that allows you to cherry pick revisions to merge between branches. That’s extremely useful if you want to move a single change between branches and not do a full branch merge. Turns out mercurial has that ability, too, but it goes by a slightly different name.

There are actually two options in Mercurial – the older transplant extension and from Mercurial 2.0 onwards, the built-in graft command. I prefer to use the graft command, mainly because it is built into base mercurial and thus is available everywhere as long as one is running Mercurial 2.0 or up. Given that the current release is 4.0.1 as of the time of writing, you should really run something newer than 2.0. Also, graft uses mercurial’s merge abilities to cherry pick the change, you have a somewhat better chance of the change applying cleanly. Transplant uses the patch mechanism with works reasonably well, but in my opinion the merge system works better especially if you’re dealing with something that turns into a three way merge.

Usage is pretty simple – switch to the branch that you want to graft a change onto (the destination branch) and then graft away using the revision number of the change you want to use. Say, you want to graft a change 9534 to the release_356 branch:

hg co release_356
hg graft 9534

Note that hg graft does a merge and commit of the specific revision in one step as long as you don’t encounter a merge conflict. If you do encounter a merge conflict you’ll have to resolve it like you would resolve any other merge conflict, followed by a manual commit.

hg graft has additional functionality over and above simple cherry picking of one revision. For example, you can graft a range of revisions onto another branch. Have look at the documentation for hg graft for more information.

Leave a Reply