【问题标题】:By given name of a Git remote-tracking branch how to find which local branch tracks it?通过 Git 远程跟踪分支的给定名称如何找到哪个本地分支跟踪它?
【发布时间】:2021-03-21 01:10:14
【问题描述】:

通过 Git 远程跟踪分支的给定名称,例如,upstream/develop 如果有的话,如何找到跟踪它的本地分支?

如果可能的话,我正在寻找一种不依赖于 shell 脚本并且也适用于 Windows 的解决方案。

【问题讨论】:

    标签: git version-control git-branch


    【解决方案1】:

    基于this answer(分支枚举)和this answer(检索上游分支),您可以遍历本地分支并检查其中是否有任何一个具有所需的跟踪远程分支:

    git for-each-ref --shell \
      --format='test %(upstream:short) = "upstream/develop" && echo %(refname:short)' \
      refs/heads/ | sh
    

    【讨论】:

    • 为什么是--shell| sh
    • @RomainValeri 来自 [手册页}(git-scm.com/docs/git-for-each-ref#Documentation/…),--shell 仅在 shell 中正确引用 (%(whatever)) 以进行直接评估,但不会单独调用 shell。 --perl--python--tcl 也是如此。
    • 感谢您的反馈,我现在更清楚了^^ 以前从未使用过该选项
    【解决方案2】:

    另一种方法是使用conditional formatfor-each-ref

    git for-each-ref --format="%(if:equals=upstream/develop)%(upstream:short)%(then)%(refname:short)%(end)" refs/heads | sort -u
    

    可以更方便地放入别名中

    git config --global alias.who-tracks '!f() { git for-each-ref --format="%(if:equals=upstream/$1)%(upstream:short)%(then)%(refname:short)%(end)" refs/heads | sort -u; }; f'
    
    # then when you need it :
    git who-tracks develop
    git who-tracks another/branch
    

    在这个别名中,我假设了一个唯一的遥控器,但当然,如果您希望能够在不同的遥控器上使用它,请稍微调整一下以在参数中包含遥控器名称:

    git config --global alias.who-tracks '!f() { git for-each-ref --format="%(if:equals=$1)%(upstream:short)%(then)%(refname:short)%(end)" refs/heads | sort -u; }; f'
    
    # then when you need it :
    git who-tracks upstream/develop
    git who-tracks origin/another/branch
    

    【讨论】:

    • 我不认为你真的需要 sort -u 在这里,放弃它可能会在 Windows 上有所帮助(不是我使用 Windows,所以我不确定:-)) .
    • @torek 没错,但是当我尝试不使用它时,空白行有点不美观和麻烦。我想这是一个选项^^
    【解决方案3】:

    另一个替代方法是使用grep过滤简单git branchvery verbose输出

    git branch -vv | grep upstream/develop
    

    【讨论】:

      猜你喜欢
      • 2010-09-15
      • 2013-04-30
      • 2012-09-18
      • 2014-08-22
      • 2010-09-27
      • 2019-02-16
      • 2014-06-09
      • 2014-11-04
      • 1970-01-01
      相关资源
      最近更新 更多