为什么在git push时会推送到两个分支?

19

是什么原因会导致'git push'尝试提交到两个分支?我正在自己的分支上工作,该分支位于共享存储库中...以及一个主分支。现在我只想推送到我的个人分支,这也成功了,但它还尝试推送到主分支并被拒绝了。看起来像这样:

foo$ git push
Counting objects: 38, done.
Delta compression using 2 threads.
Compressing objects: 100% (19/19), done.
Writing objects: 100% (21/21), 9.73 KiB, done.
Total 21 (delta 14), reused 0 (delta 0)
To ssh://example.com/project.git
   8184634..86b621e  mybranch -> mybranch
 ! [rejected]        master -> master (non-fast forward)
error: failed to push some refs to 'ssh://example.com/project.git'  

我的配置看起来像这样:

remote.origin.url=ssh://example.com/project.git
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
branch.master.remote=origin
branch.master.merge=refs/heads/master
branch.mybranch.remote=origin
branch.mybranch.merge=refs/heads/mybranch  

Esko提到他正在推送到两个分支是因为它们都在我的配置文件中。如果我想要推送到这两个分支,但不是同时进行呢?当我检出了mybranch并且使用git push时,我显然是要推送mybranch而不是master。有时我会检出master,编辑代码,并想要提交/推送那个分支。有没有一种方法让它们共存?

2个回答

28

当使用 git push 命令且没有参数时,它会将所有本地分支推送到具有相同名称的远程分支。由于您的本地仓库有 mastermybranch 两个分支,远程仓库也有同名的分支,则Git会将两个分支都推送。

如果您只想推送一个分支,可以明确告诉 Git 您要推送哪个分支:git push origin mybranch

如果您想推送 master 分支,则需要先从 master 分支拉取最新更新。Git 报错说合并不是快进式的,是因为自上次从 master 拉取以来,其他人已经向主分支推送了一个提交。


1
那如果我想要推送它们两个,但不是同时推送呢?有时候我只想推送我的分支,有时候我会将我的分支合并到主分支中,并希望推送主分支。这种情况应该怎么办呢? - Coocoo4Cocoa
你可以始终使用形式为“git push <repository> <branch>”的方式显式地命名要推送的分支。请参阅http://www.kernel.org/pub/software/scm/git/docs/git-push.html。 - Esko Luontola
较新版本的git允许您指定此行为。 - Dustin
3
不是这样的。Git会推送两个分支,因为“push matching”(将本地和远程都存在的分支推送到)是默认行为。 - Jakub Narębski
这让我感到有些奇怪,但我想这可以解释我所看到的行为(在一个分支上进行更改,提交它,git push,同时Git会拒绝推送并在另外两个分支上出现“[rejected]”和“failed to push some refs”的提示)。 - Ben Klein
“git config --global push.default current” 可能是原问题提出者想要的,也是我所使用的。 - Flash Sheridan

3
如果您只想推送当前分支,可以使用 "git push origin HEAD",或者甚至是 "git push HEAD"(使用现代 git)。
如果没有为 push 定义 refspec(您已在配置中为 fetch 定义了 refspec,但未为 push 定义),则默认行为是推送 matching 引用。来自 git-push(1)

git push [...] [<repository> <refspec>...]

<refspec>...

特殊的 refspec :(或 +: 以允许非快进更新) 指示 git 推送 "matching" 分支:对于本地存在的每个分支,如果远程端已经存在同名分支,则更新远程端。如果找不到显式的 refspec(即既不在命令行上也不在...),则这是默认操作模式


1
当我使用新的git(比如1.6.3.1)运行“git push”时,会收到一个巨大的警告,提示我应该设置push.default或存储库应配置推送refspecs。但我却不能想出如何做第二件事情。Google没有提供帮助。(我想配置存储库,因为潜在的对我的存储库进行推送的人将会被这个大而明显的警告所困扰和烦恼,我不希望他们在“git clone ...”之后还需要配置任何东西。) - asjo
2
你需要配置(设置)远程.<remotename>.push,其中<remotename>在你的情况下可能是“origin”,并且用于镜像同步推送到裸仓库的<refspec>应为“+refs/heads/*:refs/heads/*”(标签也一样)。 - Jakub Narębski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接