通过Git解析URL

shstlldc  于 2024-01-04  发布在  Git
关注(0)|答案(2)|浏览(125)

关于git的配置,

[url "[email protected]:"]
    insteadOf = https://gitlab.com/
[url "https://bitbucket.com/other/"]
    insteadOf = https://github.com/some/

字符串
Git可以更改远程仓库的源代码以及获取特定URL的方式。
因此,有了一些特定的repo url,人们如何解析目标url,git最终会用来克隆repo(而不是实际克隆它)。
使得

https://github.com/some/repo.git => https://bitbucket.com/other/repo.git
https://gitlab.com/any/repo.git => [email protected]:any/repo.git
https://bitbucket.com/no/change.git => https://bitbucket.com/no/change.git


理论上,这可以通过git config --get-regexp ...命令上的grep/sed/awk等管道系列来完成
然而,如何通过git本身来实现相同的功能,而不添加额外的自定义逻辑,并且完全按照git的方式来实现,例如

git resolve-remote https://github.com/some/repo.git


或者可能使用一些变通方法,但实际上并不涉及git clone命令。

qyzbxkaa

qyzbxkaa1#

我没有找到一个简单的命令来解析配置了url..insteadOf的远程URL。但是我找到了一个使用暂时空仓库的方法。创建一个新仓库,配置URL重写(全局或本地;对于下面的示例,我使用本地),添加一个远程,向Git请求重写的URL,删除仓库。示例:

$ cd /tmp
$ git init _repo.tmp
$ git -C _repo.tmp config [email protected]:.insteadOf https://gitlab.com/
$ git -C _repo.tmp config url.https://bitbucket.com/other/.insteadOf https://github.com/some/
$ git -C _repo.tmp remote add remote1 https://github.com/some/repo.git
$ git -C _repo.tmp remote add remote2 https://gitlab.com/any/repo.git
$ git -C _repo.tmp remote add remote3 https://bitbucket.com/no/change.git

字符串
让我们验证一下:

$ git -C _repo.tmp config --local --get-regexp "^remote\..*\.url"
remote.remote1.url https://github.com/some/repo.git
remote.remote2.url https://gitlab.com/any/repo.git
remote.remote3.url https://bitbucket.com/no/change.git


配置中的URL没有被重写。现在魔术:git remote get-url打印重写的URL:

$ git -C _repo.tmp remote get-url remote1 
https://bitbucket.com/other/repo.git

$ git -C _repo.tmp remote get-url remote2 
[email protected]:any/repo.git

$ git -C _repo.tmp remote get-url remote3 
https://bitbucket.com/no/change.git


清理:

$ rm -rf _repo.tmp
$ cd # HOME


我可以创建一个shell脚本,但它的缺点是-它将创建/删除每个URL一个仓库。如果你要检查许多URL,这可能会很慢。对于许多URL,创建一个仓库,添加远程,重写URL,然后删除仓库。

sr4lhrrt

sr4lhrrt2#

这是辉煌的@博士。这正是我所期望的方式找到!而且它真的有效!
即使你提到的缺点,我可以看到可以黑客攻击
由于我们并不真正关心仓库数据是否一致,我们可以手动组合其配置,而无需调用git本身。
使得
1.先决条件

git --global config [email protected]:.insteadOf https://gitlab.com/
git --global config url.https://bitbucket.com/other/.insteadOf https://github.com/some/

字符串
1.在批量输入urls配置中编写

git init ~/tmp/remotes
get-source-urls-list \
   | awk '{ printf "[remote \"r%s\"]\n  url = %s\n", NR, $1}' \
   >> ~/tmp/remotes/.git/config


这将在视图中将批量远程添加到配置中(无论其数量如何),

[remote "r1"]
    url = https://github.com/some/repo.git
[remote "r2"]
    url = https://gitlab.com/any/repo.git
[remote "r3"]
    url = https://bitbucket.com/no/change.git


1.然后按如下方式查询所有Map的URL

git -C ~/tmp/remotes remote  -v \
  | awk '/\(fetch\)/ {print $2}'  # print only fetch url to rid of duplicates


这导致

https://bitbucket.com/other/repo.git
[email protected]:any/repo.git
https://bitbucket.com/no/change.git


谢谢你!

相关问题