diff --git a/Documents/bin/rcfiles/git.py b/Documents/bin/rcfiles/git.py index ff92a94c84c7430e53cbaa83214b371976771f64..ed4110b6404861bf031dd4925f2e4c6fdc29ff00 100644 --- a/Documents/bin/rcfiles/git.py +++ b/Documents/bin/rcfiles/git.py @@ -1,7 +1,10 @@ """Git repository related functions.""" +import configparser import os.path import pathlib +from sh.contrib import git # pylint: disable=import-error +from . import gitlab def is_repo(path): @@ -18,3 +21,71 @@ def in_repo(): it's enough to just check if the .git directory exists where we are. """ return is_repo(".") + + +def get_remotes(): + """Return a dictionary of remotes and their URL. + Also, deduce the remote type ("gitlab", "github" or None if couldn't figure + it out) and get the namespace and repository name. + + If not in a Git repository, return None. + """ + if not in_repo: + return None + + gitlab_http_url = gitlab.get_url() + gitlab_ssh_url = ( + f'git@{gitlab_http_url.removeprefix("https://").removesuffix("/")}:' + ) + github_http_url = "https://github.com/" + github_ssh_url = "git@github.com:" + + config = configparser.ConfigParser() + config.read(".git/config") + + remotes = { + x.removeprefix('remote "').removesuffix('"'): { + "url": config[x]["url"], + "name": x.removeprefix('remote "').removesuffix('"'), + } + for x in config.sections() + if x.startswith("remote ") + } + + for name, remote in remotes.items(): + if remote["url"].startswith(gitlab_http_url) or remote[ + "url" + ].startswith(gitlab_ssh_url): + remotes[name]["type"] = "gitlab" + parts = ( + remote["url"] + .removeprefix(gitlab_http_url) + .removeprefix(gitlab_ssh_url) + .removesuffix(".git") + .split("/") + ) + if len(parts) == 2: + remotes[name]["namespace"] = parts[0] + remotes[name]["name"] = parts[1] + elif remote["url"].startswith(github_http_url) or remote[ + "url" + ].startswith(github_ssh_url): + remotes[name]["type"] = "github" + parts = ( + remote["url"] + .removeprefix(github_http_url) + .removeprefix(github_ssh_url) + .removesuffix(".git") + .split("/") + ) + if len(parts) == 2: + remotes[name]["name"] = parts[1] + else: + remotes[remote]["type"] = None + + return remotes + + +def add_remote(name, url): + """Add a remote to the Git repository.""" + git.remote("add", name, url) diff --git a/Documents/bin/rcfiles/gitlab.py b/Documents/bin/rcfiles/gitlab.py index f7ba6d9ad59be49704665c863e423c5c8938dcb8..3ea4ada54c21343001bcbac84a2dc4d45f996965 100644 --- a/Documents/bin/rcfiles/gitlab.py +++ b/Documents/bin/rcfiles/gitlab.py @@ -77,3 +77,9 @@ def create_project(conn, name, group=None, description=None, visibility=None): if visibility is not None: data["visibility"] = visibility return conn.projects.create(data) + + +def read_only_project(conn, group, name): + """Make a GitLab project read-only.""" + project = get_project(conn, group, name) + project.archive()