Skip to content

Git - 补丁操作

Patch(补丁)是一个包含一组更改的文本文件,类似于 git diff 的输出。然而,Git 生成的补丁还可以包含关于 commit(提交)的元数据(metadata),例如 commit ID、作者(author)、日期(date)和提交消息(commit message)。你可以从你的 commits 创建补丁,并与他人共享,他们可以将这些更改应用到自己的仓库中。这在没有直接推送权限时共享更改或进行代码审查流程时非常有用。

假设 Jerry 在他的项目中实现了一个新功能,比如 add_numbers 函数。Jerry 可以创建他的更改的补丁文件并发送给 Tom。Tom 然后可以将此补丁应用到他自己的项目版本中。

Jerry 使用 git format-patch 命令为他最新的 commit 创建补丁。要为某个范围的 commits 或特定 commit 创建补丁,你可以指定 commit ID 或范围。例如,git format-patch -1 为最新的 commit(HEAD)创建一个补丁。

[jerry@dev-machine project/src]$ pwd
/home/jerry/project/src
[jerry@dev-machine src]$ git status -s
M math_operations.c
?? math_operations_test
[jerry@dev-machine src]$ git add math_operations.c
[jerry@dev-machine src]$ git commit -m "Added add_numbers function"
[main b4c7f09] Added add_numbers function
1 file changed, 10 insertions(+)
[jerry@dev-machine src]$ git format-patch -1 HEAD
0001-Added-add_numbers-function.patch

上面的命令在当前目录中创建了一个 .patch 文件(例如 0001-Added-add_numbers-function.patch)。Tom 现在可以使用这个补丁了。Git 提供了两个主要的命令来应用补丁:git apply 和 git am。

git apply 接受一个补丁文件(可以是原始 diff 或 Git 格式化的补丁),并将更改应用到你的工作目录(working directory)中的文件。它 不会 创建 commit。这在你想要在提交前审查更改,或者补丁是简单的 diff 且不含 commit 元数据时非常有用。

首先,Tom 可以检查补丁是否能干净地应用(apply cleanly):

[tom@dev-machine project/src]$ git apply --check 0001-Added-add_numbers-function.patch

如果没有输出,说明补丁应该能干净地应用。现在,Tom 应用补丁:

[tom@dev-machine project/src]$ pwd
/home/tom/project/src
[tom@dev-machine src]$ git status -s
[tom@dev-machine src]$ git apply 0001-Added-add_numbers-function.patch
[tom@dev-machine src]$ git status -s
M math_operations.c
?? 0001-Added-add_numbers-function.patch

补丁已应用,并且 math_operations.c 已被修改。Tom 可以使用 git diff 查看更改:

[tom@dev-machine src]$ git diff math_operations.c

输出将显示补丁引入的更改:

diff --git a/src/math_operations.c b/src/math_operations.c
index 8ab7f42..f282fcf 100644
--- a/src/math_operations.c
+++ b/src/math_operations.c
@@ -1,5 +1,12 @@
#include <stdio.h>
+int add_numbers(int a, int b)
+{
+ // 用于加两个整数的函数
+ return a + b;
+}
+
double calculate_mean(int *data, int count)
{
double sum = 0.0;

审查后,Tom 需要暂存并提交这些更改:git add math_operations.c 和 git commit -m "Incorporate add_numbers function from Jerry's patch"。

git am(apply mailbox)用于应用格式化为电子邮件消息的补丁,这正是 git format-patch 生成的格式。git am 会应用补丁 并 创建一个 commit,使用补丁文件中的元数据(作者、消息、日期)。这通常是应用 git format-patch 创建的补丁的首选方式。

如果 Tom 想要使用 git am(假设他还没有应用和提交过):

[tom@dev-machine project/src]$ git am 0001-Added-add_numbers-function.patch
Applying: Added add_numbers function

这个命令会应用更改并创建一个新的 commit,其中包含 Jerry 补丁中的原始 commit 消息和作者信息。如果存在冲突,git am 会停止并允许你解决它们。