合并冲突
在一个新分支上开发时,修改了一个文件内容,比如:
$ git checkout -b feature
Switched to a new branch ‘feature’
修改文件readme.txt最后一行,改为
Creating a new branch is quick AND simple.
然后在feature分支上提交
$ git add readme.txt
$ git commit -m “AND simple”
[feature 65f1845] AND simple
1 file changed, 1 insertion(+), 1 deletion(-)
然后再切换到master分支
$ git checkout master
Switched to branch ‘master’
修改文件readme.txt最后一行,改为
Creating a new branch is quick & simple.
然后在master分支上提交
$ git add readme.txt
$ git commit -m “& simple”
[master 38861b0] & simple
1 file changed, 1 insertion(+), 1 deletion(-)
现在,master分支和feature分支各自都分别有新的提交,变成了这样:
这种情况下,Git无法执行“快速合并”,只能试图把各自的修改合并起来,但这种合并就可能会有冲突
$ git merge feature
Auto-merging readme.txt
CONFLICT (content): Merge conflict in readme.txt
Automatic merge failed; fix conflicts and then commit the result.
Git告诉我们,readme.txt文件存在冲突,必须手动解决冲突后再提交
git status也可以告诉我们冲突的文件
$ git status
On branch master
You have unmerged paths.
(fix conflicts and run “git commit”)
Unmerged paths:
(use “git add …” to mark resolution)
both modified: readme.txt
no changes added to commit (use “git add” and/or “git commit -a”)
解决冲突
当Git无法自动合并分支时,就必须首先解决冲突。解决冲突后,再提交,合并完成。
解决冲突就是把Git合并失败的文件手动编辑为我们希望的内容,再提交。
查看一下冲突文件的内容
$ cat readme.txt
git is a distributed version control system.
git is free sofrware distributed under the GPL.
git is a mutable index called stage.
git tracks changes of files.
creating a new branch is quick and simple.
demi change something else.
<<<<<<< HEAD
creating a new branch is quick & simple.
=======
creating a new branch is quick AND simple .
feature
Git用<<<<<<<,=======,>>>>>>>标记出不同分支的内容
将文件内容修改如下后保存,及提交
Creating a new branch is quick and simple.
$ git add readme.txt
$ git commit -m “conflict fixed”
[master a3ca253] conflict fixed
现在master分支和feature1分支变成了下图所示:
用带参数的git log也可以看到分支的合并情况
$ git log --graph --pretty=oneline --abbrev-commit
- a3ca253 conflict fixed
|\
| * 65f1845 and simple
- | 38861b0 & simple
|/
-
3fd20e0 branch test
-
db995d6 remove test file
-
1b20f77 new test file
-
9140c12 merge with no-ff
|\
| * c115606 add merge
|/
- 382dccf conflict fixed
|\
| * 2be6792 and simple
- | 5582737 & simple
|/
-
79ecc03 branch test
-
591bd0e remove test.txt
-
e3d8632 add test.txt
-
ac4cf6c git tracks changes twice
-
c7ef684 git tracks changes
-
a547464 understand how stage works
-
95f796b append GPL
-
6fd762a add distributed
-
5cd1965 wrote a readme file
最后,删除feature分支,工作完成
$ git branch -d feature
Deleted branch feature (was 65f1845).