patch的制作和使用

diff

find differences between two files

diff [option] from-file to-file

patch

apply a diff file to an original

patch [option] originalfile patchfile

but usually just

patch -pnum < patchfile

普通patch

(1)制作patch

diff -urN version1 version2 > version1_to_version2.patch

-r 递归

-u 统一格式

-N if a file is found in only one directory, treat it as present but empty in the other directory

(2)应用patch

cd version1

patch -p1 < version1_to_version2.patch

-p1 表示忽略patch路径中的最上层目录

git中的patch

(1)git diff 生成标准的patch

# mkdir test_patch_proj

# cd test_patch_proj

# git init   // Initialize empty Git repository

# echo "hello, world" > readme.txt

# git add readme.txt   // 提交到index

# git commit -m "initial import"   // 提交到本地仓库

为了修改代码,我们建立一个新的分支。

# git branch fix

# git checkout fix   // 签出fix分支

# echo "bug fixed" >> readme.txt  // 修复完bug了:)

# git diff // 输出的就是patch的内容

# git add readme.txt

# git commit -m "fix branch"

然后把diff的输出变成patch。

# git diff master > fix_bug.patch

然后用git apply来使用这个patch。

# git checkout master

# git apply fix_bug.patch

# git add readme.txt

# git commit -m "apply fix_bug.patch to master"

验证。

# git diff fix

没有输出,证明此时master和fix分支完全相同。

(2)git format-patch生成git专用补丁

继续使用上面的例子。

比较fix和master分支,生成patch。

# git format-patch -M master

0001-fix-branch.patch

-M 表示这个patch要和哪个分支对比。

可以看到生成的patch多了一些信息:提交者、提交时间等。

使用git am来应用这种补丁。

# git am 0001-fix-branch.patch

两个commit之间的修改(包含commit):

git format-patch <commit1>..<commit2>

从某commit以来的修改(不包含commit):

git format-patch <commit>

扩展

[1] 《怎样为Linux内核打补丁》很详细的文档

[2]   内核补丁制作与提交

[3]  http://www.cnblogs.com/feisky/archive/2012/01/12/2321094.html

原文地址:https://www.cnblogs.com/aiwz/p/6333367.html