Git多分支环境部署(以meanjs项目为例)

dev开发、stage测试、prod产品,符合DO分离原则。

我们的目标是建立:

上面的upstream和fork是为了方便在github上发起PR,不是必须的。

1) Fork MEAN.JS on github

  1. 假设你已经拥有github账号和ssh key,没有请自行解决。
  2. 在github上fork meanjs/mean项目。

2) clone到本地

Clone你的fork到本地,当你需要在github发起PR时使用。

# Clone你的fork到本地
git clone https://github.com/YOU/mean.git project_folder  
cd project_folder

# 创建dev开发分支
git checkout -b dev  

3) 从源项目获取更新

# Make a remote called 'upstream' to the Official repo
git remote add upstream https://github.com/meanjs/mean.git

# fetch upstream repo data.
git fetch upstream

# now upstream branches are shown
git branch -a  
git branch -a -vv

#  Branch for MEAN.JS code - track upstream 'master' for changes
git checkout -b meanjs --track upstream/master  
git branch -a -vv

$ git status
# On branch meanjs
# Your branch is ahead of 'upstream/master' by 1 commit.
#   (use "git push" to publish your local commits)
# nothing to commit, working directory clean

# Update project from Official MEAN.JS:
# Fetch upstream.  Merge upstream/master -> current branch
# Syntax: git pull [remote] [remote branch]
git checkout meanjs  
git pull upstream master

# Or because we used --track to configure branch
git checkout meanjs  
git pull

# Switch to our dev branch and merge changes
git checkout dev  
git merge meanjs  

4) 如何向源项目发起PR

将我们fork在github的origin重命名为fork,因为我打算使用私有代码库bitbucket作为origin。

git remote rename origin fork  

要向原项目发起pull request,需要三个步骤:
a. 修改代码
b. push你的commit到你的github fork项目地址
c. 通过Github来发起PR

你必须在本地的meanjs分支操作你需要PR的内容,不要在dev或其他分支操作,否则可能误将你的私有代码发出去。

git checkout meanjs

# commit a change
touch awesome_feature.js  
git add awesome_feature.js  
git commit -am "This is going to be great! "

# merge change into local/dev and test
git checkout dev  
git merge meanjs  
# Testing...

因为我们不是原项目的团队成员,不能直接push,所以我们先push到我们在github上的fork,然后通过github发起pull request。

# Syntax: git push [remote] [branch]
git push fork meanjs  

我们push到fork的代码都会是public的,因此我们只能将本地的meanjs分支push到fork,否则别人可能看到你的私有代码。(如果误操作了,你可以删掉你在github上的fork,重新创建。)

5) 建立私有代码库

要保持你的私有代码不被公开,你需要注意以下三点:

  1. 只能在meanjs分支修改公开代码
  2. 不要从dev或者其他分支merge代码到meanjs分支
  3. 只能从meanjs分支push代码到fork

总结一点就是:公开代码放在meanjs分支,私有代码放dev等分支,且不能merge到meanjs分支。

# 添加远程代码库
git remote add origin [email protected]:YOU/PROJECT.git  
# 注意此时不会显示origin
git branch -a -vv

# 推送本地所有分支到远程代码库origin
# 此处可能需要身份验证
# 语法:git push --set-upstream 远程repo 本地分支
git push --set-upstream origin master  
git push --set-upstream origin dev

# leave meanjs's upstream as remote 'upstream'
git push origin meanjs

git branch -a -vv  

Arvin Xiang

Read more posts by this author.

Subscribe to Arvin Xiang

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!