|
1 | 1 | import re
|
| 2 | +import shlex |
2 | 3 | import subprocess
|
3 | 4 | import typing
|
4 | 5 |
|
5 | 6 |
|
6 |
| -def get_owner_and_repo_from_cwd() -> typing.Tuple[str, str]: |
7 |
| - """Return the owner and name of the remote named origin in the cwd.""" |
8 |
| - origin_url = ( |
9 |
| - subprocess.check_output(["git", "remote", "get-url", "origin"]).decode().strip() |
10 |
| - ) |
11 |
| - return _extract_o_and_r(origin_url) |
| 7 | +from labels.github import Repository |
| 8 | + |
| 9 | + |
| 10 | +REMOTE_REGEX = re.compile( |
| 11 | + r"^(https|git)(:\/\/|@)github\.com[\/:](?P<owner>[^\/:]+)\/(?P<name>.+).git$" |
| 12 | +) |
12 | 13 |
|
13 | 14 |
|
14 |
| -def _extract_o_and_r(url: str) -> typing.Tuple[str, str]: |
15 |
| - """Return the owner and repo name of a remote given its SSH or HTTPS url. |
| 15 | +def load_repository_info(remote_name: str = "origin") -> typing.Optional[Repository]: |
| 16 | + """Load repository information from the local working tree. |
16 | 17 |
|
17 |
| - HTTPS url format -> 'https://github.com/user/repo.git' |
18 |
| - SSH url format -> '[email protected]:user/repo.git' |
| 18 | + HTTPS url format -> 'https://github.com/owner/name.git' |
| 19 | + SSH url format -> '[email protected]:owner/name.git' |
19 | 20 | """
|
20 |
| - parts = re.split(r"[@/:.]+", url) |
21 |
| - return (parts[-3], parts[-2]) |
| 21 | + |
| 22 | + proc = subprocess.run( |
| 23 | + shlex.split(f"git remote get-url {remote_name}"), |
| 24 | + stdout=subprocess.PIPE, |
| 25 | + encoding="utf-8", |
| 26 | + ) |
| 27 | + |
| 28 | + if proc.returncode != 0: |
| 29 | + return None |
| 30 | + |
| 31 | + match = REMOTE_REGEX.match(proc.stdout.strip()) |
| 32 | + |
| 33 | + if match is None: |
| 34 | + return None |
| 35 | + |
| 36 | + return Repository(owner=match.group("owner"), name=match.group("name")) |
0 commit comments