Cherry Picking in Version Control

Profile Picture
Andrew Davis
Dec. 8, 2017 • 3m 54s
version control

Lately, I have been trying to improve my knowledge of git. I think it’s a tool that is often overlooked in our day-to-day as developers because we focus so much on writing code. When something goes wrong with version control, it’s easy to want to blow away a branch and manually copy code to a new one or even remove the local repository and clone again. Instead of taking the hard road, let’s try to correct conflicts or inconsistencies with the features already provided by git. Without further ado, say hello to cherry-pick.

To get started, let’s open a new terminal window and create a new project folder called demo. I’ll be using Bash commands so if you’re using Windows you will just use the CMD alternatives.

$ mkdir demo
$ cd demo

Lately, I’ve been learning Swift to create an iPhone app so let’s create a new Swift file in the demo directory called main.swift and initialize a new git repository.

$ touch main.swift
$ git init
$ git add -A
$ git commit -m "First commit"

Now to illustrate how cherry-pick works, I’m going to create another branch called feature.

$ git checkout -b “feature”

Under this new branch, we’ll create a new file called Foo.swift and commit it.

$ touch Foo.swift
$ git add -A
$ git commit -m “Added Foo file”

Then, we will create another file called Bar.swift and commit it as well.

$ touch Bar.swift
$ git add -A
$ git commit -m “Added Bar file”

So now, we should have three commits in our feature branch. Let’s view them by using git log.

$ git --no-pager log —-oneline
4f070d4 (HEAD -> feature) Added Bar file
7f96854 Added Foo file
865cc49 (master) First commit

Now, let’s switch back to our master branch.

$ git checkout master

For illustration purposes, let’s say now that the requirements of our project have changed and in our master code, we just need the Foo file and not the Bar file. If we run git merge with our feature branch, we’ll get both files though. So what’s the solution? We will cherry pick the commit we want so we can add only the Foo file to master. Grab the commit hash for the Foo file from the previous git log and we’ll use it in the next command and run git log to see the results.

$ git cherry-pick 7f96854
$ git --no-pager log --oneline
4e8af63 (HEAD -> master) Added Foo file
865cc49 First commit

Now we have the Foo file in master without the Bar file!

This example is a very simple view of cherry-pick. Cherry picking is not something you would want to use with large or complicated merges, but is a great way to work with small changes and conflicts. If you want to go even more in depth, then check out git rebase for more advanced branch changes.

Happy committing!