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