Git基本操作

.gitignore

1
2
3
4
5
6
7
8
9
10
11
12
# no .a files 
*.a
# but do track lib.a, even though you're ignoring .a files above
!lib.a
# only ignore the TODO file in the current directory, not subdir/TODO
/TODO
# ignore all files in the build/ directory
build/
# ignore doc/notes.txt, but not doc/server/arch.txt
doc/*.txt
# ignore all .pdf files in the doc/ directory
doc/**/*.pdf

patch

生成 patch

git diff

1
2
3
4
#只想 patch Test.java 文件
git diff Test.java > test.patch
# 把所有的修改文件打成 patch
git diff > test.patch

git format-patch

1
2
3
4
5
6
7
8
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(生成的patch不包含r1. <r1>和<r2>都是具体的commit号)
git format-patch -1 <r1> #生成单个commit的patch
git format-patch <r1> #生成某commit以来的修改patch(不包含该commit)
git format-patch --root <r1> #生成从根到r1提交的所有patch

应用 patch

git am

  • 直接将patch的所有信息打上去,而且不用重新git add和git commit,author也是patch的author而不是打patch的人。
    1
    2
    git am --abort                                 # 当git am失败时,用以将已经在am过程中打上的patch废弃掉(比如有三个patch,打到第三个patch时有冲突,那么这条命令会把打上的前两个patch丢弃掉,返回没有打patch的状态)
    git am --resolved # 当git am失败,解决完冲突后,这条命令会接着打patch

git apply

  • git apply并不会将commit message等打上去,打完patch后需要重新git add和git commit。

检查 patch 情况

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

冲突处理

方式一(编辑冲突的 patch 文件)

  1. 根据git am失败的信息,找到发生冲突的具体patch文件,然后用命令git apply –reject ,强行打这个patch,发生冲突的部分会保存为.rej文件(例如发生冲突的文件是a.txt,那么运行完这个命令后,发生conflict的部分会保存为a.txt.rej),未发生冲突的部分会成功打上patch
  2. 根据.rej文件,通过编辑该patch文件的方式解决冲突
  3. 废弃上一条am命令已经打了的patch:git am –abort
  4. 重新打patch:git am ~/patch-set/*.patchpatch

方式二(编辑冲突的源码)

  1. 根据git am失败的信息,找到发生冲突的具体patch文件,然后用命令git apply –reject ,强行打这个patch,发生冲突的部分会保存为.rej文件(例如发生冲突的文件是a.txt,那么运行完这个命令后,发生conflict的部分会保存为a.txt.rej),未发生冲突的部分会成功打上patch
  2. 根据.rej文件,通过编辑发生冲突的code文件的方式解决冲突
  3. 将该patch涉及到的所有文件(不仅仅是发生冲突的文件)通过命令git add 添加到工作区中
  4. 告诉git冲突已经解决,继续打patch: git am –resolved (git am –resolved 和 git am –continue是一样的)

强制打 patch

1
git apply --reject xxx.patch