我在Git中创建了一个新分支:
git branch my_branch
推动它:
git push origin my_branch
现在假设有人在服务器上做了一些更改,我想从origin/my_branch中提取。我愿意:
git pull
但我得到:
You asked me to pull without telling me which branch you
want to merge with, and 'branch.my_branch.merge' in
your configuration file does not tell me, either. Please
specify which branch you want to use on the command line and
try again (e.g. 'git pull <repository> <refspec>').
See git-pull(1) for details.
If you often merge with the same branch, you may want to
use something like the following in your configuration file:
[branch "my_branch"]
remote = <nickname>
merge = <remote-ref>
[remote "<nickname>"]
url = <url>
fetch = <refspec>
See git-config(1) for details.
我了解到,我可以通过以下方式实现:
git branch --set-upstream my_branch origin/my_branch
但为什么我需要为我创建的每个分支都这样做?如果我将my_branch推到origin/my_branch,那么我会想将origin/mi_branch拉到my_brance,这不是很明显吗?如何将此设置为默认行为?
这里有很多很好的答案,然而,所有这些都要求您在运行git pull之前正确地执行其他操作
使用别名来完成诸如“通过创建本地正在正确跟踪的远程分支,使git push按应有的方式工作”之类的工作当然会有所帮助。然而,当你忘记使用它们,或者经历了不同的工作流程时,这些都不会对你有所帮助。
这里有一个bash函数,您可以使用它来按应该的方式进行拉取,方法是检测何时未配置远程合并目标,但远程上有一个与本地分支同名的分支,然后将该分支设置为合并目标,然后进行拉取。
git-pulldown() {
head="$(git rev-parse --abbrev-ref HEAD)"
if [[ $(git config "branch.$head.merge") ]]; then #there's already a merge target configured, just pull as normal from there
git pull
else
if [[ $(git ls-remote --heads origin $head) ]]; then #there is an upstream branch existing with the same name as our branch
git branch --set-upstream-to origin/$head #set merge target to upstream branch with same name
git pull
else #fail with explanation
echo "Branch $head has no upstream or merge target! You will likely have to push first, or manually configure it"
return 1
fi
fi
}
这里有很多很好的答案,然而,所有这些都要求您在运行git pull之前正确地执行其他操作
使用别名来完成诸如“通过创建本地正在正确跟踪的远程分支,使git push按应有的方式工作”之类的工作当然会有所帮助。然而,当你忘记使用它们,或者经历了不同的工作流程时,这些都不会对你有所帮助。
这里有一个bash函数,您可以使用它来按应该的方式进行拉取,方法是检测何时未配置远程合并目标,但远程上有一个与本地分支同名的分支,然后将该分支设置为合并目标,然后进行拉取。
git-pulldown() {
head="$(git rev-parse --abbrev-ref HEAD)"
if [[ $(git config "branch.$head.merge") ]]; then #there's already a merge target configured, just pull as normal from there
git pull
else
if [[ $(git ls-remote --heads origin $head) ]]; then #there is an upstream branch existing with the same name as our branch
git branch --set-upstream-to origin/$head #set merge target to upstream branch with same name
git pull
else #fail with explanation
echo "Branch $head has no upstream or merge target! You will likely have to push first, or manually configure it"
return 1
fi
fi
}
更新:push.autoSetupRemote现在终于以更简单的方式解决了这个问题!有关更多信息,请参阅此处的另一个答案。
原答覆:
我使用这个Git别名,而不是每次从Git复制/粘贴建议:https://gist.github.com/ekilah/88a880c84a50b73bd306
复制的源代码如下(将其添加到~/.gitconfig文件中):
[alias]
pushup = "!gitbranchname() { git symbolic-ref --short HEAD; }; gitpushupstream() { git push --set-upstream origin `gitbranchname`; }; gitpushupstream"