Understanding Git Cherry-pick: How to Use
What is Git cherry-pick?
Git is the most widely used modern version control system in the world. A large number of software projects depend on Git for version control (both commercial and other open-sourced projects). If you're a beginner, you can get started on this beginner's guide to git and github.
One of its commands that I've found very useful especially when working with large teams is "git cherry-pick", along with other features such as git-flow, and even this guide to common git problems and their fixes.
But cherry-picking simply means picking a commit from a branch and applying that commit onto another branch. It is more useful for sampling out a small subset of changes from a topic branch you've decided to delete, but you still got some useful commits on it. This will introduce a new, distinct commit.
Cherry-picking becomes very useful and essential when it comes to bug fixing. This is because bugs are fixed and tested on the development branch with their respective snapshots (committed) — which might have been on a different level from your production branch.
As with other Git operations that introduce changes via the process of applying a diff, you may need to resolve conflicts to fully apply the changes from the given commit. This could be averted by doing a git cherry-pick.
This could also be useful whenever a full branch merge is not possible due to incompatible versions in the various branches.
Also, you can use git cherry-pick to pull the changes introduced to a sub-branch, without changing the branch, by your colleague working on the same project.
How do you do GIT cherry-pick?
Let's consider a git repo with two branches and some snapshots as shown below:
The image above shows a git repo with the master branch having A,B,C,D commits and cherry-pick branch with E,F,G commit.
To cherry-pick a particular commit from the master (i.e C) into "cherry-pick" branch:
- go to the branch that has the commit you want to cherry-pick and run
git checkout master
- Obtain the commit hash by typing
Alternatively, go to your GitHub page and copy the commit hash.
- Checkout the branch you want to have the commit (i.e cherry-pick)
git checkout cherry-pick
- Cherry-pick the commit by running:
git cherry-pick C
upon running the last command, your snapshot will now look like this
The cherry-pick branch now has just the snapshot C in the master branch
Why do a GIT cherry-pick
As stated above while defining what a git cherry-pick is, you will mostly cherry-pick a snapshot instead of merging the whole branch into the current branch.