Create patch or diff file from git repository and apply it to another different git repository

GitDiffPatchGit DiffGit Apply

Git Problem Overview


I work on WordPress based project and I want to patch my project at each new release version of WP. For this, I want generate a patch between two commits or tags.

For example, in my repo /www/WP I do this:

$ git patch-format com1..com2 --stdout > '~/patchs/mypatch.patch'

# or

$ git patch-format tag1..tag2 --stdout > '~/patchs/mypatch.patch'

/www/WP git natif WordPress

/www/myproject My git project WordPress based

The git apply command line doesn't work, I think because we are in different repositories.

Can I generate a patch file without a commit, just a differential and apply it to another git repository?

Thank you.

Git Solutions


Solution 1 - Git

You can just use git diff to produce a unified diff suitable for git apply:

git diff tag1..tag2 > mypatch.patch

You can then apply the resulting patch with:

git apply mypatch.patch

Solution 2 - Git

To produce patch for several commits, you should use format-patch git command, e.g.

git format-patch -k --stdout R1..R2

This will export your commits into patch file in mailbox format.

To generate patch for the last commit, run:

git format-patch -k --stdout HEAD~1

Then in another repository apply the patch by am git command, e.g.

git am -3 -k file.patch

See: man git-format-patch and git-am.

Solution 3 - Git

You can apply two commands

  1. git diff --patch > mypatch.patch // to generate the patch`
  2. git apply mypatch.patch // to apply the patch`

Solution 4 - Git

As a complementary, to produce patch for only one specific commit, use:

git format-patch -1 <sha>

When the patch file is generated, make sure your other repo knows where it is when you use git am ${patch-name}

Before adding the patch, use git apply --check ${patch-name} to make sure that there is no confict.

Solution 5 - Git

You even can do patches only for sub directory you are currently in. Just add .

git format-patch -k b365cce8..80a2c18a .

Then you can apply them:

git am *.patch

See this answer for details

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzatamineView Question on Stackoverflow
Solution 1 - GitEnrico CampidoglioView Answer on Stackoverflow
Solution 2 - GitkenorbView Answer on Stackoverflow
Solution 3 - Gituser7396942View Answer on Stackoverflow
Solution 4 - GitEugeneView Answer on Stackoverflow
Solution 5 - GitEugen KonkovView Answer on Stackoverflow