Git Cherry Pick

Today, I learned about git cherry-pick. The man page of cherry-pick states that:

Given one existing commit, apply the change the patch introduces, and record a new commit that records it. This requires your working tree to be clean (no modifications from the HEAD commit).

One of the use case I know of is to take a commit from one branch, and apply it on another. Given this,

- a - b - c - d - e - f (master)
            \
              g - h - i (dev)

and if I do this:

git checkout dev
git cherry-pick [SHA-1 hash of commit f]

I will have this:

- a - b - c - d - e - f (master)
            \
              g - h - i - f"(dev)

Now I will have another commit f” with a different SHA-1 hash from commit f.


However, take note that there are consequences of cherry-picking. The history in commit d and commit e will be lost. Consider a simpler tree:

- a - b - c (master)
    \
      d (dev)

Referring to the simple tree above, let’s say we introduce cheese_cake_recipe.txt in commit b with the content:

get_recipe() {
  return "cheese + flour + lime juice"
}

and changes the content of cheese_cake_recipe.txt in commit c into:

get_recipe() {
  return "cheese + flour + milk"
}

later I cherry-pick it from the (dev) branch like this:

git checkout dev
git cherry-pick [SHA-1 hash of commit c]

now I have this:

- a - b - c (master)
    \
      d - c" (dev)

But in commit c”, the content of cheese_cake_recipe.txt will be:

get_recipe() {
  return "cheese + flour + milk"
}

And we never know that lime juice ever exist in the older recipe, now our cheesecake won’t taste as nice and we won’t be able to find out why easily.

So use with care… Here are 2 posts talking about this:

http://stackoverflow.com/questions/880957/pull-all-commits-from-a-branch-push-specified-commits-to-another/881014#881014

http://stackoverflow.com/questions/881092/how-to-merge-a-specific-commit-in-git/881112#881112

Advertisements

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