以下是对 git format-patch
命令的全面总结,涵盖常见用法、离线打包原理及实践技巧:
git format-patch
核心作用将 Git 提交转换为标准补丁文件(.patch
),保留完整的提交元数据(作者、日期、提交信息)和代码变更,适用于离线代码迁移、跨仓库协作或代码审核场景。
场景 | 命令 | 说明 |
---|---|---|
最近 1 次提交 | git format-patch HEAD^ 或 git format-patch -1 |
生成最后一次提交的补丁 |
最近 N 次提交 | git format-patch -N (如 -3 表示最近 3 次) |
生成连续多次提交的独立补丁文件 |
提交 A 到 B 的所有变更 | git format-patch |
包含 B 但不包含 A 的提交(需 A 早于 B) |
某次提交之后的所有变更 | git format-patch |
生成从 commit-X 之后到当前 HEAD 的所有提交补丁 |
-o
指定补丁保存路径(如 -o ./patches
)git format-patch --stdout > all.patch
将多个补丁合并到单一文件--cover-letter
生成补丁集的说明文档(用于邮件列表)--suffix=.patch
自定义文件后缀# 从首次提交到某次提交(含根提交)
git format-patch --root <commit-C>
# 某次提交(含)之前的 N 次提交
git format-patch -N <commit-D>
.patch
文件是 Unix 邮箱格式(RFC 5322),包含:
From
、Date
、Subject
)diff -p --stat
格式)# 将 commit-A 到 commit-B 的所有补丁合并到 fix.patch
git format-patch commit-A..commit-B --stdout > fix.patch
0001-*
、0002-*
)。命令 | 适用场景 | 特点 |
---|---|---|
git am *.patch |
保留提交历史 | 自动创建提交,保留作者信息,推荐正式迁移 |
git apply fix.patch |
临时修改 | 仅修改文件,不生成提交,需手动 git add/commit |
若 git am
失败:
git apply --reject fix.patch # 生成 `.rej` 文件记录冲突位置
.rej
文件内容).rej
文件git add . && git am --continue
注:若需放弃,使用
git am --abort
回滚。
git log
确认目标提交;git apply --check
检测兼容性;--signoff
声明补丁应用者身份;通过
git format-patch
生成的补丁,本质是提交历史的标准化封装,结合git am
可完整还原代码变更链,是 Git 分布式协作的核心工具之一。