Understanding Git Patches: A Guide to Creating and Applying Changes
Learn how to work with Git patches, which are text files representing specific changes to your repository. Discover how to create patches from commits and apply them to other repositories, facilitating collaboration and code sharing.
Git - Patch Operation
Introduction
A patch in Git is a text file similar to a Git diff but includes additional metadata such as commit ID, date, and commit messages. Developers can create patches from commits, which other developers can then apply to their repositories.
In this example, tom implements the strcat
function for his project and creates a patch to send to david, who can apply the patch to his code.
Creating a Patch
tom uses the git format-patch
command to create a patch from his latest commit. If you want to create a patch for a specific commit, use the COMMIT_ID
with the format-patch
command.
Syntax
[tom@CentOS src]$ git status -s
M string_operations.c
?? string_operations
[tom@CentOS src]$ git add string_operations.c
[tom@CentOS src]$ git commit -m "Added my_strcat function"
[master b4c7f09] Added my_strcat function
1 files changed, 13 insertions(+), 0 deletions(-)
[tom@CentOS src]$ git format-patch -1
0001-Added-my_strcat-function.patch
This command creates a .patch
file in the current working directory. david can use this patch to update his code.
Applying a Patch
Git provides two commands to apply patches: git apply
and git am
. The git apply
command modifies local files without creating a commit, while git am
applies the patch and creates a commit.
To apply the patch and create a commit, david uses the following commands:
Syntax
[david@CentOS src]$ git apply 0001-Added-my_strcat-function.patch
[david@CentOS src]$ git status -s
M string_operations.c
?? 0001-Added-my_strcat-function.patch
After applying the patch, david can view the modifications by using the git diff
command.
Syntax
[david@CentOS src]$ git diff
Output
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
+char *my_strcat(char *t, char *s)
{
char *p = t;
while (*p)
++p;
while (*p++ = *s++)
;
return t;
}
The patch is successfully applied, and now david can see the changes in his local files.