Pwnosaurus
Pwnosaurus

Reputation: 2170

How does git cherry-pick compute the patch?

I understand how git cherry-pick works at a high level: It takes the changes introduced in one commit and applies them to another.

However, I’m trying to gain a better understanding of how git actually achieves this under the hood.

Suppose you run the following:

$ git checkout main
$ git cherry-pick source-commit

My understanding is that since a commit is a snapshot, not a set of changes, that cherry-pick must first be computing some sort of diff, and then applying that patch/diff to the current branch (main). Is this patch just the diff of source-commit with its parent? Is the merge base of source-commit and main involved at all?

Upvotes: 0

Views: 137

Answers (1)

rodrigo
rodrigo

Reputation: 98436

Indeed, doing a git cherry-pick HASH with a single commit is more or less equivalent to:

  1. git show --patch HASH > temp.diff
  2. git apply temp.diff

In turn, step 1 above computes the difference between the given commit and its single parent.

(You can cherry-pick a merge, but you have to specify what parent to compare against, with option -m parent-number.)

About the merge base, AFAIK the merge base of HASH and main is not involved at all. Note that in case of conflicts, if you have configured the diff3 conflict style, the middle hunk (which for merges is the merge base) is just the parent of the cherry.

Upvotes: 2

Related Questions