git 推送时保留远程目标

Preserve remote target when git pushing

我设置了两个遥控器 git,效果非常好,即 originproduction。为避免不小心将内容推送到生产环境,如果我只输入 git push,我只想推送到 origin。但是,当我执行 git push production 时,后续推送将推送到生产环境。我想这与 git 文档中的以下摘录有关。

When the command line does not specify where to push with the argument, branch.*.remote configuration for the current branch is consulted to determine where to push. If the configuration is missing, it defaults to origin.

我该如何解决这个问题?理想情况下,当我执行 git push 时,我希望收到一条错误消息,以便我始终必须为此回购指定遥控器, 以便它永远不会切换到 production.

最接近的可能是将 push.default 配置为 nothing(参见 git-config reference for push.default):

nothing - do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.

如果没有给出refspec,它会打印一个错误,即没有指定要推送的分支。这意味着推送需要始终包含远程和分支,确保需要明确指定远程。

配置命令为:

git config push.default nothing

以及显示错误生成的示例:

$ git push
fatal: You didn't specify any refspecs to push, and push.default is "nothing".
$ git push origin
fatal: You didn't specify any refspecs to push, and push.default is "nothing".
$ git push origin master
Counting objects: 2, done.
...

请注意,您也可以使用 HEAD 而不是明确的分支名称来表示当前签出的分支。

因为这提供了一些防止意外推送的安全性,我通常将 push.default 全局配置为 nothing(即对于所有回购协议,除非明确覆盖):

git config --global push.default nothing

这可以通过

来完成
git config remote.pushDefault origin

现在,如果您省略远程并仅发出 git push,它将推送到源并且 不会 进行部署。推送到另一个遥控器,例如部署,只发布git push deploy。有关详细信息,请参阅 git documentation.