Git Cherry Pick
Recently I ran into a problem on a project where I was working on the wrong branch and committed changes. Those commits were supposed to go elsewhere and I now I need to get them into the correct branch!
There are a few options to solve this:
Merge the incorrect branch into the correct branch. But I don’t want to that because there are items in the incorrect branch that I don’t want. So, that’s out.
Recreate those changes in my working branch and just go on with my day. But that’s a waste of my time and I’m adamantly against redoing work!
Create a patch and then apply that patch to the new branch.
All solid options but there’s still something better:
$ git cherry-pick
A Scenario for Using git-cherry-pick #
Let’s review where we’re at in our pretend situation (follow along with me, okay?) and then how to solve the problem using git-cherry-pick
.
I just created a new commit in my repository, in the branch called some_other_feature
. But that’s the wrong branch!
$ git branch
develop
master
my_new_feature
* some_other_feature
stage
The new commit should be on the my_new_feature
branch. I could merge the branches but the some_other_feature
branch contains commits and changes that I don’t want in the other branch (they are not ready for merging into any upstream branches, like develop
or master
.
Here’s the commit I need to get into my_new_feature
:
commit ec485b624e85b2cad930cf8b7c383a134748b057
Author: Ryan Irelan <[email protected]>
Date: Fri Aug 19 10:44:47 2016 -0500
new contact page
Using git-cherry-pick #
The syntax of git-cherry-pick is this:
$git cherry-pick [commit hash]
The first step is fetch the commit hash for the commits we want to cherry-pick. We can do that using git-log
and then copying the hash (in full or just the last 7 characters will work) to our clipboard.
Next, we need to be on the branch where we want the changes to be (our destination branch).
$ git checkout my_new_feature
Now we can run the git-cherry-pick
command and apply the commit to our destination branch.
$ git cherry-pick ec485b624e85b2cad930cf8b7c383a134748b057
This will return something like this:
[my_new_feature 1bf8955] new contact page
Date: Fri Aug 19 10:44:47 2016 -0500
1 file changed, 1 insertion(+)
create mode 100644 contact.html
If we look at our log for this branch, we now see our commit:
$ git log
commit 1bf8955d5e6ca71633cc57971379e86b9de41916
Author: Ryan Irelan <[email protected]>
Date: Fri Aug 19 10:44:47 2016 -0500
new contact page
What’s happening when we run git-cherry-pick
?
- Git is fetching the changes in the specified commit and replaying them in the current branch. The commits are not removed from the source branch; they remain intact.
- Because this commit is being applied to a new branch and therefore has different contents it will get a different hash than the source commit.
With the problem solved, we are ready to move on with our development work!