Search code examples
gitgit-cherry-pick

What are the difference between Cherry-pick and patch apply?


I am aware about git cherry-pick and git apply terminalogies. But today i came across with some issue. I was applying one patch by using the diff of two revisions. I used the below command:

git diff HEAD > diff.patch

git apply diff.patch

I got patch apply failed for one file.

Then i simply tried to cherry-pick the commit-id2. It is cherry-picked successfully.

What may be the reason? Anyone wants to throw some light on the same.


Solution

  • Two possibilities:

    • The changes in diff.patch are probably different from the changes in commit-id2, which is why the two behaved differently.

      git diff HEAD shows the diff between HEAD and the current working directory. git cherry-pick commit-id2 applies the diff between commit-id2 and its parent (and commits the result using the metadata from commit-id2). The diff between commit-id2 and its parent is not (usually) the same as the diff between HEAD and the current working directory.

    • You did not tell git apply to fall back to a 3-way merge like cherry-pick does. Try adding the --3way (or -3) option to git apply.

    Try the following:

    git diff commit-id2^! >diff.patch
    git apply -3 diff.patch
    

    The above should behave like git cherry-pick -n commit-id2. (See git help revisions for an explanation of the ^! syntax.)