如何向开源项目贡献代码?Git与Github的配置和使用
创建ssh key,配置git
-
设置username和email
git config --global user.name "He Zhou" git config --global user.email "zhouhegu@gmail.com"
-
通过终端命令创建ssh key
ssh-keygen -t rsa -C "zhouhegu@gmail.com"
此步骤需要输入邮箱对应的github账户密码,创建的key默认存储在路径下的/.ssh/id_rsa和/.ssh/id_rsa.pub。
查看并复制keyvim .ssh/id_rsa.pub
-
登陆GitHub账号点击Settings添加ssh key
-
添加完成后在终端验证能否链接github即可
ssh -T git@github.com
项目仓库管理
- fork原始项目到自己的账号下。fork项目https://github.com/vuejs/vue到自己账户的仓库下,可以称之为原始仓库(主仓库)的子仓库。
- clone克隆fork后的子仓库到本地,指定master分支。
从GitHub上clone一个repo到本地时,除非你是这个repo到contributor,否则你是不能向向其pull request的,此时,该远程的repo对于本地repo来说就是upstream。git clone -b master https://github.com/zhouhegu/vue.git
- 从GitHub上fork一个repo后,再clone forked repo到本地,你是可以任意向其pull request的,此时远程的forked repo对于本地repo来说就是origin。
- 如果是upstream repo,你只可以拉取最新代码
git fetch
,从而保证本地的仓库与源仓库同步。 - 如果是origin repo,就是你自己forked repo,你可以做任何推拉操作(push and pull)。
- 你可以通过pull request向upstream repo贡献代码。
- 设置upstream
设置成功后可通过git remote add upstream https://github.com/vuejs/vue.git
git remote -v
查看
之后就可以拉取远程的upstream repo并更新本地master分支git remote -v origin https://github.com/zhouhegu/vue.git (fetch) origin https://github.com/zhouhegu/vue.git (push) upstream https://github.com/vuejs/vue.git (fetch) upstream https://github.com/vuejs/vue.git (push)
git fetch upstream git checkout master git rebase upstream/master
- 提交修改到本地仓库
# 添加修改过的文件 git add 文件名 # 添加修改的所有文件 git add -A # 提交commit git commit -m "修改的描述"
- 将修改后的代码push到子仓库上
完成upstream更新同步,并将修改提交到本地仓库后,可以将代码push到子仓库中。git push origin master
- 向主仓库发起pull request
参考资料
向开源项目贡献代码那点事
Github中origin和upstream的区别
使用 git upstream 从其他远程仓库同步分支
Git分支-变基