已知Git远程跟踪分支,如何查找对应远程仓库及分支
问题描述
我配置了一个带有特殊fetchspec的远程仓库:
[remote "devall"] url = https://BNahum90789@dcilpa670/scm/devops/dev4all.git fetch = +refs/heads/dev/BNahum90789_2/*:refs/remotes/dev_BNahum90789/*
执行推送命令:
git push -u devall my:dev/BNahum90789_2/my_on_remote
得到远程跟踪分支:
git rev-parse --symbolic-full-name dev_BNahum90789/my_on_remote refs/remotes/dev_BNahum90789/my_on_remote
已知该远程跟踪分支refs/remotes/dev_BNahum90789/my_on_remote,如何查找对应的远程仓库名称及远程分支?(注意该分支未包含远程名称及本地跟踪分支)我目前想到的方法是遍历所有远程仓库的fetch-spec进行匹配,是否有更优方案?
解决方案
好问题!这种自定义fetch spec导致远程跟踪分支前缀和远程名称不一致的情况确实容易让人困惑,除了你想到的遍历fetch spec的方法,还有几个更高效的方案:
1. 用git rev-parse直接获取关联的远程仓库
Git其实会记录每个远程跟踪分支对应的远程仓库,哪怕前缀被自定义过,你可以用这条命令直接获取:
git rev-parse --symbolic-full-name dev_BNahum90789/my_on_remote@{remote}
在你的场景里,这条命令会直接返回devall,也就是该跟踪分支对应的远程仓库名称。
2. 用git for-each-ref一次性获取完整关联关系
这个命令可以帮你批量查看所有远程跟踪分支的详细关联信息,包括对应的远程仓库和上游远程分支:
git for-each-ref --format='%(refname) | 远程仓库: %(remote) | 对应远程分支: %(upstream:short)' refs/remotes/
如果只想查看目标分支的信息,直接在命令末尾加上分支路径即可:
git for-each-ref --format='%(refname) | 远程仓库: %(remote) | 对应远程分支: %(upstream:short)' refs/remotes/dev_BNahum90789/my_on_remote
执行后你会得到类似这样的结果:
refs/remotes/dev_BNahum90789/my_on_remote | 远程仓库: devall | 对应远程分支: dev/BNahum90789_2/my_on_remote
直接就能拿到你需要的所有信息。
3. 遍历fetch spec的兜底方案
如果上面的命令因为Git版本过低或者特殊场景失效,你提到的遍历fetch spec是非常可靠的兜底方法:
- 先列出所有远程仓库的fetch规则:
git config --get-regexp remote\..*\.fetch - 找到匹配目标跟踪分支的规则:你的分支是
refs/remotes/dev_BNahum90789/my_on_remote,对应规则里的右侧是+refs/heads/dev/BNahum90789_2/*:refs/remotes/dev_BNahum90789/*。把右侧的*替换成my_on_remote,就能得到对应的远程分支refs/heads/dev/BNahum90789_2/my_on_remote;而规则前缀remote.devall.fetch则说明对应的远程仓库是devall。
内容的提问来源于stack exchange,提问作者Boaz Nahum




