Managing feature branches changes that aren’t quite ready for a full merge can be a difficult task. Sometimes you don’t want to push a whole branch into another, and only need to pick a few specific commits. This process is called cherry-picking. Why Cherry Pick? Let’s take a look at the following scenario which will […]
Managing feature branches changes that aren’t quite ready for a full merge can be a difficult task. Sometimes you don’t want to push a whole branch into another, and only need to pick a few specific commits. This process is called cherry-picking.
Let’s take a look at the following scenario which will make it easier to understand how cherry-picking works.
We are implementing new features for the next weekly sprint. Once the code is ready, we will push it to the development branch and open it up on the next public release when everything has been tested out.
But, the client isn’t pleased with all of the changes and is asking us to introduce only specific ones. Because not all features have been accepted for the next release, a
git merge or
git rebase would not produce the desired results since it will include all changes made in the last sprint.
Cherry pick is the right answer! It focuses only on the changes included in the commit that implement the wished features without bringing along other commits.
There are many other uses that this tool can offer:
git cherry-pickinstead of other options that as well apply changes from the given commits, such as
git cherry-pickis used to get the changes introduced to a sub-branch, without changing the branch.
Let’s cherry-pick a commit from the development and add it to feature branch by using the commit hash.
We want to pick a commit
C from the master. There are a few steps you should follow to get the job done:
git log --oneline, to get the log of your commits history. Make sure you are on the correct branch:
git checkout master.
git checkout feature.
git cherry-pick C.
If you run the
git log you will see that our cherry-picked commit at the top of the feature branch. It will have a new and different commit hash.
git cherry-pick C D.
git cherry-pick -m 1 <merge_hash>. Be careful! It is preferred to use
git mergeinstead of
git cherry-pick. When you cherry-pick a merge commit, it collapses all the changes made into that one commit. You lose the commit history.
Be wary of cherry-picking a lot of commits out of order. The new sequence will be reflecting the way you cherry-picked, and not the chronological order of the original commits.
Cherry picking is commonly discouraged in the developer community. The main reason is that it creates duplicate commits and you lose the ability to track the commit history. You should always aim to use
Merging nearby always overpowers cherry-picking. But it is worth taking a look at this unique Git feature! Share your experience with us.
The upcoming cherry-picking season marks a new list of future articles! Subscribe to stay up-to-date!