• Servers and Tools

Cherry Picking

From the class:  Git Merging

Another useful command is git-cherry-pick, and what it allows us to do is to bring in the changes that are introduced by a specific commit. So for example, let's say you're working on a branch for a while and you decide that you'd want to throw away the branch. You don't want to work with it anymore, but there is one change, one commit that you made somewhere in between-- somewhere in the middle of all the changes that you made. And you just want to pull in that one change.

Well, you can do that really easily with cherry-pick. Let's look at a quick, simple example. I'm going to create a feature branch again, so get checkout. Feature 6 this time, and I'll just make it simple. I'll echo out another change to, let's see, three.txt.

If I look at the get log now, the commit that I just made is 4560. So we can kind of remember that. 4560. I'm going to check out the master branch now, and then I can say git-cherry-pick, and-- oop.

I already forgot it. Let's scroll back. 4560. 4560. There we go.

And I can just provide the first couple of characters of the SHA-1 hash and press Enter, and it goes ahead and applies that commit to our master branch. And I can take a look at it with get log.

And we can see that commit is clearly pulled into the master branch as the top level commit here. I've created two windows that we can see the two branches side-by-side. On the right is our feature 6 branch that we just pulled in this commit from, and on the left is our master branch.

I want to point out, again, that the IDs of the hash of the commits have changed, so this commit is CF2D, and this one is 4560. But it point this one here will point to the same tree as this one, so they both point to the same tree. And the reason that the commit IDs are different is because, remember, that this gets turned into a patch and then it gets applied on top of our master branch. And during the application process, get is going to go ahead and create a separate commit for it.

This was a bit of a contrived example. But hopefully, you can imagine, if you had a branch that had a ton of commits in it and you wanted to throw away the branch but maybe grab one of these commits in the middle and pull that one in, cherry-pick makes it really easy to do that.