Coverage for src/governed_harness/forges/detect.py: 88%
96 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
1"""Which forge a repository lives on, from its ``origin`` remote (#56).
3The detection is a pure function of the remote URL, so it is reproducible and needs no
4network: the host names the forge (``github.com``, ``gitlab.com``, ``bitbucket.org``,
5``dev.azure.com`` and ``*.visualstudio.com``) or, for a self-hosted forge, contains its name
6(``gitlab.example.com``, ``gitea.example.com``, ``forgejo...``, ``codeberg.org``). Anything
7else is unknown and needs ``delivery.forge.kind``."""
9from __future__ import annotations
11import re
12from dataclasses import dataclass
13from urllib.parse import urlsplit
15KNOWN_FORGES: tuple[str, ...] = ("github", "gitlab", "bitbucket", "azure-devops", "gitea")
18@dataclass(frozen=True)
19class ForgeLocation:
20 """A repository on a forge: its kind, host, path and the default API base URL."""
22 kind: str
23 host: str
24 repository: str
25 """``owner/name``, a GitLab project path, ``workspace/repo`` or
26 ``organization/project/repository`` (Azure DevOps)."""
27 api_url: str
29 def as_dict(self) -> dict[str, str]:
30 return {
31 "kind": self.kind,
32 "host": self.host,
33 "repository": self.repository,
34 "apiUrl": self.api_url,
35 }
38_SCP = re.compile(r"^(?:[\w.-]+@)?(?P<host>[\w.-]+):(?P<path>[^/].*)$")
41def _host_and_path(url: str) -> tuple[str, str] | None:
42 url = url.strip()
43 if "://" in url:
44 parts = urlsplit(url)
45 if not parts.hostname: 45 ↛ 46line 45 didn't jump to line 46 because the condition on line 45 was never true
46 return None
47 return parts.hostname.lower(), parts.path.strip("/")
48 match = _SCP.match(url)
49 if match:
50 return match.group("host").lower(), match.group("path").strip("/")
51 return None
54_AZURE_SSH_HOST = "ssh.dev.azure.com"
55_VISUALSTUDIO = ".visualstudio.com"
56"""The suffix of the hosts of the former Azure DevOps service (``org.visualstudio.com``)."""
59def kind_of_host(host: str) -> str | None:
60 """The forge a host name points to, or ``None``."""
61 if host == "github.com" or host.endswith(".github.com") or host.startswith("github."):
62 return "github"
63 if host == "bitbucket.org" or host.endswith(".bitbucket.org"):
64 return "bitbucket"
65 if (
66 host in {"dev.azure.com", _AZURE_SSH_HOST}
67 or host.endswith(_VISUALSTUDIO)
68 or host.endswith(".dev.azure.com")
69 ):
70 return "azure-devops"
71 if "gitlab" in host:
72 return "gitlab"
73 if "gitea" in host or "forgejo" in host or host == "codeberg.org":
74 return "gitea"
75 return None
78def default_api_url(kind: str, host: str, repository: str = "") -> str:
79 """The REST base URL of a forge on a host."""
80 if kind == "github":
81 return "https://api.github.com" if host == "github.com" else f"https://{host}/api/v3"
82 if kind == "gitlab":
83 return f"https://{host}/api/v4"
84 if kind == "bitbucket":
85 return "https://api.bitbucket.org/2.0"
86 if kind == "azure-devops":
87 organization = repository.split("/", 1)[0] if repository else ""
88 if host.endswith(_VISUALSTUDIO):
89 return f"https://{host}"
90 return f"https://dev.azure.com/{organization}" if organization else "https://dev.azure.com"
91 return f"https://{host}/api/v1"
94def _azure_repository(host: str, path: str) -> str | None:
95 """``organization/project/repository`` from the forms of an Azure DevOps remote."""
96 segments = [item for item in path.split("/") if item]
97 if host == _AZURE_SSH_HOST and len(segments) >= 4 and segments[0] == "v3":
98 return "/".join(segments[1:4])
99 if "_git" in segments: 99 ↛ 113line 99 didn't jump to line 113 because the condition on line 99 was always true
100 index = segments.index("_git")
101 if index + 1 >= len(segments): 101 ↛ 102line 101 didn't jump to line 102 because the condition on line 101 was never true
102 return None
103 repository = segments[index + 1]
104 before = segments[:index]
105 if host.endswith(_VISUALSTUDIO):
106 organization = host.split(".", 1)[0]
107 project = before[-1] if before else repository
108 return f"{organization}/{project}/{repository}"
109 if len(before) >= 2: 109 ↛ 111line 109 didn't jump to line 111 because the condition on line 109 was always true
110 return f"{before[0]}/{before[1]}/{repository}"
111 if len(before) == 1:
112 return f"{before[0]}/{repository}/{repository}"
113 return None
116def parse_remote(url: str, kind: str | None = None) -> ForgeLocation | None:
117 """The forge location of a remote URL (HTTPS, SSH or scp-like); ``kind`` overrides the
118 detection by host (a self-hosted forge whose host does not name it)."""
119 parsed = _host_and_path(url)
120 if parsed is None:
121 return None
122 host, path = parsed
123 path = path.removesuffix(".git")
124 detected = kind if kind not in {None, "auto"} else kind_of_host(host)
125 if detected is None:
126 return None
127 if detected == "azure-devops":
128 repository = _azure_repository(host, path)
129 if repository is None: 129 ↛ 130line 129 didn't jump to line 130 because the condition on line 129 was never true
130 return None
131 api_host = "dev.azure.com" if host == _AZURE_SSH_HOST else host
132 return ForgeLocation(
133 detected, api_host, repository, default_api_url(detected, api_host, repository)
134 )
135 if path.startswith("scm/"): # Bitbucket Server style; kept as the path after it 135 ↛ 136line 135 didn't jump to line 136 because the condition on line 135 was never true
136 path = path.removeprefix("scm/")
137 segments = [item for item in path.split("/") if item]
138 if len(segments) < 2: 138 ↛ 139line 138 didn't jump to line 139 because the condition on line 138 was never true
139 return None
140 repository = "/".join(segments) if detected == "gitlab" else "/".join(segments[:2])
141 return ForgeLocation(detected, host, repository, default_api_url(detected, host, repository))
144__all__ = ["KNOWN_FORGES", "ForgeLocation", "default_api_url", "kind_of_host", "parse_remote"]