如果2个修改相互干扰,合并时就会发生冲突,例如,2个人同时对一个地方做了修改。
让我们引入并解决一个冲突,来演示一下怎么解决合并冲突。
引入冲突
按如下步骤引入一个冲突:
- 创建新分支,并切换为当前分支:
git checkout -b dev2
- 在新分支下,修改
test1.txt
文件,修改文件第一行为:file name is test1.txt
,暂存并提交到新分支。 - 切换到
master
分支下,修改test1.txt
文件,修改文件第一行为:file type is txt
,暂存并提交到master
分支。 - 尝试把
dev2
分支合并到master
,执行git merge dev2
,这时就会发生冲突,输出如下提示:
Kevin@qikegu MINGW64 /g/project/git-demo (master)
$ git merge dev2
Auto-merging test1.txt
CONFLICT (content): Merge conflict in test1.txt
Automatic merge failed; fix conflicts and then commit the result.
master
分支与dev2
分支上的同个文件同一行都被修改了,合并时git无法处理这个问题。
可以运行git status
查看一下状态信息:
Kevin@qikegu MINGW64 /g/project/git-demo (master|MERGING)
$ git status
On branch master
Your branch is ahead of 'origin/master' by 5 commits.
(use "git push" to publish your local commits)
You have unmerged paths.
(fix conflicts and run "git commit")
(use "git merge --abort" to abort the merge)
Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified: test1.txt
no changes added to commit (use "git add" and/or "git commit -a")
可以看到test1.txt
的同个位置,同时被多人修改了,有冲突,无法合并,需要先解决冲突。
解决冲突
让我们来解决冲突,用编辑器打开test1.txt
。
对于简单的冲突,使用文本编辑器就可以了。对于有大量冲突的文件,就需要强大的IDE或编辑器,例如vs code。
test1.txt
的内容如下:
<<<<<<< HEAD
file type is txt
=======
file name is test1.txt
>>>>>>> dev2
this is a test text file
abcde
fghij
冲突的不同内容都已列出来了:
<<<<<<< HEAD
当前分支中的内容>>>>>>> dev2
要合并分支中的内容
解决冲突,只需确定冲突内容的取舍,同时删除git引入的特殊行。
此处把文件改成这样:
file type is txt
abcde
fghij
接下来继续本次合并,生成合并提交,要做的与普通的更改提交一样:
Kevin@qikegu MINGW64 /g/project/git-demo (master|MERGING)
$ git add test1.txt
Kevin@qikegu MINGW64 /g/project/git-demo (master|MERGING)
$ git commit -m 'resolve test1.txt conflict'
[master be504c1] resolve test1.txt conflict
Kevin@qikegu MINGW64 /g/project/git-demo (master)
$
中断合并
如果有冲突时,不想合并了,可以运行git merge --abort
中断合并。