Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import type {
3 RepositoryIdentity,
4 SourceControlHostOverrides,
5 SourceControlProviderInfo,
6} from "@t3tools/contracts";
7
8export interface ChangeRequestPresentation {
9 readonly icon:
10 | "github"
11 | "gitlab"
12 | "forgejo"
13 | "azure-devops"
14 | "bitbucket"
15 | "gitcafe"
16 | "change-request";
17 readonly providerName: string;
18 readonly shortName: string;
19 readonly longName: string;
20 readonly pluralLongName: string;
21 readonly providerLongName: string;
22 readonly checkoutCommandExample?: string;
23 readonly urlExample: string;
24}
25
26export interface ChangeRequestTerminology {
27 readonly shortLabel: string;
28 readonly singular: string;
29}
30
31const GITHUB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
32 icon: "github",
33 providerName: "GitHub",
34 shortName: "PR",
35 longName: "pull request",
36 pluralLongName: "pull requests",
37 providerLongName: "GitHub pull request",
38 checkoutCommandExample: "gh pr checkout 123",
39 urlExample: "https://github.com/owner/repo/pull/42",
40};
41
42const GITLAB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
43 icon: "gitlab",
44 providerName: "GitLab",
45 shortName: "MR",
46 longName: "merge request",
47 pluralLongName: "merge requests",
48 providerLongName: "GitLab merge request",
49 checkoutCommandExample: "glab mr checkout 123",
50 urlExample: "https://gitlab.com/group/project/-/merge_requests/42",
51};
52
53const FORGEJO_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
54 icon: "forgejo",
55 providerName: "Forgejo",
56 shortName: "PR",
57 longName: "pull request",
58 pluralLongName: "pull requests",
59 providerLongName: "Forgejo pull request",
60 checkoutCommandExample: "tea pr checkout 123",
61 urlExample: "https://codeberg.org/owner/repo/pulls/42",
62};
63
64const AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
65 icon: "azure-devops",
66 providerName: "Azure DevOps",
67 shortName: "PR",
68 longName: "pull request",
69 pluralLongName: "pull requests",
70 providerLongName: "Azure DevOps pull request",
71 checkoutCommandExample: "az repos pr checkout --id 123",
72 urlExample: "https://dev.azure.com/org/project/_git/repo/pullrequest/42",
73};
74
75const BITBUCKET_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
76 icon: "bitbucket",
77 providerName: "Bitbucket",
78 shortName: "PR",
79 longName: "pull request",
80 pluralLongName: "pull requests",
81 providerLongName: "Bitbucket pull request",
82 urlExample: "https://bitbucket.org/workspace/repo/pull-requests/42",
83};
84
85const GITCAFE_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
86 icon: "gitcafe",
87 providerName: "GitCafe",
88 shortName: "PR",
89 longName: "pull request",
90 pluralLongName: "pull requests",
91 providerLongName: "GitCafe pull request",
92 checkoutCommandExample: "cafe pr checkout 123",
93 urlExample: "https://git.cafe/owner/repo/pulls/42",
94};
95
96const GENERIC_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
97 icon: "change-request",
98 providerName: "source control",
99 shortName: "change request",
100 longName: "change request",
101 pluralLongName: "change requests",
102 providerLongName: "change request",
103 urlExample: "#42",
104};
105
106export function resolveChangeRequestPresentation(
107 provider: SourceControlProviderInfo | null | undefined,
108): ChangeRequestPresentation {
109 switch (provider?.kind) {
110 case "github":
111 case undefined:
112 return GITHUB_CHANGE_REQUEST_PRESENTATION;
113 case "gitlab":
114 return GITLAB_CHANGE_REQUEST_PRESENTATION;
115 case "forgejo":
116 return FORGEJO_CHANGE_REQUEST_PRESENTATION;
117 case "azure-devops":
118 return AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION;
119 case "bitbucket":
120 return BITBUCKET_CHANGE_REQUEST_PRESENTATION;
121 case "gitcafe":
122 return GITCAFE_CHANGE_REQUEST_PRESENTATION;
123 default:
124 return GENERIC_CHANGE_REQUEST_PRESENTATION;
125 }
126}
127
128function resolveChangeRequestPresentationForKind(
129 kind: SourceControlProviderKind,
130): ChangeRequestPresentation {
131 return resolveChangeRequestPresentation({ kind, name: "", baseUrl: "" });
132}
133
134export function getChangeRequestTerminologyForKind(
135 kind: SourceControlProviderKind,
136): ChangeRequestTerminology {
137 const presentation = resolveChangeRequestPresentationForKind(kind);
138 return {
139 shortLabel: presentation.shortName,
140 singular: presentation.longName,
141 };
142}
143
144const SCP_SSH_REMOTE_PATTERN = /^[a-zA-Z0-9._-]+@([^:/]+):/;
145
146export function isSshRemoteUrl(remoteUrl: string): boolean {
147 const trimmed = remoteUrl.trim();
148 return SCP_SSH_REMOTE_PATTERN.test(trimmed) || trimmed.toLowerCase().startsWith("ssh://");
149}
150
151function parseRemoteHost(remoteUrl: string, includeSshPort = false): string | null {
152 const trimmed = remoteUrl.trim();
153 if (trimmed.length === 0) {
154 return null;
155 }
156
157 const scpMatch = SCP_SSH_REMOTE_PATTERN.exec(trimmed);
158 if (scpMatch?.[1]) {
159 return scpMatch[1].toLowerCase();
160 }
161
162 try {
163 const url = new URL(trimmed);
164 return (url.protocol === "ssh:" && !includeSshPort ? url.hostname : url.host).toLowerCase();
165 } catch {
166 return null;
167 }
168}
169
170function parseHostName(host: string): string {
171 try {
172 return new URL(`https://${host}`).hostname.toLowerCase();
173 } catch {
174 return host.replace(/:\d+$/u, "").toLowerCase();
175 }
176}
177
178function toBaseUrl(host: string): string {
179 return `https://${host}`;
180}
181
182function hasDnsLabel(host: string, label: string): boolean {
183 return host.split(".").includes(label);
184}
185
186/** `*.ghe.com` is GitHub Enterprise Cloud with data residency, one subdomain per enterprise. */
187function isGitHubHost(host: string): boolean {
188 return host === "github.com" || host.endsWith(".ghe.com") || hasDnsLabel(host, "github");
189}
190
191function isGitLabHost(host: string): boolean {
192 return host === "gitlab.com" || hasDnsLabel(host, "gitlab");
193}
194
195function isAzureDevOpsHost(host: string): boolean {
196 // `ssh.dev.azure.com` is the default Azure DevOps SSH clone host
197 // (git@ssh.dev.azure.com:v3/org/project/repo), so match any `*.dev.azure.com`
198 // subdomain, not just the bare `dev.azure.com`. Legacy hosts stay under
199 // `.visualstudio.com` (including `vs-ssh.visualstudio.com`).
200 return (
201 host === "dev.azure.com" ||
202 host.endsWith(".dev.azure.com") ||
203 host.endsWith(".visualstudio.com")
204 );
205}
206
207function isGitCafeHost(host: string): boolean {
208 return host === "git.cafe" || host === "staging.git.cafe";
209}
210
211function isBitbucketHost(host: string): boolean {
212 return host === "bitbucket.org" || hasDnsLabel(host, "bitbucket");
213}
214
215export function sourceControlHostOverridesKey(overrides: SourceControlHostOverrides): string {
216 return JSON.stringify(
217 Object.entries(overrides)
218 .sort(([left], [right]) => left.toLowerCase().localeCompare(right.toLowerCase()))
219 .map(([host, value]) => [
220 host.toLowerCase(),
221 value.kind,
222 value.baseUrl === undefined ? null : new URL(value.baseUrl).toString().replace(/\/+$/, ""),
223 ]),
224 );
225}
226
227export function sourceControlHostOverrideForRemoteUrl(
228 remoteUrl: string,
229 overrides: SourceControlHostOverrides,
230) {
231 const authority = parseRemoteHost(remoteUrl, true);
232 if (authority === null) return undefined;
233 const entries = Object.entries(overrides);
234 if (/^https?:/iu.test(remoteUrl.trim())) {
235 const url = new URL(remoteUrl.trim());
236 const port = url.port || (url.protocol === "https:" ? "443" : "80");
237 const specific = entries.find(
238 ([host]) => host.toLowerCase() === `${url.hostname}:${port}`,
239 )?.[1];
240 if (specific !== undefined) return specific;
241 }
242 return (
243 entries.find(([host]) => host.toLowerCase() === authority)?.[1] ??
244 entries.find(([host]) => host.toLowerCase() === parseHostName(authority))?.[1]
245 );
246}
247
248export function detectSourceControlProviderFromRemoteUrl(
249 remoteUrl: string,
250 overrides: SourceControlHostOverrides = {},
251): SourceControlProviderInfo | null {
252 const host = parseRemoteHost(remoteUrl);
253 if (!host) {
254 return null;
255 }
256 const hostname = parseHostName(host);
257 const override = sourceControlHostOverrideForRemoteUrl(remoteUrl, overrides);
258 if (override !== undefined) {
259 const kind = SourceControlProviderKind.make(override.kind);
260 return {
261 kind,
262 name: resolveChangeRequestPresentationForKind(kind).providerName,
263 baseUrl:
264 override.baseUrl?.replace(/\/+$/, "") ??
265 (/^https?:/iu.test(remoteUrl.trim()) ? new URL(remoteUrl.trim()).origin : toBaseUrl(host)),
266 };
267 }
268
269 if (isGitCafeHost(hostname)) {
270 return {
271 kind: SourceControlProviderKind.make("gitcafe"),
272 name: "GitCafe",
273 baseUrl: toBaseUrl(hostname),
274 };
275 }
276
277 if (
278 hostname === "codeberg.org" ||
279 hasDnsLabel(hostname, "forgejo") ||
280 hasDnsLabel(hostname, "gitea")
281 ) {
282 return {
283 kind: SourceControlProviderKind.make("forgejo"),
284 name: "Forgejo",
285 baseUrl: /^https?:/iu.test(remoteUrl.trim())
286 ? new URL(remoteUrl.trim()).origin
287 : toBaseUrl(host),
288 };
289 }
290
291 if (isGitHubHost(hostname)) {
292 return {
293 kind: SourceControlProviderKind.make("github"),
294 name: hostname === "github.com" ? "GitHub" : "GitHub Self-Hosted",
295 baseUrl: toBaseUrl(host),
296 };
297 }
298
299 if (isGitLabHost(hostname)) {
300 return {
301 kind: SourceControlProviderKind.make("gitlab"),
302 name: hostname === "gitlab.com" ? "GitLab" : "GitLab Self-Hosted",
303 baseUrl: toBaseUrl(host),
304 };
305 }
306
307 if (isAzureDevOpsHost(hostname)) {
308 return {
309 kind: SourceControlProviderKind.make("azure-devops"),
310 name: "Azure DevOps",
311 baseUrl: toBaseUrl(host),
312 };
313 }
314
315 if (isBitbucketHost(hostname)) {
316 return {
317 kind: SourceControlProviderKind.make("bitbucket"),
318 name: hostname === "bitbucket.org" ? "Bitbucket" : "Bitbucket Self-Hosted",
319 baseUrl: toBaseUrl(host),
320 };
321 }
322
323 return {
324 kind: SourceControlProviderKind.make("unknown"),
325 name: host,
326 baseUrl: toBaseUrl(host),
327 };
328}
329
330/**
331 * Azure DevOps is the exception: `az repos pr list --repository` takes a repository name, and
332 * takes the organisation and project from the checkout it detects — so the recorded
333 * `org/project/_git/repo` path is refused outright and the whole repository reads as
334 * unavailable. Its name is the last segment, which is what this hands over.
335 */
336export function sourceControlRepositorySelector(
337 identity:
338 | Pick<RepositoryIdentity, "provider" | "displayName" | "owner" | "name">
339 | null
340 | undefined,
341): string | null {
342 if (!identity) return null;
343 if (identity.provider === "azure-devops") {
344 const segments = (identity.displayName ?? "").split("/").filter((part) => part !== "_git");
345 return identity.name || segments.at(-1) || null;
346 }
347 if (identity.displayName) return identity.displayName;
348 return identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null;
349}
350
351export function canonicalRepositoryKey(key: string): string {
352 return key
353 .replace(
354 /^(?:ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)\/v3\/([^/]+)\/([^/]+)\/([^/]+)$/u,
355 "dev.azure.com/$1/$2/_git/$3",
356 )
357 .replace(
358 /^([^.]+)\.visualstudio\.com\/(?:defaultcollection\/)?([^/]+)\/_git\/([^/]+)$/u,
359 "dev.azure.com/$1/$2/_git/$3",
360 );
361}