Git Commit 生成与合入 Patch 指南
1. 生成 Patch 文件
1.1 使用 Diff 命令生成 Patch
通过 diff
命令,可以为两个目录生成差异补丁,这对于文件夹内文件的修改非常有用,可以生成一个包含所有修改操作的补丁文件。[3]
前提条件:
- 需要对比的两个目录的顶层路径深度需一致。[4]若不一致,建议使用软链接来满足此要求。[5]
示例:
假设有两个目录:
- 目录1:
/media/data2/quectel/r12/cn_kj_r12a07/ql-ol-kernel/
- 目录2:
/tmp/sdk/cn_kj_r12a07/ql-ol-kernel/
可以通过以下命令创建软链接并生成补丁:
mkdir patch
ln -s /media/data2/quectel/r12/cn_kj_r12a07/ql-ol-kernel/ patch/new
ln -s /tmp/sdk/cn_kj_r12a07/ql-ol-kernel/ patch/old
若只修改了部分目录(如 arch/arm/boot/dts/qcom,drivers,sound),则只需对比这些路径:
cd patch
diff -Naur old/arch/arm/boot/dts/qcom new/arch/arm/boot/dts/qcom > gpio-export.diff
diff -Naur old/drivers new/drivers >> gpio-export.diff
diff -Naur old/sound new/sound >> gpio-export.diff
参数说明:
- -N: 将不存在的文件视为空文件。
- -a: 将所有文件视为文本文件处理。
- -u: 输出差异时附带差异前后三行的内容。
- -r: 递归比较所有子目录。
注意:
- 确保生成的补丁中,对比文件路径的顶层路径一致,以便合并时能正确找到对应文件。
1.2 使用 Git Format-Patch 生成 Patch
在 Git 中,可以使用 git format-patch 命令生成特定 commit 的补丁文件。
步骤:
- 确保已提交想要生成补丁的 commit。
- 使用 git format-patch 命令生成补丁文件。
示例:
- 生成最新提交的补丁:
git format-patch -1 HEAD
- 为特定 commit 生成补丁:
git format-patch -1 <commit-hash>
- 为一系列 commits 生成补丁:
git format-patch <commit-hash1>..<commit-hash2>
常用命令:
$ git format-patch HEAD^ # 生成最近的1次commit的patch
$ git format-patch HEAD^^ # 生成最近的2次commit的patch
$ git format-patch HEAD^^^ # 生成最近的3次commit的patch
$ git format-patch <r1>..<r2> # 生成两个commit间的修改的patch
$ git format-patch -1 <r1> # 生成单个commit的patch
$ git format-patch --root <r1> # 生成从根到r1提交的所有patch
2. 合入 Patch 文件
2.1 使用 Patch 命令合入
将生成的 .diff 或 .patch 文件复制到目标目录,然后使用 patch 命令合入。
示例:
cp gpio-export.diff /tmp/sdk/cn_kj_r12a07/ql-ol-kernel/
patch -p1 < gpio-export.diff
参数说明:
- -p1: 合入时忽略第一层目录。例如,.diff 文件中的 new/sound/soc/soc-jack.c 路径,查找时会忽略 new/ 前缀。
- -pn: 忽略 n 层目录。
撤销补丁:
patch -p1 -RE < /media/data2/quectel/r12/patch/gpio-export.diff
参数说明:
- -R: 还原修改,即撤销合入的补丁。
- -E: 删除合入补丁后的空文件。
通过以上步骤,您可以轻松地生成并合入 Git commit 的 patch 文件,从而方便地进行代码的审查和合并。