Nav links

Saturday, 20 June 2015

Tell me more about cherry-picking in Git

This is part 38 in a non-existent series of Git for Simpletons. 

Suppose you do your experimental development work in branch-1, and when it's ready you somehow put it into branch-2. The boss loved your work on Apples, and it's already in production. You've finished your Banana section, but it hasn't been approved. Oh no, your boss now wants the Apples to be changed to Avocados, and a new Cheese bit added, but no, the Banana still needs approval from public affairs. This is where the git cherry-pick command can come in handy.

Below shows the contents of the repository for the two branches at each stage. I've omitted some of the commands so as to concentrate on the exciting bits.

branch-1 branch-2
Create text file "a.txt" in branch-1
Store contents of branch-1 in repository:
git commit -m "commit 1"
a.txt: Apple
Create branch-2. This is identical to branch-1.
git branch branch-2

a.txt: Apple
Create text file "b.txt" in branch-1
Store contents of branch-1 in repository:
git commit -m "commit 2"
a.txt: Apple
b.txt: Banana

Change contents of "a.txt" and create new text file "c.txt"

Store contents of branch-1 in repository:
git commit -m "commit 3"
a.txt: Avocado
b.txt: Banana
c.txt: Cheese

Switch to branch-2:
git checkout branch-2


Apply changes from commit 2 to commit 3 onto branch-2
git cherry-pick [hash of commit 3]

a.txt: Avocado
c.txt: Cheese

Git can be quite intimidating, even if you're familiar with other source control systems. It's easier to understand some commands by doing them and watching the outcomes than reading about them, and cherry-pick is one of them. Hopefully doing this vicariously delivers the same comprehension to you as it did to me.