Git - 补丁操作

Patch是一个文本文件,其内容类似于Git diff,但与代码一起,它还包含有关提交的元数据;例如,提交ID,日期,提交消息等.我们可以从提交创建补丁,其他人可以将它们应用到他们的存储库.

Jerry为他的项目实现了strcat函数. Jerry可以创建他的代码路径并将其发送给Tom.然后,他可以将收到的补丁应用到他的代码中.

Jerry使用Git format-patch 命令为最新提交创建补丁.如果要为特定提交创建补丁,请使用 COMMIT_ID 和format-patch命令.

[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)
   {