补丁格式
diff 原始格式
--- original_file.txt
+++ modified_file.txt
@@ -1,4 +1,4 @@
-This is the original content of the file.
+This is the modified content of the file.
-We are removing this line.
+We are adding a new line.
@@
表示修改的行号,1-4行
-
表示原始/删除内容
+
表示修改/新增内容
diff 上下文格式
不仅包含修改内容,还包含修改内容的上下行信息:
--- original_file.txt
+++ modified_file.txt
@@ -1,4 +1,4 @@
-This is the original content of the file.
+This is the modified content of the file.
It has some lines.
-We are removing this line.
+We are adding a new line.
And here is another line.
git-diff 格式
diff --git a/file.txt b/file.txt
index 1234567..abcdefg 100644
--- a/file.txt
+++ b/file.txt
@@ -1,5 +1,5 @@
This is the original content of file.txt.
-Hello, world!
+Hello, Git!
Some more lines here.
git-patch 邮件格式
邮件格式增添了From
和Subject
关键字。
From: John Doe <john@example.com>
Subject: [PATCH] Add new feature
This is a patch to add a new feature to the project.
diff --git a/file1.txt b/file1.txt
index abcdefg..1234567 100644
--- a/file1.txt
+++ b/file1.txt
@@ -1,3 +1,3 @@
This is the original content of file1.txt.
-Old line 1
-Old line 2
+New line 1
+New line 2
New line 3
quilt 格式
=== added file 'main.py'
--- /dev/null
+++ b/main.py
@@ -0,0 +1,4 @@
+def greet(name):
+ print(f"Hello, {name}!")
+
+greet("World")
补丁工具
diff 补丁
diff 用于比较两个文件a和b,并生成差异文件。
生成补丁:
# 比较两个文件
diff <源文件> <修改文件> > <xxx.patch>
# 比较文件夹
diff -Nr <源文件夹> <新文件夹> > <xxx.patch>
# 其他
-u 生成上下文补丁
-b 忽略空行比较
-i 忽略大小写
-a 比较二进制文件
应用补丁:
# 将补丁应用到源文件
patch <源文件> < <差分文件>
# 撤销目标文件上的补丁内容
patch -RE <修改文件> < <差分文件>
git 补丁
如果是使用git管理工程,那么可以针对commit-id生成补丁。
git提供了两种补丁方式,git diff
和git format-patch
。git diff
是diff的增强版,可以将多个修改合成在一个补丁文件中,但是不包含commit信息;git format-patch
是git格式的补丁,会记录commit信息。
patch 格式
生成补丁:
# 生成commit-id到HEAD之间的补丁
git format-patch <commit-id>
# 生成commit-id和commit-id之间的补丁
git format-patch <id1> <id2>
应用补丁:
# 查看是否能应用成功
git apply --check <xxx.patch>
# 应用补丁
git apply <xxx.patch>
git am <xxx.patch>
git apply 和 git am 都是 Git 中用于应用补丁的命令,但它们在应用补丁的方式和适用场景上有一些区别,主要区别如下:
补丁格式:
- git apply:适用于各种补丁格式,包括普通格式(unified format)、上下文格式(context format)和原始格式(raw format)等。
git am:主要适用于邮件格式(email format)的补丁,这些补丁通常由 git format-patch 命令生成。
应用方式: - git apply:将补丁文件中的修改直接应用到工作目录,但不会自动创建提交记录。需要手动使用 git add 和 git commit 命令来提交更改。
git am:将补丁中的修改应用为一系列的提交记录,根据补丁中的提交信息自动创建提交记录。
冲突处理:
- git apply:在应用补丁时,如果发生冲突,会将冲突标记添加到相应的文件中,并继续应用补丁。需要手动解决冲突后,使用 git add 命令标记解决的冲突。
- git am:在应用补丁时,如果发生冲突,会停止应用并等待手动解决冲突。解决冲突后,使用 git am --continue 命令继续应用剩余的补丁。
综上所述,git apply 适用于直接将补丁应用到工作目录中,手动处理冲突并手动创建提交记录。而 git am 适用于应用邮件格式补丁,自动创建提交记录,并提供更多的冲突处理功能。
diff 格式
生成补丁:
git diff <commit-id1> <commit-id2> > <diff文件名>
quilt 补丁
quilt是Debian用于管理补丁的方式,用于将多个文件修改归档为一次patch,而不至于像diff那样挨个比较。
# 创建补丁环境
quilt new
# 关联/取消关联文件到补丁
quilt add/remove <files>
# 修改文件内容后,生成补丁
refresh
# 应用补丁
patch <源文件> < <xxx.patch>