便笺: git 与 patch

发表于 2026-02-24 00:50 更新于 2026-02-24 00:50 343 字 2 min read

kissablecho avatar

kissablecho

kissablecho 的个人博客 / 记录生活,分享技术 / 喜欢二次元和白丝。

This post is not yet available in English. Showing the original.
克隆或使用模板创建仓库后,设为私人仓库,就不太好同步原仓库的更新了。本文介绍如何通过 git 生成 patch 文件,以及如何通过 patch 文件同步原仓库的更新。

乱写的 description

克隆或使用模板创建仓库后,设为私人仓库,就不太好同步原仓库的更新了。

本文介绍如何通过 git 生成 patch 文件,以及如何通过 patch 文件同步原仓库的更新。

生成 patch 文件

生成最近一次提交的 patch

git format-patch HEAD~

# 或
git format-patch -1

生成指定提交(如 abc123)的 patch

git format-patch -1 abc123

生成多个提交的 patch 文件

# 生成最近 N 个提交的 patch(例如最近3次)
git format-patch -3

# 生成两个提交之间的所有 patch(不包含起始提交)
git format-patch <start-commit>..<end-commit>
# 示例:生成从 abc123 到当前 HEAD 的所有提交
git format-patch abc123..HEAD

应用 patch 文件

保留元数据

git am *..patch

如果报错信息如下:

error: patch failed: ...
error: ... could not apply patch ...
......
hint: Use 'git am --show-current-patch=diff' to see the failed patch
Applying: v3.0.8 (#132)
Patch failed at 0001 v3.0.8 (#132)
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".

可以添加 -3 参数,手动解决冲突。

git am --abort
git am -3 *..patch

解决冲突后,继续应用 patch 文件。

git am --continue

不保留元数据

git apply *.patch

如果报错,可手动解决冲突

git apply --3way *.patch

If you enjoyed this, leave a comment~

© 2024 - 2026 kissablecho
Powered by theme astro-koharu · Inspired by Shoka