How to apply a patch to git including new files an

2019-04-10 21:21发布

问题:

I am looking for a universal way to turn a patch file generated by git show, git format-patch or even diff in a commit the best way possible.

I would expect the following features:

  1. Existing files should be modified and the modifications staged for the new commit.
  2. New files should be created and staged for the new commit.
  3. File deletions should be staged for the new commit as well.
  4. If the patch was created using git format-patch, commit message should be parsed and used for the new commit.
  5. If the patch was created using git show, commit message should be parsed and used for the new commit.
  6. If the patch was not created by the two tools above, it should still be processed.
  7. The CLI should be able to accept multiple patches and thus create multiple commits.

I am mostly interested in existing solutions before I consider creating a new tool.

Previous research:

The closest tool is git am but fails #5 and #6 so it isn't useful for the purpose. On the other hand git apply doesn't create a commit on its own and fails at least #2 and #5. I'm not aware of tools that would be more successful than those two.

When applying patches from RPM specfile in the following format:

Patch0: abc.patch
Patch1: xyz.patch

I'm currently building a script using the following sed command:

sed -re 's/.*: *(.*)/git apply \1 \&\& git add . \&\& git commit -am \1/'

This of course doesn't do #4 and #5 as it always uses patch filename as the commit message and #7 is worked around.

回答1:

I know your'e asking about diff, git format-patch and git show but all of those will transfer changes, not commits.

There is command called git bundle that will transfer the commits instead, including author, time and everything. You can read up on the docs.

Basically you'll create a bundle file containing at least the new commits, then send that file around. The receiver will clone the file into a repository that you can merge, pull, rebase or anything from.