'Retrieve Github repository name using GitPython

Is there a way to get the repository name using GitPython?

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

I can't seem to find any properties attached to the repo object which has this information. It might be that I misunderstand how github/GitPython works.



Solution 1:[1]

Simple, compact, and robust that works with remote .git repos:

 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]

Solution 2:[2]

May I suggest:

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'

Solution 3:[3]

I don't think there is a way to do it. However, I built this function to retrieve the repository name given an URL (you can see it in action here):

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]

Then, you do:

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

Solution 4:[4]

The working_dir property of the Repo object is the absolute path to the git repo. To parse the repo name, you can use the os.path.basename function.

>>> 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'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rrlamichhane
Solution 2 boarik
Solution 3 Davide Spadini
Solution 4 Jonathan Haubrich