17

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.

4 Answers 4

20

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]
Sign up to request clarification or add additional context in comments.

2 Comments

working_tree_dir is None for bare repositories.
This is good, but won't work on windows path. I suggest instead: repo_name = Path(str(repo.remotes.origin.url)).stem
6

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'

1 Comment

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

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

1 Comment

I did something similar: repoName = repoUrl.rsplit("/")[1].split(".")[0] but your way is more robust I guess.
0

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'

1 Comment

This gives you the name of the folder. While the default when you clone a repo is to name the folder the same as the repo, it can be changed by the user.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.