Retrieve Github repository name using GitPython
Asked Answered
K

4

16

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.

Keverne answered 13/3, 2019 at 0:6 Comment(0)
L
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]
Lydgate answered 11/8, 2020 at 6:19 Comment(1)
working_tree_dir is None for bare repositories.Prandial
S
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'
Shorthand answered 29/3, 2020 at 5:37 Comment(1)
repo.remotes.origin.url.split('.git')[0].split('/')[-1]Lydgate
I
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
Interpleader answered 13/3, 2019 at 8:59 Comment(1)
I did something similar: repoName = repoUrl.rsplit("/")[1].split(".")[0] but your way is more robust I guess.Keverne
S
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'
Subsidy answered 29/7, 2019 at 3:25 Comment(1)
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.Wesle

© 2022 - 2024 — McMap. All rights reserved.