新建分支——git branch,git checkout
设想此时,项目已经有如下提交:
此时为解决issue 53
,创建并切换到iss53
分支,即:
$ git checkout -b iss53
上述命令是下面两条命令的简写:
$ git branch iss53
$ git checkout iss53
在iss53
分支提交,iss53
向前移动:
此时,线上出现问题需要紧急修复,需要切换到master
分支,修复之前,iss53
分支的内容应保持已提交状态,避免切换分支导致内容丢失。此时通过git checkout master
切换回master分支
,此时工作区和C2
提交时一致(Git会自动添加、删除、修改文件)。
为了修复问题,创建紧急修复分支hotfix
,在hotfix
分支解决问题并提交,hotfix
向前移动:
合并分支——git merge
hotfix
测试通过后,合并回master
分支部署线上:
$ git checkout master 合并回master分支要先切到master
$ git merge hotfix 将hotfix合并入当前分支,即master
Updating f42c576..3a0874c
Fast-forward
index.html | 2 ++
1 file changed, 2 insertions(+)
合并时,由于master
指向的C2
是hotfix
指向的C4
的直接上游,Git简单地将指针向前移动,即快进fast-forward
,此时master
都指向了提交对象C4
。
问题解决,删除不再需要的分支hotfix
:
$ git branch -d hotfix
切换回iss53
分支,继续之前的工作并提交:
由于线上环境一般只能部署master
分支的代码,iss53
并不包含hotfix
的提交C4
,此时面临两种选择:
- 及时将
hotfix
的修改并入iss53
,使master
保持iss53
的直接上游 - 在
iss53
继续工作,最后合入master
若选择后者,假设此时issue 53
开发完成,需要合入master
:
$ git checkout master
$ git merge iss53
Merge made by the 'recursive' strategy.
index.html | 1 +
1 file changed, 1 insertion(+)
与合并hotfix
不同,不再是fast-forward
,而是Merge made by 'recursive' strategy
。
原因是master
指向的C4
不是iss53
指向的C5
的直接上游,Git不能直接进行快进,而是基于master
的C4
,iss53
的C5
,以及共同祖先C2
,做三方合并,合并结果如图:
提交对象C6
是此次三方合并的新的快照,C6
是一次合并提交,它有不止一个父提交。因为切换到了master
进行的merge
操作,所以master
指向了最新的提交C6
,iss53
仍然指向其合并之前的提交C5
,此时iss53
可以删除git branch -d iss53
。
合并冲突——git merge,git add
如果在两个分支对同一文件的同一部分进行了不同修改,合并时会产生合并冲突:
$ git merge iss53
Auto-merging index.html
CONFLICT (content): Merge conflict in index.html
Automatic merge failed; fix conflicts and then commit the result.
CONFLICT
即遇到了冲突,Git将冲突文件做了合并,但没有创建合并提交,git status
时会出现在Unmerged paths
下:
$ git status
On branch master
You have unmerged paths.
(fix conflicts and run "git commit")
Unmerged paths:
(use "git add <file>" to mark resolution)
both modified: index.html
显示index.html
被同时修改了,解决冲突之后,执行git add <file>
标记冲突已解决。
冲突文件样例:
<<<<<<< HEAD:index.html
<div id="footer">contact : email.support@github.com</div>
=======
<div id="footer">
please contact us at support@github.com
</div>
>>>>>>> iss53:index.html
=======
之上,为当前分支的内容,之下为合并进来的内容,选择或修改成合适的内容之后,执行git add
标记为已解决,将会出现在git status
的Changes to be committed
下。
执行git commit
,将本次的合并提交对象提交。
分支管理——git branch
$ git branch 当前分支列表,结果中的*星号,表示HEAD指向的分支
$ git branch -v 显示每个分支的最后一次提交
iss53 93b412c fix javascript issue
* master 7a98805 Merge branch 'iss53' // 当前处于master分支
testing 782fd34 add scott to the author list in the readmes
$ git branch --merged 只显示已经合并到当前分支的分支
iss53 // iss53已经合并到master
* master
$ git branch --no-merged 只显示尚未合并到当前分支的分支
testing