Git 补丁操作
补丁是一个文本文件,其内容与Git diff类似,但除了代码之外,还包含有关提交的元数据,例如提交ID、日期、提交消息等。我们可以从提交中创建补丁,其他人可以将其应用到他们的代码库中。
Jerry为他的项目实现了strcat函数。Jerry可以创建一个代码的补丁并将其发送给Tom。然后,他可以将收到的补丁应用到自己的代码中。
Jerry使用Git的 format-patch 命令为最新的提交创建补丁。如果您想为特定的提交创建补丁,可以在format-patch命令中使用 COMMIT_ID 。
[jerry@CentOS project]pwd /home/jerry/jerry_repo/project/src [jerry@CentOS src] git status -s M string_operations.c ?? string_operations [jerry@CentOS src]git add string_operations.c [jerry@CentOS src] git commit -m "Added my_strcat function" [master b4c7f09] Added my_strcat function 1 files changed, 13 insertions(+), 0 deletions(-) [jerry@CentOS src]$ git format-patch -1 0001-Added-my_strcat-function.patch
以上命令在当前工作目录下创建 .patch 文件。Tom可以使用此补丁来修改他的文件。Git提供了两个命令来应用补丁 git am 和 git apply 。
使用 git apply 命令会修改本地文件而不创建提交,而 git am 会修改文件并创建提交。
要应用补丁并创建提交,请使用以下命令:
[tom@CentOS src]pwd /home/tom/top_repo/project/src [tom@CentOS src] git diff [tom@CentOS src]git status –s [tom@CentOS src] git apply 0001-Added-my_strcat-function.patch [tom@CentOS src]$ git status -s M string_operations.c ?? 0001-Added-my_strcat-function.patch
补丁已成功应用,现在我们可以使用 git diff 命令查看修改。
[tom@CentOS src]$ git diff
上述命令将产生以下结果 –
diff --git a/src/string_operations.c b/src/string_operations.c index 8ab7f42..f282fcf 100644 --- a/src/string_operations.c +++ b/src/string_operations.c @@ -1,5 +1,16 @@ #include <stdio.h> +char *my_strcat(char *t, char *s) diff --git a/src/string_operations.c b/src/string_operations.c index 8ab7f42..f282fcf 100644 --- a/src/string_operations.c +++ b/src/string_operations.c @@ -1,5 +1,16 @@ #include <stdio.h> +char *my_strcat(char *t, char *s) + { + char *p = t; + + + while (*p) ++p; + while (*p++ = *s++) + ; + return t; + } + size_t my_strlen(const char *s) { const char *p = s; @@ -23,6 +34,7 @@ int main(void) {
版权声明:本页面内容旨在传播知识,为用户自行发布,若有侵权等问题请及时与本网联系,我们将第一时间处理。E-mail:284563525@qq.com