Cherry-Picking for Fun and Profit

In Git, it is often useful to merge one specific commit from one branch into another. Frequently this happens when Using Git Interactive Rebase With Feature Branches, as you develop in the branch, you realize that one or more of your commits should be added to master right away, but not all the CLs. Enter git cherry-pick <changelist hash> for the win! The cherry pick command allows you to merge one CL from a branch, or even straight from the reflog into another branch.

Getting ready

For this article, lets assume you have a commit history that looks like:

fc64d55 -- d0e6ac9 -- 1edbe95 -- 24c685b -- 2f0514a  [master]
                          a70d41c -- b45af4a -- 38967f5 [branch feature1]

And we want to merge some important change in #b45af4a into master.

How do it…

The code to cherry pick the change into master is:

git checkout master
git cherry-pick b45af4a

Now rebase master on to the feature1 branch:

git checkout feature1
git rebase master

You may have to resolve conflicts, but notice that git is smart enough not to reapply the cherry picked changelist:

Applying: a70d41c
Applying: 38967f5

How it works…

It is important to note that cherry-pick behaves just like a merge. If there are merge conflicts that git cannot resolve, then it will ask you to manually resolve them. Consequently, the new changelist in master will not necessarily be identical to the cherry-picked CL, and it will definitely have a new hashcode. Fortunately, git tracks cherry-picked CLs, so when you rebase back onto the cherry-picked branch, it won’t duplicate the CLs and will restructure your history according to master.

Also, while cherry-pick is great for merging one or two commits, it is not ideal from many commits.