使用GitPython检索Github存储库名称

14

是否有一种使用GitPython获取存储库名称的方法?

repo = git.Repo.clone_from(repoUrl, ".", branch=branch)

我似乎找不到附加在 repo 对象上的任何属性,其中包含此信息。可能是我没有理解 github/GitPython 的工作方式。

4个回答

19

简单、紧凑、健壮,可与远程的 .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]

2
注意:删除末尾的\ - Japu_D_Cret
裸仓库的 working_tree_dirNone - wonder.mice

6

我可以建议:

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'

repo.remotes.origin.url.split('.git')[0].split('/')[-1] - nimig18

4

我认为目前没有可行的方法。但是,我编写了一个函数(你可以在这里看到它的实际运用),该函数通过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

1
我做了类似的事情:repoName = repoUrl.rsplit("/")[1].split(".")[0],但是你的方法更加健壮,我猜。 - erihanse

0
Repo对象的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'

5
这将为您提供文件夹的名称。当您克隆存储库时,默认情况下文件夹的名称与存储库相同,但用户可以更改它。 - Cyberwiz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接