场景
在Git操作中,冲突一般出现在执行git merge
或者git rebase
操作后,出现冲突的原因一般是两个人修改了同一文件的同一区域,Git无法判断以哪个修改为准,或者两个都要,或者两个都不要。这就需要程序员手动修复。一般出现冲突后,你看到的提示信息会是这样的:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
git rebase
Auto-merging src/a.c
CONFLICT (content): Merge conflict in src/a.c
error: could not apply e06ba3a... print world
hint: Resolve all conflicts manually, mark them as resolved with
hint: "git add/rm <conflicted_files>", then run "git rebase --continue".
hint: You can instead skip this commit: run "git rebase --skip".
hint: To abort and get back to the state before "git rebase", run "git rebase --abort".
Recorded preimage for 'src/a.c'
Could not apply e06ba3a... print world
git status -s
UU src/a.c
|
git rebase
Auto-merging src/a.c
CONFLICT (content): Merge conflict in src/a.c
error: could not apply e06ba3a... print world
hint: Resolve all conflicts manually, mark them as resolved with
hint: "git add/rm <conflicted_files>", then run "git rebase --continue".
hint: You can instead skip this commit: run "git rebase --skip".
hint: To abort and get back to the state before "git rebase", run "git rebase --abort".
Recorded preimage for 'src/a.c'
Could not apply e06ba3a... print world
git status -s
UU src/a.c
通过git status -s
我们可以看到所有的冲突文件,在输出开头的UU
表示unmerged, both modified
,
打开文件后,我们可以看到对应的差异:
1
2
3
4
5
6
7
8
9
|
#include <stdio.h>
int main(int argc, char *argv[]) {
<<<<<<< HEAD
printf("hello\n");
=======
printf("world");
>>>>>>> e06ba3a (print world)
return 0;
}
|
#include <stdio.h>
int main(int argc, char *argv[]) {
<<<<<<< HEAD
printf("hello\n");
=======
printf("world");
>>>>>>> e06ba3a (print world)
return 0;
}
手动修复
上面被<<<<<<< HEAD
和=======
包围的部分是你的修改,被=======
和>>>>>>> e06ba3a (print world)
包围的部分是其他人的修改。如果我们需要两个都保留,可以修改为如下所示:
1
2
3
4
5
6
|
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("hello\n");
printf("world");
return 0;
}
|
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("hello\n");
printf("world");
return 0;
}
注意要去掉git在rebase时生成的提示符信息:<<<<<<<
, =======
, >>>>>>>
,修改完成后,继续执行rebase:
1
2
|
git add src/a.c
git rebase --continue
|
git add src/a.c
git rebase --continue
如果你有多个提交,上面的修复过程可能会出现多次,直到成功为止。