Working with Git – Cherry Picking Commits

Cherry-Picking

7The perfectly named git cherry-pick command is similar to git merge in that you can copy commits from a different branch into your current branch.  However, where merging will copy all of the commits from the other branch, cherry-pick is useful when you only want to copy specific commits into your branch.

The simplest use case is to copy one commit from a different branch into your branch.  The command is:

git cherry-pick <commit>

2015-10-18_23-13-06

Here we have a master branch with 7 commits, and a temp branch that only has the initial commit from master.  I want to copy one of the commits from master into temp.

  1. The commit I want to copy
  2. The list of commits in temp.  You can see just the one is there.
  3. The cherry-pick command.
  4. Checking the log of temp after the cherry-pick shows that the commit is now part of the temp branch.

One important thing to note is that the cherry-picked commit has a different ID than the corresponding commit in master.  This is because a commit’s ID is based on the code change AND the parent commit ID.  So even though the commit we copied in played-back the same code change in temp, it has a different parent in temp than it did in master.

To copy multiple commits, just include each of the commit ID’s in the cherry-pick command:

2015-10-18_23-48-13

  1. cherry-pick with the 2 commits to copy.  Since we are copying the commit that is at the top of master, we can use the branch name instead of the commit ID.
  2. The 2 commits copied into the temp branch.

Other Options

Some other useful options you can use with cherry-pick are

  1. Including -e allows you to edit each of the copied commit messages
  2. Including -x automatically edits each commit message to include the original commit ID
  3. Including -n will play-back the changes in each of the commits, but will not actually create any new commits in your branch.  This will leave your branch in a state of having staged, un-committed changes.  This option is useful if you want to squash the copied commits into one commit.

Resources

Other options and details about the cherry-pick command can be found at these sites:

  1. https://git-scm.com/docs/git-cherry-pick
  2. http://think-like-a-git.net/sections/rebase-from-the-ground-up/cherry-picking-explained.html

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s