Git Cherry Pick

Some of my team members asked me how to merge only specific commits from a branch into the current branch. The reason you’d want to do this is to merge specific changes that you need immediately, leaving the other code changes you’re not interested.

First of all, use git log to see exactly which commit you want to pick or you can use the UI to identify the commit ID.
 
As an example:
Screen Shot 2016-06-21 at 3.30.34 pm

 

Let’s say you’ve written some code in the commit f69eb3 of the feature branch that is very important right at this moment. It may contain a bug fix or the code that other people need might need access to. You might want to have commit f69eb3 in the release branch, but not the other code you’ve written in the feature branch. Here the git cherry-pick comes very handy, in this case, f69eb3 is the cherry and you want to pick it.

Below are the step by step instructions to pick one commit from feature branch to release branch.

git checkout release
git cherry-pick f69eb3

That’s all, f69eb3 is now applied to the master branch and commited (as a new commit) in release branch. The cherry-pick behaves just like merge. If git can’t apply the changes then you will get merge conflicts. Git leaves you to resolve the conflicts manually and make the commit yourself.

In some cases picking one single commit is not enough. You may need, let’s say few consecutive commits. In this case, cherry-pick is not the right tool. Instead use rebase. From the previous example, you’d want commit 76f39a through b816a0 in release.

The process is to first create a new branch from feature at the last commit you want. Let’s say you want upto b816a0.

git checkout -b mybranch b816a0

Next, you rebase the mybranch commit –onto master. The 76f39a^ indicates that you want to start from that specific commit.

 git rebase --onto master 76f39a

The result is that commits 76f39a through b816a0 are applied to master branch.

Please note, git commit ID is a hash of both its contents and its history. So, even if you have two commits that introduce the exact same change, if they point to different parent commits, they still have different IDs. After the cherry pick, the commit in the release branch will not reflect the same commit id as it will have new commit id.

By : Nataraj Srikantaiah

Leave a Reply

Your email address will not be published.