git patch 可以将项目中的 commit 导出为 .patch 文件,其他分支或项目可合并这些 patch 并生成一致的提交记录,常用于把误写在错误分支的功能迁移到正确分支。

生成 patch

使用 git format-patch 生成需要的 patch:

  • 超前于 master 分支的所有提交:
git format-patch -M master
  • 某个提交后的所有提交(不含该提交):
git format-patch 35ec56
  • 两个提交之间的所有提交(不含 35ec56,含 c388c0):
git format-patch 35ec56...c388c0
  • 某提交前的 N 次提交(含该提交):
git format-patch -N 35ec56
  • 单个提交:
git format-patch -1 35ec56

执行后,每个 commit 会生成一个编号的 .patch 文件,顺序与提交顺序一致。

合并 patch

  • 查看 patch 改动:
git apply --stat 0001-demo.patch
  • 预检查 patch 是否可用(不会真正应用):
git apply --check *.patch
  • 合并 patch:
git am *.patch

出现冲突时 Git 会报错并停止后续 patch。

冲突处理

示例输出:

 ~ git am *.patch
Applying: add supervisor 配置
Applying: add Nginx配置
Applying: 更新配置
Applying: 修改博客LOGO
error: aaa.txt: does not exist in index
Patch failed at 0004 修改博客LOGO
Use 'git am --show-current-patch' to see the failed patch
When you have resolved this problem, run "git am --continue".
If you prefer to skip this patch, run "git am --skip" instead.
To restore the original branch and stop patching, run "git am --abort".

git apply --reject 0004.patch:自动写入可合并的修改,并为失败的块生成 .rej 文件,方便手动对照处理。根据 .rej 提示调整相关文件,确保冲突处理完毕。

.rej 文件中包含了冲突文件的 diff 信息,参考该 .rej 文件对冲突的文件进行修改,.rej 文件参考完之后可以删除。

按 .rej 文件提示修改冲突文件,然后:

git add aaa.txt bbb.txt
git am --resolved

Git 会根据已暂存的改动生成当前 patch 的提交。

参考链接