Git 系列文章(三)—— 分支

文章来自我的博客
正文之前
上一篇文章中讲述了 Git 的基本操作,这一篇文章着重将其中的分支相关的操作
正文
在 GitHub 的仓库中,展现给世人的仓库内容都是 master 主分支的,在团队成员对仓库进行改动时,需要将此仓库 fork 至自己的账户中,并创建分支,在自己创建的分支中对仓库进行修改,然后对源仓库的 master 进行 pull request
一句话,对仓库做贡献就三个步骤:
-
fork 到自己仓库
-
做改动
-
pull request
注意的是,在创建了 pull request,在拥有者还没确认之前,如果还有改动,就别再创建 pull request,直接在你自己的分支上提交就可以(下文会验证),之前没有这个概念,在自己的项目里,一项功能用了 3 个 PR,汗颜:

实战演练
创建分支
还是用上次创建的 Git-test 仓库来做演示:
首先我们先看到本地仓库和远程仓库都只有 master 分支:

然后我们在本地仓库新建一个分支:
git checkout -b A
推送至远程仓库:
git push origin A
就会发现远程仓库有了分支 A:

创建 PR
这时候我们切换到分支 A 中,将 README.md 的内容修改为:test from branch A
修改完之后回到仓库界面,会发现有个提示,我们按照提示创建 pull request:

填写信息,并观察此次合并有哪些文件改动,在最下方发现了 README.md 文档的改动:

然后创建 pull request:

需要说明的是
因为这里是我一个人操作的,所以拥有者和贡献者都是我,但是在其他情况下,贡献者一般不是本人,所以在这里需要说明一点,贡献完了之后,需要拥有者来点击 Merge pull request
这个按钮,才能将分支合并,贡献者是看不见这个按钮的
这里先不急着合并,来验证一下上面的说法,在创建 pull request 之后,如果有更新怎么办:
将 README.md 中添加一行:Git-test,然后提交至分支 A:

然后我们再到刚才创建的 pull request 中查看一下:

点击 Files changed
就会发现创建 pull request 之前的文件和现在的文件有什么区别:

合并
点击合并之后,PR 就处于关闭状态,仓库的文件也改变了:

从远程仓库拉取分支
我们在远程仓库创建一个分支 B,然后用 git checkout -b B origin/B
从远程仓库拉取分支并切换到该分支:

其他的操作都是一样的,本地改文件,提交,GitHub 上 PR
到此,分支的基本操作就结束了
GitHub 就是用来进行团队合作开发的,所以在团队使用 GitHub 时有一些注意事项,下一篇文章会讲述