【发布时间】:2021-03-21 01:10:14
【问题描述】:
通过 Git 远程跟踪分支的给定名称,例如,upstream/develop 如果有的话,如何找到跟踪它的本地分支?
如果可能的话,我正在寻找一种不依赖于 shell 脚本并且也适用于 Windows 的解决方案。
【问题讨论】:
标签: git version-control git-branch
通过 Git 远程跟踪分支的给定名称,例如,upstream/develop 如果有的话,如何找到跟踪它的本地分支?
如果可能的话,我正在寻找一种不依赖于 shell 脚本并且也适用于 Windows 的解决方案。
【问题讨论】:
标签: git version-control git-branch
基于this answer(分支枚举)和this answer(检索上游分支),您可以遍历本地分支并检查其中是否有任何一个具有所需的跟踪远程分支:
git for-each-ref --shell \
--format='test %(upstream:short) = "upstream/develop" && echo %(refname:short)' \
refs/heads/ | sh
【讨论】:
--shell 和| sh?
--shell 仅在 shell 中正确引用 (%(whatever)) 以进行直接评估,但不会单独调用 shell。 --perl、--python 和 --tcl 也是如此。
另一种方法是使用conditional format 和for-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,所以我不确定:-)) .
另一个替代方法是使用grep过滤简单git branch的very verbose输出
git branch -vv | grep upstream/develop
【讨论】: