我们可以通过git version确定当前的git版本(如果小于2.0,更新是个更好的选择),通过
git config --global push.default [option]
改变push.default的默认行为(或者也可直接编辑~/.gitconfig文件)。

push.default 有以下几个可选值:
nothing, current, upstream, simple, matching

其用途分别为:

nothing - push操作无效,除非显式指定远程分支,例如git push origin develop(我觉得。。。可以给那些不愿学git的同事配上此项)。

current - push当前分支到远程同名分支,如果远程同名分支不存在则自动创建同名分支。

upstream - push当前分支到它的upstream分支上(这一项其实用于经常从本地分支push/pull到同一远程仓库的情景,这种模式叫做central workflow)。

simple - simple和upstream是相似的,只有一点不同,simple必须保证本地分支和它的远程 upstream分支同名,否则会拒绝push操作。

matching - push所有本地和远程两端都存在的同名分支

git pull
弄清楚git push的默认行为后,再来看看git pull。

当我们未指定当前分支的upstream时,通常git pull操作会得到如下的提示:

There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details

git pull <remote> <branch>

If you wish to set tracking information for this branch you can do so with:

git branch --set-upstream-to=origin/<branch> new1

git pull的默认行为和git push完全不同。
当我们执行git pull的时候,实际上是做了git fetch + git merge操作,fetch操作将会更新本地仓库的remote tracking,也就是refs/remotes中的代码,并不会对refs/heads中本地当前的代码造成影响。

当我们进行pull的第二个行为merge时,对git来说,如果我们没有设定当前分支的upstream,它并不知道我们要合并哪个分支到当前分支,所以我们需要通过下面的代码指定当前分支的upstream:

git branch --set-upstream-to=origin/ develop
// 或者git push --set-upstream origin develop
实际上,如果我们没有指定upstream,git在merge时会访问git config中当前分支(develop)merge的默认配置,我们可以通过配置下面的内容指定某个分支的默认merge操作

[branch "develop"]
remote = origin
merge = refs/heads/develop // [1]为什么不是refs/remotes/develop?

或者通过command-line直接设置:

git config branch.develop.merge refs/heads/develop
这样当我们在develop分支git pull时,如果没有指定upstream分支,git将根据我们的config文件去merge origin/develop;如果指定了upstream分支,则会忽略config中的merge默认配置。

以上就是git push和git pull操作的全部默认行为,如有错误,欢迎斧正

标签: git

添加新评论