[英]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/'
它使用sed
将git 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.