3.1 分支管理工作流
分支管理工作流有:Git Flow ,Github Flow 和 Gitlab Flow (不过多说明)
以下以Github 工作流作为演示。
- 在GitHub新建一个仓库用于学习测试,然后复制仓库地址(http,ssh)都可以。
$ git clone https://github.com/kjasn/git_test.git # 我用的是 http 协议的仓库地址
Cloning into 'git_test'...
warning: You appear to have cloned an empty repository. # 因为新建的是一个空仓库,什么也没加
- 克隆的仓库存放在当前目录下的 git_test 目录下,切换到仓库目录下,随便创建一个文件用来演示提交。 eg:
- add,commit并push
然后在Github仓库页面刷新后可以看到新添加的readme文件。
新建一个Feature分支:
push之后,自动创建了一个向main分支合并的pull request
在Feature分支更新readme文件然后push(图中链接)。访问链接可以查看提交的代码变更,是否与main分支有冲突,解决冲突后可以选择是否与main分支合并。
设置main分支保护,以防错误的提交代码影响到main分支:
演示更新提交,然后直接push:
$ git push origin main
Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Delta compression using up to 12 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 298 bytes | 298.00 KiB/s, done.
Total 3 (delta 1), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (1/1), completed with 1 local object.
remote: error: GH006: Protected branch update failed for refs/heads/main.
remote: error: Changes must be made through a pull request.
To github.com:kjasn/git_test.git
! [remote rejected] main -> main (protected branch hook declined) # 不允许直接push
error: failed to push some refs to 'github.com:kjasn/git_test.git'
3.2 代码合并
- Fast-Forward
不会产生一个 merge 节点,合并后保持一个线性历史,如果 target 分支有了更新,则需要通过 rebase 操作更新source branch 后才可以合入。图示:
- Three-Way Merge
三方合并,会产生一个新的 merge 节点。图示:
- 演示:
Fast-Forward
- 不会生成merge结点
Three-Way Merge
- 生成一个merge结点
3.3 选择合适的工作流
- 选择原则
没有最好的,只有最合适的
- 针对小型团队合作,推荐使用 Github 工作流即可
- 尽量保证少量多次,最好不要一次性提交上千行代码
- 提交 Pull Request 后最少需要保证有 CR 后再合入
- 主干分支尽量保持整洁,使用 fast-forward 合入方式,合入前进行 rebase
- 大型团队合作,根据自己的需要指定不同的工作流,不需要局限在某种流程中。