【git】代码patch包生成和合入

发布时间 2023-07-08 13:13:35作者: -zx-

patch合入

git am

git am会直接将patch的所有信息打上去,而且不用重新git add和git commit,author也是patch的author而不是打patch的人

常用命令

git am 0001-limit-log-function.patch           # 将名字为0001-limit-log-function.patch的patch打上
git am --signoff 0001-limit-log-function.patch # 添加-s或者--signoff,还可以把自己的名字添加为signed off by信息,作用是注明打patch的人是谁,因为有时打patch的人并不是patch的作者
git am ~/patch-set/*.patch                     # 将路径~/patch-set/*.patch 按照先后顺序打上
git am --abort                                 # 当git am失败时,用以将已经在am过程中打上的patch废弃掉(比如有三个patch,打到第三个patch时有冲突,那么这条命令会把打上的前两个patch丢弃掉,返回没有打patch的状态)
git am --resolved                              # 当git am失败,解决完冲突后,这条命令会接着打patch

如有提示“patch does not apply”,表示patch冲突,手动解决完冲突后,继续合入

git am --continue

或者忽略

git am --skip

或者停止合入

git am --abort

git apply

git apply是将补丁文件应用到代码库中,但不会自动创建提交记录。而且使用git apply可以快速地测试一个补丁,检查它是否会导致任何问题或冲突,但是需要手动创建提交记录来记录这个补丁被应用了。但是git apply并不会将commit message等打上去,打完patch后需要重新git add和git commit。

常用命令

git apply --stat 0001-limit-log-function.patch          # 查看patch的情况
git apply --check 0001-limit-log-function.patch         # 检查patch是否能够打上,如果没有任何输出,则说明无冲突,可以打上

打入patch

git apply xxx.patch

如果git与需要打patch的文件不在一个目录(git 在framework下,patch要打入到frameworks/base/下)

git apply --check --directory=base/ xxx.patch
git apply --directory=base/ xxx.patch

如果有冲突,可以先导出冲突

git apply --reject xxxx.patch

此时在代码工程路径下生成.rej结尾的冲突文件,手动修改完冲突点后

git add 修改文件

然后解决冲突后合入

git am --resolved

patch生成

git format-patch

常用命令

git format-patch HEAD^       #生成最近的1次commit的patch
git format-patch HEAD^^      #生成最近的2次commit的patch
git format-patch HEAD^^^     #生成最近的3次commit的patch
git format-patch HEAD^^^^    #生成最近的4次commit的patch
git format-patch <r1>..<r2>  #生成两个commit间的修改的patch(包含两个commit. <r1>和<r2>都是具体的commit号)
git format-patch -1 <r1>     #生成单个commit的patch
git format-patch <r1>        #生成某commit以来的修改patch(不包含该commit)
git format-patch --root <r1> #生成从根到r1提交的所有patch

git diff

将所有修改文件打包成patch

git diff > test.patch

只生成一个文件的patch

git diff test.c > test.patch











参考文章:

https://zhuanlan.zhihu.com/p/104055075