Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import {
3 buildCommitUrl,
4 changeRequestUrlBelow,
5 defineSourceControl,
6 isChangeRequestAuthorityOfProject,
7 parseChangeRequestPath,
8 parseCommitPath,
9 remoteWebOrigin,
10} from "@t3tools/source-control-core/shared/definition";
11import { icon } from "./icon.ts";
12
13// Azure DevOps Server runs on any hostname; its `_git` route identifies it.
14const CHANGE_REQUEST_PATH = /^\/((?:[^/]+\/)*_git\/[^/]+)\/pullrequest\/(\d+)(?:\/|$)/u;
15const COMMIT_PATH = /^\/((?:[^/]+\/)*_git\/[^/]+)\/commit\/([0-9a-f]+)\/?$/iu;
16const CHECKOUT_COMMAND = /^az\s+repos\s+pr\s+checkout\s+(.+)$/i;
17const CHANGE_REQUEST_REFERENCE =
18 /^https:\/\/(?:dev\.azure\.com\/[^/\s]+\/[^/\s]+|[^/\s]+\.visualstudio\.com\/(?:DefaultCollection\/)?[^/\s]+)\/_git\/[^/\s]+\/pullrequest\/(\d+)(?:[/?#].*)?$/i;
19
20// `ssh.dev.azure.com` is the default SSH clone host (git@ssh.dev.azure.com:v3/org/project/repo),
21// so any `*.dev.azure.com` subdomain is Azure. Legacy hosts stay under `.visualstudio.com`,
22// including `vs-ssh.visualstudio.com`.
23function isAzureHostname(hostname: string): boolean {
24 return (
25 hostname === "dev.azure.com" ||
26 hostname.endsWith(".dev.azure.com") ||
27 hostname.endsWith(".visualstudio.com")
28 );
29}
30
31/**
32 * Azure alone addresses one repository under two names that share no part: `ssh.dev.azure.com` and
33 * `v3/{org}/{project}/{repo}` over SSH, against `dev.azure.com` and `{org}/{project}/_git/{repo}`
34 * everywhere a person sees it. A project cloned over SSH would otherwise be a different repository
35 * to every comparison made against a pull request URL, which arrives in the web spelling.
36 */
37function repositoryKeyFromRemote(key: string): string | null {
38 const match =
39 /^(ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)\/v3\/([^/]+)\/([^/]+)\/([^/]+)$/u.exec(key);
40 if (match === null) {
41 // Azure takes a name as written, so its keys keep the `.git` other hosts drop.
42 return isAzureHostname(key.split("/", 1)[0]!) ? key : null;
43 }
44 const [, host, organization, project, repository] = match;
45 return host === "ssh.dev.azure.com"
46 ? `dev.azure.com/${organization}/${project}/_git/${repository}`
47 : `${organization}.visualstudio.com/${project}/_git/${repository}`;
48}
49
50/** Every spelling of an Azure DevOps Services repository, on `dev.azure.com`. */
51function canonicalRepositoryKey(key: string): string | null {
52 const canonical = key
53 .replace(
54 /^(?:ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)\/v3\/([^/]+)\/([^/]+)\/([^/]+)$/u,
55 "dev.azure.com/$1/$2/_git/$3",
56 )
57 .replace(
58 /^([^.]+)\.visualstudio\.com\/(?:defaultcollection\/)?([^/]+)\/_git\/([^/]+)$/u,
59 "dev.azure.com/$1/$2/_git/$3",
60 );
61 return canonical.startsWith("dev.azure.com/") ? canonical : null;
62}
63
64function decodeUrlPathSegment(segment: string): string {
65 try {
66 return decodeURIComponent(segment);
67 } catch {
68 return segment;
69 }
70}
71
72function checkoutCommandId(args: string): string | null {
73 const parts = args.trim().split(/\s+/).filter(Boolean);
74 for (const [index, part] of parts.entries()) {
75 if (part === "--id" || part === "-i") return parts[index + 1] ?? null;
76 if (part.startsWith("--id=")) return part.slice("--id=".length) || null;
77 }
78 return parts.find((part) => !part.startsWith("-")) ?? null;
79}
80
81const KIND = SourceControlProviderKind.make("azure-devops");
82
83export const definition = defineSourceControl({
84 kind: KIND,
85 label: "Azure DevOps",
86 pickerLabel: "Azure DevOps",
87 icon,
88 changeRequest: {
89 shortLabel: "PR",
90 shortLabelWithArticle: "a PR",
91 singular: "pull request",
92 plural: "pull requests",
93 },
94 repositoryPathHint: "project/repository",
95 // `az repos` reads need the checkout's organization and project, so a bare hostname names no
96 // repository this client can act on.
97 publicHost: null,
98 publishDescription: "dev.azure.com",
99 publishHost: () => "dev.azure.com",
100 newRepositoryOwner: () => null,
101 defaultCloneTransport: "ssh",
102 changeRequestUrl: ({ host, repository, number, remoteUrl, webUrl }) => {
103 if (webUrl) return changeRequestUrlBelow(webUrl, `pullrequest/${number}`);
104 const key = `${host}/${repository}`.toLowerCase();
105 const [canonicalHost = host, ...path] = (canonicalRepositoryKey(key) ?? key).split("/");
106 return `${remoteWebOrigin(canonicalHost, remoteUrl)}/${path.join("/")}/pullrequest/${number}`;
107 },
108 commitUrl: (input) => {
109 const key = `${input.host}/${input.repository}`.toLowerCase();
110 const [host = input.host, ...path] = (canonicalRepositoryKey(key) ?? key).split("/");
111 return buildCommitUrl({ ...input, host, repository: path.join("/") }, "commit");
112 },
113 parseCommitUrl: (url) => parseCommitPath(url, COMMIT_PATH),
114 // Servers on different ports are different servers, so a port stays in the link.
115 parseChangeRequestUrl: (url) => {
116 const link = parseChangeRequestPath(url, CHANGE_REQUEST_PATH);
117 return link === null || url.port === "" ? link : { ...link, authority: url.host.toLowerCase() };
118 },
119 changeRequestUrlFromReferenceAutolink: () => null,
120 changeRequestActions: new Set([
121 "merge",
122 "ready",
123 "draft",
124 "close",
125 "reopen",
126 "enable-auto-merge",
127 "disable-auto-merge",
128 ] as const),
129 checkoutCommand: ({ number }) => `az repos pr checkout --id ${number}`,
130 // Completing or abandoning is a status change, the same `update` this package runs.
131 changeRequestCloseCommand:
132 /\baz\s+repos\s+pr\s+update\b[^;&|]*--status[\s=]+["']?(?:completed|abandoned)\b/u,
133 authorProfileUrl: () => null,
134 hardLineBreaks: true,
135 reviewSummaryRequired: () => false,
136 checkoutCommandArgument: (input) => {
137 const args = CHECKOUT_COMMAND.exec(input)?.[1];
138 return args ? checkoutCommandId(args) : null;
139 },
140 isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
141 checkoutChangeRequestHost: () => null,
142 recognizeRemote: ({ host, hostname }) =>
143 isAzureHostname(hostname)
144 ? { kind: KIND, name: "Azure DevOps", baseUrl: `https://${host}` }
145 : null,
146 /**
147 * `az repos pr list --repository` takes a name; organisation and project come from checkout.
148 * Decode the remote URL's name segment: `az` treats escapes literally and returns 404.
149 */
150 repositorySelector: (identity) => {
151 const segments = (identity.displayName ?? "").split("/").filter((part) => part !== "_git");
152 const name = identity.name || segments.at(-1);
153 return name ? decodeUrlPathSegment(name) : null;
154 },
155 repositoryKeyFromRemote,
156 canonicalRepositoryKey,
157 isChangeRequestInRepository: (identity, link) => {
158 if (!isChangeRequestAuthorityOfProject(identity, link)) return false;
159 const projectKey = identity.canonicalKey.toLowerCase();
160 const linkKey = `${link.host}/${link.repository}`.toLowerCase();
161 return (
162 (canonicalRepositoryKey(projectKey) ?? projectKey) ===
163 (canonicalRepositoryKey(linkKey) ?? linkKey)
164 );
165 },
166 canReadChangeRequestOnHost: () => false,
167});