Git 远程分支的pull与push

Git 远程分支的pull与push

远程分支信息查看

git branch -r #查看远程分支
git branch -a #查看全部分支,本地和远程

git remote show [remote-name] #查看远程仓库信息

其中git remote show [remote-name]展现的信息包括:git

  • 会列出远程仓库的 URL 与跟踪分支的信息
  • 列出了当你在特定的分支上执行 git push 会自动地推送到哪个远程分支
  • 列出了哪些远程分支不在你的本地
  • 哪些远程分支已经从服务器上移除了
  • 执行 git pull 时哪些分支会自动合并
  • ……

检出远程非master分支到本地

git checkout -b local origin/daily/dev

上面的方法能够直接检出远程分支到本地,在本地新建local分支,并切换到local分支上,注意本地分支和远程分支不一样名。shell

这个方法会自动建立远程分支 /daily/dev 和本地分支local的跟踪关系, 经过git remote show origin能够看到包含以下信息:服务器

Local branches configured for 'git pull':
     local merges with remote /daily/dev
     master       merges with remote master
  Local ref configured for 'git push':
    master pushes to master (up to date)

其中Local branches configured for 'git pull':下的就是upstream跟踪分支。工具

能够看出,远程分支 /daily/dev 和本地分支local 创建了git pull的关系,可是没有创建git push的关系。此时若是强行push,不会成功,会出现以下提示:gitlab

fatal: The current branch new has no upstream branch.  
To push the current branch and set the remote as upstream, use
    git push --set-upstream origin develop

Git默认push设置

咱们知道经过git clone git@gitlab.xxx.com:xxxxx.git能够创建默认的本地master分支和远程master分支的pull和push的关系,可是咱们没法经过clone命令检出非master分支,那么对于非master分支怎么办呢?code

Git中push.default能够指定在没有明确指定远程分支的状况下,默认push的远程分支,其取值能够是:blog

  • nothing - push操做无效,除非显式指定远程分支(想让push变得简单的就不要用这个)
  • current - push当前分支到远程同名分支,若是远程同名分支不存在则自动建立同名分支(central 和 non-central workflows都适用)
  • upstream - push当前分支到它的upstream分支上(一般用于central workflow)
  • simple - simple和upstream是类似的(一般用于central workflow),只有一点不一样,simple必须保证本地分支和它的远程 upstream分支同名,不然会拒绝push操做
  • matching - push全部本地和远程两端都存在的同名分支

central / non-central workflows 是Git的两种常见工做流场景:rem

  • central workflows - 集中式工做流,一个分支的push和pull都是同一个远程仓库
  • non-central workflows - 非集中式工做流,一个分支的push和pull可能分别都有不一样的远程仓库

在Git 2.0以前,push.default的内建值被设为'matching',2.0以后则被更改成了'simple'。get

在了解push.default以后,咱们有以下几种比较好的从远程分支检出本地分支的方法(基于V2.0+):workflow

解法一

因此若是你只有一个远程仓库,且你想检出的分支名称和远程分支不一样名(有些管理工具会自动生成比较丑的远程分支名,相似:/features/2017-03-31-featuresA-1),那么你能够经过设置push.default 默认推送到pull的远程分支(upstream 分支):

#检出重命名
git checkout -b dev origin/features/2017-03-31-featuresA-1
#设置push.default为upstream
git config --global push.default upstream
#or
git config push.default upstream
#取消设置
git config --unset push.default

解法二

若是不想经过修改upstream,那么只能经过设置检出本地分支名称和远程分支名称相同:

git checkout -b <BRANCH-NAME> <REMOTE-NAME>/<BRANCH-NAME>

注意:若是使用git checkout -b features/feature_1 origin/features/feature_1检出,那么远程分支名称是features/feature_1,而不是origin/features/feature_1

解法三

这个也不算什么解法,可是强烈推荐,就是创建远程分支的时候,取个好点的名字。

git clone git@gitlab.xxx.com:xxxxx.git
#从master创建新分支
git checkout -b dev
#push并创建同名远程分支
git push origin dev

参考

Git push与pull的默认行为
Git config

相关文章
相关标签/搜索