Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
5
6import * as AzureDevOpsChangeRequestTemplate from "./azureDevOpsChangeRequestTemplate.ts";
7import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
8import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
9import type { NormalizedAzureDevOpsPullRequestRecord } from "./azureDevOpsPullRequests.ts";
10import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
11import {
12 combinedAuthOutput,
13 firstSafeAuthLine,
14 providerAuth,
15 type SourceControlAuthProbeInput,
16 type SourceControlCliDiscoverySpec,
17} from "@t3tools/source-control-core/server/discovery";
18
19function parseAzureAuth(input: SourceControlAuthProbeInput) {
20 const account = input.stdout.trim().split(/\r?\n/)[0]?.trim();
21
22 if (input.exitCode !== 0) {
23 return providerAuth({
24 status: "unauthenticated",
25 detail:
26 firstSafeAuthLine(combinedAuthOutput(input)) ?? "Run `az login` to authenticate Azure CLI.",
27 });
28 }
29
30 if (account !== undefined && account.length > 0) {
31 return providerAuth({
32 status: "authenticated",
33 account,
34 host: "dev.azure.com",
35 });
36 }
37
38 return providerAuth({
39 status: "unknown",
40 host: "dev.azure.com",
41 detail: "Azure CLI account status could not be parsed.",
42 });
43}
44
45export const discovery = {
46 type: "cli",
47 kind: SourceControlProviderKind.make("azure-devops"),
48 label: "Azure DevOps",
49 executable: "az",
50 versionArgs: ["--version"],
51 authArgs: ["account", "show", "--query", "user.name", "-o", "tsv"],
52 // `az --version` starts Python and takes ~6s on Windows, exceeding the default probe timeout.
53 probeTimeoutMs: 20_000,
54 parseAuth: parseAzureAuth,
55 installHint:
56 "Install the Azure command-line tools (`az`), then enable Azure DevOps support with `az extension add --name azure-devops`.",
57} satisfies SourceControlCliDiscoverySpec;
58
59/**
60 * The repository name a remote ends in; `az` takes it decoded and finds org and project itself.
61 * Azure clone URLs carry no `.git` suffix, so a trailing `.git` is part of the name.
62 */
63function repositoryNameFromRemote(remoteUrl: string): string | null {
64 const path = URL.parse(remoteUrl.trim())?.pathname ?? remoteUrl.trim();
65 const encoded = path.replace(/\/+$/u, "").split(/[/:]/u).at(-1);
66 if (!encoded) return null;
67 let name = encoded;
68 try {
69 name = decodeURIComponent(encoded);
70 } catch {}
71 // `az` replaces any argument value starting with `@` by the contents of that local file.
72 return name.startsWith("@") ? null : name;
73}
74
75/** The remote T3 selected, which scopes `az` instead of the checkout's primary remote. */
76const remoteOf = (input: { readonly context?: { readonly remoteUrl: string } | undefined }) =>
77 input.context === undefined ? {} : { remoteUrl: input.context.remoteUrl };
78
79function toChangeRequest(summary: NormalizedAzureDevOpsPullRequestRecord): ChangeRequest {
80 return {
81 provider: SourceControlProviderKind.make("azure-devops"),
82 number: summary.number,
83 title: summary.title,
84 url: summary.url,
85 baseRefName: summary.baseRefName,
86 headRefName: summary.headRefName,
87 ...(summary.headSha !== undefined ? { headSha: summary.headSha } : {}),
88 state: summary.state,
89 ...(summary.isDraft === true ? { isDraft: true } : {}),
90 closedAt: summary.closedAt ?? null,
91 mergedAt: summary.mergedAt ?? null,
92 updatedAt: summary.updatedAt,
93 isCrossRepository: summary.isCrossRepository,
94 };
95}
96
97export const make = Effect.gen(function* () {
98 const azure = yield* AzureDevOpsCli.AzureDevOpsCli;
99 const { git } = yield* SourceControlHost.SourceControlHost;
100
101 return SourceControlProvider.SourceControlProvider.of({
102 kind: SourceControlProviderKind.make("azure-devops"),
103 // Azure lists fork pull requests by source branch with no owner filter, so read a full page.
104 headBranchProbe: ({ headSelectors }) => ({
105 headSelectors: headSelectors.filter((selector) => !selector.includes(":")),
106 limit: 100,
107 }),
108 readChangeRequestTemplate: Effect.fn(
109 "AzureDevOpsSourceControlProvider.readChangeRequestTemplate",
110 )(
111 function* ({ cwd }) {
112 // Azure uses the repository default branch even when the PR targets another branch.
113 const remoteName = yield* git.resolvePrimaryRemoteName(cwd);
114 const defaultRef = yield* git.execute({
115 operation: "AzureDevOpsSourceControlProvider.resolveDefaultBranch",
116 cwd,
117 args: ["symbolic-ref", `refs/remotes/${remoteName}/HEAD`],
118 });
119 return yield* AzureDevOpsChangeRequestTemplate.detect(
120 cwd,
121 defaultRef.stdout.trim(),
122 git.execute,
123 );
124 },
125 Effect.orElseSucceed(() => Option.none()),
126 ),
127 listChangeRequests: Effect.fn("AzureDevOpsSourceControlProvider.listChangeRequests")(
128 function (input) {
129 const source = SourceControlProvider.sourceControlRefFromInput(input);
130 return azure
131 .listPullRequests({
132 cwd: input.cwd,
133 ...remoteOf(input),
134 headSelector: input.headSelector,
135 ...(source !== undefined ? { source } : {}),
136 state: input.state,
137 ...(input.limit !== undefined ? { limit: input.limit } : {}),
138 })
139 .pipe(
140 Effect.map((items) => items.map(toChangeRequest)),
141 Effect.mapError(
142 (error) =>
143 new SourceControlProviderError({
144 provider: SourceControlProviderKind.make("azure-devops"),
145 operation: "listChangeRequests",
146 command: error.command,
147 cwd: input.cwd,
148 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
149 input.headSelector,
150 ),
151 detail: error.detail,
152 cause: error,
153 }),
154 ),
155 );
156 },
157 ),
158 getChangeRequest: Effect.fn("AzureDevOpsSourceControlProvider.getChangeRequest")(
159 function (input) {
160 return azure
161 .getPullRequest({ cwd: input.cwd, reference: input.reference, ...remoteOf(input) })
162 .pipe(
163 Effect.map(toChangeRequest),
164 Effect.mapError(
165 (error) =>
166 new SourceControlProviderError({
167 provider: SourceControlProviderKind.make("azure-devops"),
168 operation: "getChangeRequest",
169 command: error.command,
170 cwd: input.cwd,
171 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
172 input.reference,
173 ),
174 detail: error.detail,
175 cause: error,
176 }),
177 ),
178 );
179 },
180 ),
181 createChangeRequest: Effect.fn("AzureDevOpsSourceControlProvider.createChangeRequest")(
182 function (input) {
183 const source = SourceControlProvider.sourceControlRefFromInput(input);
184 return azure
185 .createPullRequest({
186 cwd: input.cwd,
187 ...remoteOf(input),
188 baseBranch: input.baseRefName,
189 headSelector: input.headSelector,
190 ...(source !== undefined ? { source } : {}),
191 ...(input.target !== undefined ? { target: input.target } : {}),
192 title: input.title,
193 bodyFile: input.bodyFile,
194 })
195 .pipe(
196 Effect.mapError(
197 (error) =>
198 new SourceControlProviderError({
199 provider: SourceControlProviderKind.make("azure-devops"),
200 operation: "createChangeRequest",
201 command: error.command,
202 cwd: input.cwd,
203 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
204 input.headSelector,
205 ),
206 detail: error.detail,
207 cause: error,
208 }),
209 ),
210 );
211 },
212 ),
213 getRepositoryCloneUrls: Effect.fn("AzureDevOpsSourceControlProvider.getRepositoryCloneUrls")(
214 function (input) {
215 return azure
216 .getRepositoryCloneUrls({
217 cwd: input.cwd,
218 repository: input.repository,
219 ...remoteOf(input),
220 })
221 .pipe(
222 Effect.mapError(
223 (error) =>
224 new SourceControlProviderError({
225 provider: SourceControlProviderKind.make("azure-devops"),
226 operation: "getRepositoryCloneUrls",
227 command: error.command,
228 cwd: input.cwd,
229 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
230 input.repository,
231 ),
232 detail: error.detail,
233 cause: error,
234 }),
235 ),
236 );
237 },
238 ),
239 createRepository: Effect.fn("AzureDevOpsSourceControlProvider.createRepository")(
240 function (input) {
241 return azure.createRepository(input).pipe(
242 Effect.mapError(
243 (error) =>
244 new SourceControlProviderError({
245 provider: SourceControlProviderKind.make("azure-devops"),
246 operation: "createRepository",
247 command: error.command,
248 cwd: input.cwd,
249 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
250 input.repository,
251 ),
252 detail: error.detail,
253 cause: error,
254 }),
255 ),
256 );
257 },
258 ),
259 getDefaultBranch: Effect.fn("AzureDevOpsSourceControlProvider.getDefaultBranch")(
260 function (input) {
261 const remoteUrl = input.context?.remoteUrl;
262 const repository = remoteUrl === undefined ? null : repositoryNameFromRemote(remoteUrl);
263 if (remoteUrl === undefined || repository === null) return Effect.succeed(null);
264 return azure.getDefaultBranch({ cwd: input.cwd, repository, remoteUrl }).pipe(
265 Effect.mapError(
266 (error) =>
267 new SourceControlProviderError({
268 provider: SourceControlProviderKind.make("azure-devops"),
269 operation: "getDefaultBranch",
270 command: error.command,
271 cwd: input.cwd,
272 detail: error.detail,
273 cause: error,
274 }),
275 ),
276 );
277 },
278 ),
279 // `az repos pr checkout` ignores git failures: in a single-branch clone its checkout fails
280 // and its pull then merges the pull request into the current branch.
281 checkoutChangeRequest: Effect.fn("AzureDevOpsSourceControlProvider.checkoutChangeRequest")(
282 function* (input) {
283 const pullRequest = yield* azure.getPullRequest({
284 cwd: input.cwd,
285 reference: input.reference,
286 ...remoteOf(input),
287 });
288 if (pullRequest.isCrossRepository)
289 return yield* new SourceControlProviderError({
290 provider: SourceControlProviderKind.make("azure-devops"),
291 operation: "checkoutChangeRequest",
292 cwd: input.cwd,
293 reference: SourceControlProvider.transportSafeSourceControlErrorValue(input.reference),
294 detail: "Checking out an Azure DevOps pull request from a fork is not supported.",
295 });
296 const branch = pullRequest.headRefName;
297 const remoteBranch = {
298 cwd: input.cwd,
299 remoteName: input.context?.remoteName ?? "origin",
300 remoteBranch: branch,
301 };
302 // An existing branch is only switched to; the caller advances it without losing commits.
303 if ((yield* git.listLocalBranchNames(input.cwd)).includes(branch))
304 yield* git.fetchRemoteTrackingBranch(remoteBranch);
305 else yield* git.fetchRemoteBranch({ ...remoteBranch, localBranch: branch });
306 yield* git.switchRef({ cwd: input.cwd, refName: branch });
307 },
308 (effect, input) =>
309 effect.pipe(
310 Effect.mapError((error) =>
311 error._tag === "SourceControlProviderError"
312 ? error
313 : new SourceControlProviderError({
314 provider: SourceControlProviderKind.make("azure-devops"),
315 operation: "checkoutChangeRequest",
316 command: error.command,
317 cwd: input.cwd,
318 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
319 input.reference,
320 ),
321 detail: error.detail,
322 cause: error,
323 }),
324 ),
325 ),
326 ),
327 });
328});