Note: git and patch

Published 2026-02-24 00:50 Updated 2026-02-24 00:41 339 words 2 min read

After cloning or creating a repository using a template and setting it as a private repository, it becomes difficult to synchronize updates from the original repository. This article introduces how to generate a patch file using git and how to synchronize updates from the original repository through the patch file.

Translated by AI model Qwen/Qwen3-8B.

Source Language: Simplified Chinese, Target Language: english, Translation Time: 2026-05-01 04:05

.

AI translation is for reference only. Accuracy is not guaranteed, please refer to the original text.

Messy description

After cloning or creating a repository using a template and setting it to a private repository, it's not easy to synchronize updates from the original repository.

This article introduces how to generate a patch file through git, and how to synchronize updates from the original repository using the patch file.

Generating patch files

Generate a patch for the latest commit

git format-patch HEAD~

# 或
git format-patch -1

Generate a patch for a specific commit (e.g. abc123)

git format-patch -1 abc123

Generate patch files for multiple commits

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

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

Applying patch files

Preserve metadata

git am *.patch

If the error message is as follows:

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".

You can add the -3 parameter and manually resolve conflicts.

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

After resolving conflicts, continue applying the patch file.

git am --continue

Do not preserve metadata

git apply *.patch

If an error occurs, you can manually resolve conflicts

git apply --3way *.patch

If you enjoyed this, leave a comment~