是否有一种使用GitPython获取存储库名称的方法?
repo = git.Repo.clone_from(repoUrl, ".", branch=branch)
我似乎找不到附加在 repo 对象上的任何属性,其中包含此信息。可能是我没有理解 github/GitPython 的工作方式。
是否有一种使用GitPython获取存储库名称的方法?
repo = git.Repo.clone_from(repoUrl, ".", branch=branch)
我似乎找不到附加在 repo 对象上的任何属性,其中包含此信息。可能是我没有理解 github/GitPython 的工作方式。
简单、紧凑、健壮,可与远程的 .git
仓库一起使用:
from git import Repo
repo = Repo(repo_path)
# For remote repositories
repo_name = repo.remotes.origin.url.split('.git')[0].split('/')[-1]
# For local repositories
repo_name = repo.working_tree_dir.split("/")[-1]
我可以建议:
remote_url = repo.remotes[0].config_reader.get("url") # e.g. 'https://github.com/abc123/MyRepo.git'
os.path.splitext(os.path.basename(remote_url))[0] # 'MyRepo'
我认为目前没有可行的方法。但是,我编写了一个函数(你可以在这里看到它的实际运用),该函数通过URL获取存储库名称:
def get_repo_name_from_url(url: str) -> str:
last_slash_index = url.rfind("/")
last_suffix_index = url.rfind(".git")
if last_suffix_index < 0:
last_suffix_index = len(url)
if last_slash_index < 0 or last_suffix_index <= last_slash_index:
raise Exception("Badly formatted url {}".format(url))
return url[last_slash_index + 1:last_suffix_index]
get_repo_name_from_url("https://github.com/ishepard/pydriller.git") # returns pydriller
get_repo_name_from_url("https://github.com/ishepard/pydriller") # returns pydriller
get_repo_name_from_url("https://github.com/ishepard/pydriller.git/asd") # Exception
repoName = repoUrl.rsplit("/")[1].split(".")[0]
,但是你的方法更加健壮,我猜。 - erihanseRepo
对象的working_dir
属性是git仓库的绝对路径。要解析仓库名称,可以使用os.path.basename
函数。>>> import git
>>> import os
>>>
>>> repo = git.Repo.clone_from(repoUrl, ".", branch=branch)
>>> repo.working_dir
'/home/user/repo_name'
>>> os.path.basename(repo.working_dir)
'repo_name'
\
。 - Japu_D_Cretworking_tree_dir
为None
。 - wonder.mice