使用 GitPython 检索 Github 存储库名称

eri*_*nse 6 gitpython python-3.6

有没有办法使用 GitPython 获取存储库名称?

repo = git.Repo.clone_from(repoUrl, ".", branch=branch)
Run Code Online (Sandbox Code Playgroud)

我似乎找不到附加到具有此信息的 repo 对象的任何属性。可能是我误解了 github/GitPython 的工作原理。

小智 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'
Run Code Online (Sandbox Code Playgroud)


nim*_*g18 6

简单、紧凑且坚固:

 from git import Repo

 repo = Repo(repo_path)
 repo_name = repo.remotes.origin.url.split('.git')[0].split('/')[-1]`
Run Code Online (Sandbox Code Playgroud)

  • 注意:去掉最后的“\” (2认同)

小智 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]
Run Code Online (Sandbox Code Playgroud)

然后,你这样做:

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
Run Code Online (Sandbox Code Playgroud)