繁体   English   中英

找出您在 Git 中克隆的原始存储库的名称

[英]Finding out the name of the original repository you cloned from in Git

当您使用语法进行第一次克隆时

git clone username@server:gitRepo.git

是否可以使用您的本地存储库来查找该初始克隆的名称?

(所以在上面的例子中,找到gitRepo.git 。)

git config --get remote.origin.url

在存储库根目录中, .git/config文件包含有关远程存储库和分支的所有信息。 在您的示例中,您应该查找以下内容:

[remote "origin"]
    fetch = +refs/heads/*:refs/remotes/origin/*
    url = server:gitRepo.git

此外,Git 命令git remote -v显示远程存储库名称和 URL。 “原始”远程存储库通常对应于原始存储库,从该存储库克隆了本地副本。

这是您可能正在搜索的快速 Bash 命令,它只会打印远程存储库的基本名称:

哪里获取:

basename $(git remote show -n origin | grep Fetch | cut -d: -f2-)

或者你推

basename $(git remote show -n origin | grep Push | cut -d: -f2-)

特别是-n选项使命令更快。

我用这个:

basename $(git remote get-url origin) .git

它返回类似gitRepo东西。 (删除命令末尾的.git以返回类似gitRepo.git 。)

(注:需要 Git 2.7.0 或更新版本)

我偶然发现了这个问题,试图从 github 或 gitlab 等 git 主机获取organization/repo字符串。

这对我有用:

git config --get remote.origin.url | sed -e 's/^git@.*:\([[:graph:]]*\).git/\1/'

它使用sedgit config命令的输出替换为组织和存储库名称。

github/scientist这样的东西会被正则表达式中的字符类[[:graph:]]匹配。

\\1告诉 sed 只用匹配的字符替换所有内容。

git remote show origin -n | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'

它使用三种不同的 URL 样式进行了测试:

echo "Fetch URL: http://user@pass:gitservice.org:20080/owner/repo.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
echo "Fetch URL: Fetch URL: git@github.com:home1-oss/oss-build.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
echo "Fetch URL: https://github.com/owner/repo.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'

git repo 名称的 Powershell 版本命令:

(git config --get remote.origin.url) -replace '.*/' -replace '.git'
git ls-remote --get-url | xargs basename         # gitRepo.git
git ls-remote --get-url | xargs basename -s .git # gitRepo

# zsh
git ls-remote --get-url | read
print $REPLY:t   # gitRepo.git
print $REPLY:t:r # gitRepo

为清楚起见编辑:

如果remote.origin.url的格式为protocol://auth_info@git_host:port/project/repo.git ,这将用于获取值。 如果您发现它不起作用,请调整作为第一个 cut 命令一部分的-f5选项。

用于协议的示例remote.origin.url:// auth_info @ git_host:端口/项目/ repo.git切口命令创建将包含以下输出:

-f1: 协议: -f2: (空白) -f3: auth_info@git_host:port -f4: 项目 -f5: repo.git

如果遇到问题,请查看git config --get remote.origin.url命令的输出以查看哪个字段包含原始存储库。 如果remote.origin.url不包含.git字符串,则省略第二个cut命令的管道。

#!/usr/bin/env bash
repoSlug="$(git config --get remote.origin.url | cut -d/ -f5 | cut -d. -f1)"
echo ${repoSlug}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM