获取默认远程推送和默认远程分支

4

我想要从脚本中获取默认的推送远程分支和默认的推送分支。

关于回忆,git将按以下顺序选择设置之间的远程主机:

  • branch.<name>.pushRemote
  • remote.pushDefault
  • branch.<name>.remote
  • 最后默认
    • 如果 config push.default current ,则为 origin
    • 如果 config push.default upstream ,则为 NULL

我找不到关于git如何选择这个最后的默认origin的任何参考资料,但它似乎是静态的。

默认的远程分支可能是:

  • branch.<name>.merge 如果 config push.default upstream
  • 否则是当前分支名称

现在,我想要一种安全的方法来获取默认的推送远程分支和默认的推送分支。

  1. 我可以使用 git config --get,但我必须根据 config push.default 解决行为问题,这似乎有点冒险。
  2. 我更喜欢使用这些命令之一:
    • git for-each-ref --format='%(push:short)' refs/heads/mybranch
    • git rev-parse --abbrev-ref=loose mybranch@{push}

最后,我有两个问题:

  1. git for-eachgit rev-parse 返回类似于 origin/mybranch 的路径。 我该如何在远程名称和分支名称之间进行拆分(远程名称可能包含斜杠)。
  2. 这两个命令中是否有更安全的函数? (在所有测试中,它们都返回相同的输出)。
1个回答

1

在 Git 2.16(2018 年第一季度)中,有一种新的语法,其中 "git for-each-ref" 的 "--format=..." 选项学会了通过 "%(push:remotename)" 和类似的方式来显示'upstream' 和 'push' 受影响的远程端仓库和远程端引用的名称。

请查看 提交 1b58686(2017年11月7日)和 提交 cc72385(2017年10月5日),作者为 Johannes Schindelin (dscho)
请查看 提交 9700fae(2017年11月7日),作者为 J Wyman (whoisj)
(由 Junio C Hamano -- gitster -- 合并于 提交 093048b,2017年11月15日)

for-each-ref: 让 upstream/push 可以选择性地报告远程名称

有时,例如脚本想要知道的不仅是远程存储库上游分支的名称,还需要知道远程的名称。

此补丁为 upstream 和 push 原子提供了新的后缀 :remotename,允许精确显示。例如:

$ cat .git/config
...
[remote "origin"]
    url = https://where.do.we.come/from
    fetch = refs/heads/*:refs/remote/origin/*
[remote "hello-world"]
    url = https://hello.world/git
    fetch = refs/heads/*:refs/remote/origin/*
    pushURL = hello.world:git
    push = refs/heads/*:refs/heads/*
[branch "master"]
    remote = origin
    pushRemote = hello-world
...

$ git for-each-ref \
  --format='%(upstream) %(upstream:remotename) %(push:remotename)' \
  refs/heads/master
refs/remotes/origin/master origin hello-world

实现选择不要过度智能化推送远程,如果没有明确配置推送远程;原因是可以通过使用来进行过度智能化。
%(if)%(push:remotename)%(then)
    %(push:remotename)
%(else)
    %(upstream:remotename)
%(end)

虽然如果调用者只对显式推送远程感兴趣,那么“取消DWIM”信息将是不可能的。 尽管:remote更短,但它也更加模糊,而且它还会关闭例如:remoteref的可能性(这显然会引用远程存储库中相应的引用)。

for-each-ref: 让 upstream/push 报告远程引用名称

有时脚本想要知道不仅是远程推送分支的名称,还有远程仓库中已知的分支名称

例如,当工具希望从与其自动拉取的相同分支推送到同一分支时,即git push <remote> <from>:<to>中的<remote><to>将分别由%(upstream:remotename)%(upstream:remoteref)提供。

此补丁为upstreampush原子提供了新后缀:remoteref,允许准确显示。例如:

$ cat .git/config
...
[remote "origin"]
    url = https://where.do.we.come/from
    fetch = refs/heads/*:refs/remote/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
[branch "develop/with/topics"]
    remote = origin
    merge = refs/heads/develop/with/topics
...

$ git for-each-ref \
    --format='%(push) %(push:remoteref)' \
    refs/heads
refs/remotes/origin/master refs/heads/master
refs/remotes/origin/develop/with/topics refs/heads/develop/with/topics

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