开发学院

您的位置:首页>教程>正文

教程正文

Git Patch操作

Git 补丁操作

  patch是一个文本文件,其内容类似于Git diff,但是跟代码放在一起,它还有关于提交的元数据(metadata ):例如提交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 amand和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)
   {