Git's cherry pick

May 2, 2024

DISCLAIMER: I do not condone the frequent usage of this command. But I do believe it has helped me get out of sticky situations way more than I'd like to admit

Why cherry-pick?

Imagine you've been asked to deliver on a feature, a particular business requirement. You forked a branch from the master branch in Git, and you and maybe some other developers have started working on the same branch for a while

Somewhere along the line, you discovered a bug that was already present in the main branch and you made a commit that fixes it in the new feature branch (Not an ideal scenario, you always want to commit your changes before the fix and fix the bug on another branch).

You keep working on your feature when someone comes along and points out the exact bug that you observed and demands an immediate fix to be deployed

You made that fix 4 commits ago. It was a big fix. Your feature isn't ready to be merged into the main branch. And the bug fix was a big one, required a lot of changes

What do you do?

That's right. You checkout to the main branch and start copy pasting the code you changed to fix the bug

Just Kidding

For situations like these, git's cherry-pick command comes in real handy.

So how do I use it?

Imagine your feature branch diverged from your main branch like so at commit a2.

a1 - a2 - a3 - a4 - a5   :main
\
b1 - b2 - b3 - b4 :development

You kept coding away, fixed the bug in commit b2 and you've reached b4 now. So you've somehow got to apply the changes from commit b2 into your main branch.

You can use the git cherry-pick command like so:

git cherry-pick <commitSha>

commitSha refers to the commit reference. You can find the commit reference by doing a `git log` and finding the exact commit

So if you were to apply a commit from the development branch to the main branch, assuming you have the commit reference you need in commitShaB2

git checkout main
git cherry-pick commitShaB2

And now you have the changes made from one single commit on your main branch like so:

a1 - a2 - a3 - a4 - a5 - b2   :main
\
b1 - b2 - b3 - b4 :development

This is great! I can use it all the time

Don't. Using this often without care can lead to issues

When you cherry-pick a commit into another branch, it is created with a new unique hash, without any connectivity to the original branch. This indeed increases the possibility of having duplicate commits on your main branch

Moreover since at some point of time you will complete your feature and merge to the main branch, having modified the same file in both branches will lead to merge conflicts

TL:DR;

Use git cherry-pick to take very specific commits from a feature branch into a target branch without merging the entire branch. Do so with care to avoid conflicts and duplicate commits


Latest articles