Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as PlatformError from "effect/PlatformError";
5import * as Result from "effect/Result";
6import * as Schema from "effect/Schema";
7import {
8 NonNegativeInt,
9 TrimmedNonEmptyString,
10 type SourceControlRepositoryVisibility,
11 type VcsError,
12 type VcsProcessExitFailureKind,
13} from "@t3tools/contracts";
14
15import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
16import * as HostProcess from "@t3tools/shared/HostProcess";
17import { SpawnExecutableResolution } from "@t3tools/shared/shell";
18import { AzureCliInstallLocation } from "./azureCliLauncher.ts";
19import {
20 decodeAzureDevOpsPullRequestJson,
21 decodeAzureDevOpsPullRequestListJson,
22 type NormalizedAzureDevOpsPullRequestRecord,
23} from "./azureDevOpsPullRequests.ts";
24import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
25
26const DEFAULT_TIMEOUT_MS = 30_000;
27
28const azureDevOpsCommandErrorFields = {
29 operation: Schema.Literal("execute"),
30 command: Schema.Literal("az"),
31 cwd: Schema.String,
32 argumentCount: NonNegativeInt,
33 cause: Schema.Defect(),
34};
35
36export class AzureDevOpsCliUnavailableError extends Schema.TaggedError<AzureDevOpsCliUnavailableError>()(
37 "AzureDevOpsCliUnavailableError",
38 azureDevOpsCommandErrorFields,
39) {
40 get detail(): string {
41 return "Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.";
42 }
43
44 override get message(): string {
45 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
46 }
47}
48
49export class AzureDevOpsCliAuthenticationError extends Schema.TaggedError<AzureDevOpsCliAuthenticationError>()(
50 "AzureDevOpsCliAuthenticationError",
51 azureDevOpsCommandErrorFields,
52) {
53 get detail(): string {
54 return "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.";
55 }
56
57 override get message(): string {
58 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
59 }
60}
61
62export class AzureDevOpsCliRateLimitError extends Schema.TaggedError<AzureDevOpsCliRateLimitError>()(
63 "AzureDevOpsCliRateLimitError",
64 azureDevOpsCommandErrorFields,
65) {
66 get detail(): string {
67 return "Azure DevOps API rate limit exceeded.";
68 }
69
70 override get message(): string {
71 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
72 }
73}
74
75export class AzureDevOpsPullRequestNotFoundError extends Schema.TaggedError<AzureDevOpsPullRequestNotFoundError>()(
76 "AzureDevOpsPullRequestNotFoundError",
77 azureDevOpsCommandErrorFields,
78) {
79 get detail(): string {
80 return "Pull request not found. Check the PR number or URL and try again.";
81 }
82
83 override get message(): string {
84 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
85 }
86}
87
88export class AzureDevOpsCommandFailedError extends Schema.TaggedError<AzureDevOpsCommandFailedError>()(
89 "AzureDevOpsCommandFailedError",
90 azureDevOpsCommandErrorFields,
91) {
92 get detail(): string {
93 return "Azure DevOps CLI command failed.";
94 }
95
96 override get message(): string {
97 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
98 }
99
100 static fromVcsError(
101 context: {
102 readonly operation: "execute";
103 readonly command: "az";
104 readonly cwd: string;
105 readonly argumentCount: number;
106 },
107 cause: VcsError,
108 ): AzureDevOpsCliError {
109 const fields = { ...context, cause };
110
111 if (
112 cause._tag === "VcsProcessSpawnError" &&
113 cause.cause instanceof PlatformError.PlatformError &&
114 cause.cause.reason._tag === "NotFound" &&
115 cause.cause.reason.pathOrDescriptor !== context.cwd &&
116 cause.cause.reason.syscall !== "chdir"
117 ) {
118 return new AzureDevOpsCliUnavailableError(fields);
119 }
120
121 if (cause._tag === "VcsProcessExitError") {
122 if (cause.failureKind === "authentication") {
123 return new AzureDevOpsCliAuthenticationError(fields);
124 }
125 if (cause.failureKind === "rate-limited") {
126 return new AzureDevOpsCliRateLimitError(fields);
127 }
128 if (cause.failureKind === "not-found") {
129 return new AzureDevOpsPullRequestNotFoundError(fields);
130 }
131 }
132
133 return new AzureDevOpsCommandFailedError(fields);
134 }
135}
136
137const azureDevOpsDecodeErrorFields = {
138 command: Schema.Literal("az"),
139 cwd: Schema.String,
140 outputLength: NonNegativeInt,
141 cause: Schema.Defect(),
142};
143
144export class AzureDevOpsPullRequestListDecodeError extends Schema.TaggedError<AzureDevOpsPullRequestListDecodeError>()(
145 "AzureDevOpsPullRequestListDecodeError",
146 {
147 operation: Schema.Literal("listPullRequests"),
148 ...azureDevOpsDecodeErrorFields,
149 },
150) {
151 get detail(): string {
152 return "Azure DevOps CLI returned invalid PR list JSON.";
153 }
154
155 override get message(): string {
156 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
157 }
158}
159
160export class AzureDevOpsPullRequestDecodeError extends Schema.TaggedError<AzureDevOpsPullRequestDecodeError>()(
161 "AzureDevOpsPullRequestDecodeError",
162 {
163 operation: Schema.Literal("getPullRequest"),
164 ...azureDevOpsDecodeErrorFields,
165 },
166) {
167 get detail(): string {
168 return "Azure DevOps CLI returned invalid pull request JSON.";
169 }
170
171 override get message(): string {
172 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
173 }
174}
175
176const AzureDevOpsRepositoryDecodeOperation = Schema.Literals([
177 "getRepositoryCloneUrls",
178 "getDefaultBranch",
179 "createRepository",
180]);
181
182export class AzureDevOpsRepositoryDecodeError extends Schema.TaggedError<AzureDevOpsRepositoryDecodeError>()(
183 "AzureDevOpsRepositoryDecodeError",
184 {
185 operation: AzureDevOpsRepositoryDecodeOperation,
186 ...azureDevOpsDecodeErrorFields,
187 },
188) {
189 get detail(): string {
190 return "Azure DevOps CLI returned invalid repository JSON.";
191 }
192
193 override get message(): string {
194 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
195 }
196}
197
198export const AzureDevOpsCliError = Schema.Union([
199 AzureDevOpsCliUnavailableError,
200 AzureDevOpsCliAuthenticationError,
201 AzureDevOpsCliRateLimitError,
202 AzureDevOpsPullRequestNotFoundError,
203 AzureDevOpsCommandFailedError,
204 AzureDevOpsPullRequestListDecodeError,
205 AzureDevOpsPullRequestDecodeError,
206 AzureDevOpsRepositoryDecodeError,
207]);
208export type AzureDevOpsCliError = typeof AzureDevOpsCliError.Type;
209
210export interface AzureDevOpsRepositoryCloneUrls {
211 readonly nameWithOwner: string;
212 readonly url: string;
213 readonly sshUrl: string;
214}
215
216export class AzureDevOpsCli extends Context.Service<
217 AzureDevOpsCli,
218 {
219 readonly execute: (input: {
220 readonly cwd: string;
221 readonly args: ReadonlyArray<string>;
222 readonly timeoutMs?: number;
223 readonly maxOutputBytes?: number;
224 }) => Effect.Effect<SourceControlHost.SourceControlProcessOutput, AzureDevOpsCliError>;
225
226 readonly listPullRequests: (input: {
227 readonly cwd: string;
228 readonly headSelector: string;
229 readonly source?: SourceControlProvider.SourceControlRefSelector;
230 readonly state: "open" | "closed" | "merged" | "all";
231 readonly limit?: number;
232 }) => Effect.Effect<ReadonlyArray<NormalizedAzureDevOpsPullRequestRecord>, AzureDevOpsCliError>;
233
234 readonly getPullRequest: (input: {
235 readonly cwd: string;
236 readonly reference: string;
237 }) => Effect.Effect<NormalizedAzureDevOpsPullRequestRecord, AzureDevOpsCliError>;
238
239 readonly getRepositoryCloneUrls: (input: {
240 readonly cwd: string;
241 readonly repository: string;
242 }) => Effect.Effect<AzureDevOpsRepositoryCloneUrls, AzureDevOpsCliError>;
243
244 readonly createRepository: (input: {
245 readonly cwd: string;
246 readonly repository: string;
247 readonly visibility: SourceControlRepositoryVisibility;
248 }) => Effect.Effect<AzureDevOpsRepositoryCloneUrls, AzureDevOpsCliError>;
249
250 readonly createPullRequest: (input: {
251 readonly cwd: string;
252 readonly baseBranch: string;
253 readonly headSelector: string;
254 readonly source?: SourceControlProvider.SourceControlRefSelector;
255 readonly target?: SourceControlProvider.SourceControlRefSelector;
256 readonly title: string;
257 readonly bodyFile: string;
258 }) => Effect.Effect<void, AzureDevOpsCliError>;
259
260 readonly getDefaultBranch: (input: {
261 readonly cwd: string;
262 readonly repository: string;
263 }) => Effect.Effect<string | null, AzureDevOpsCliError>;
264 }
265>()("@t3tools/source-control-azure-devops/server/AzureDevOpsCli") {}
266
267function normalizeChangeRequestId(reference: string): string {
268 const trimmed = reference.trim().replace(/^#/, "");
269 const urlMatch = /(?:pullrequest|pull-request|pull|_pulls?)\/(\d+)(?:\D.*)?$/i.exec(trimmed);
270 return urlMatch?.[1] ?? trimmed;
271}
272
273function toAzureStatus(state: "open" | "closed" | "merged" | "all"): string {
274 switch (state) {
275 case "open":
276 return "active";
277 case "closed":
278 return "abandoned";
279 case "merged":
280 return "completed";
281 case "all":
282 return "all";
283 }
284}
285
286const RawAzureDevOpsRepositorySchema = Schema.Struct({
287 name: TrimmedNonEmptyString,
288 webUrl: TrimmedNonEmptyString,
289 remoteUrl: TrimmedNonEmptyString,
290 sshUrl: TrimmedNonEmptyString,
291 project: Schema.optional(
292 Schema.Struct({
293 name: TrimmedNonEmptyString,
294 }),
295 ),
296 defaultBranch: Schema.optional(Schema.NullOr(Schema.String)),
297});
298
299function normalizeDefaultBranch(value: string | null | undefined): string | null {
300 const trimmed = value?.trim().replace(/^refs\/heads\//, "") ?? "";
301 return trimmed.length > 0 ? trimmed : null;
302}
303
304function normalizeRepositoryCloneUrls(
305 raw: Schema.Schema.Type<typeof RawAzureDevOpsRepositorySchema>,
306): AzureDevOpsRepositoryCloneUrls {
307 const projectName = raw.project?.name.trim();
308 return {
309 nameWithOwner: projectName ? `${projectName}/${raw.name}` : raw.name,
310 url: raw.remoteUrl,
311 sshUrl: raw.sshUrl,
312 };
313}
314
315function parseRepositorySpecifier(repository: string): {
316 readonly project: string | null;
317 readonly name: string;
318} {
319 const parts: Array<string> = [];
320 for (const part of repository.split("/")) {
321 const trimmed = part.trim();
322 if (trimmed.length > 0) {
323 parts.push(trimmed);
324 }
325 }
326 return {
327 project: parts.length > 1 ? (parts.at(-2) ?? null) : null,
328 name: parts.at(-1) ?? repository.trim(),
329 };
330}
331
332function decodeAzureDevOpsJson<S extends Schema.Top>(
333 raw: string,
334 schema: S,
335 operation: typeof AzureDevOpsRepositoryDecodeOperation.Type,
336 cwd: string,
337): Effect.Effect<S["Type"], AzureDevOpsRepositoryDecodeError, S["DecodingServices"]> {
338 return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
339 Effect.mapError(
340 (cause) =>
341 new AzureDevOpsRepositoryDecodeError({
342 operation,
343 command: "az",
344 cwd,
345 outputLength: raw.length,
346 cause,
347 }),
348 ),
349 );
350}
351
352const classifyAzFailure = (stderr: string): VcsProcessExitFailureKind | null => {
353 const normalized = stderr.toLowerCase();
354 if (normalized.includes("az devops login") || /please run '?az login'?/.test(normalized)) {
355 return "authentication";
356 }
357 // Azure DevOps reports usage-limit throttling as TF400733, often without an HTTP status.
358 if (normalized.includes("tf400733")) return "rate-limited";
359 return normalized.includes("pull request") &&
360 (normalized.includes("not found") || normalized.includes("does not exist"))
361 ? "not-found"
362 : null;
363};
364
365export interface AzureCliInvocation {
366 readonly command: string;
367 /** Arguments `az` needs before the caller's, to run the CLI in UTF-8 mode. */
368 readonly args: ReadonlyArray<string>;
369 readonly env?: NodeJS.ProcessEnv;
370}
371
372/**
373 * `-X utf8` is the only way in: the launcher's `-I` implies `-E`, so `PYTHONUTF8` and
374 * `PYTHONIOENCODING` are ignored, and the ANSI code page loses text `az` cannot encode.
375 * Resolved once when the service is built: installing `az` later needs a restart.
376 */
377export const azureCliInvocation = Effect.fn("AzureDevOpsCli.invocation")(function* () {
378 if ((yield* HostProcess.Platform) !== "win32") {
379 return { command: "az", args: [] } satisfies AzureCliInvocation;
380 }
381 const resolveExecutable = yield* SpawnExecutableResolution;
382 const launcher = resolveExecutable("az", "win32", yield* HostProcess.Environment);
383 const installFor = yield* AzureCliInstallLocation;
384 const install = launcher === undefined ? undefined : installFor(launcher);
385 // Unrecognized installs (pipx's Scripts\az.exe) keep the launcher and today's decode.
386 return install === undefined
387 ? ({ command: "az", args: [] } satisfies AzureCliInvocation)
388 : ({
389 command: install.interpreter,
390 args: ["-X", "utf8", "-IBm", "azure.cli"],
391 // What the launcher sets before running this same interpreter.
392 env: { AZ_INSTALLER: install.installer },
393 } satisfies AzureCliInvocation);
394});
395
396/** @public */
397export const make = Effect.gen(function* () {
398 const { process } = yield* SourceControlHost.SourceControlHost;
399 const invocation = yield* azureCliInvocation();
400
401 const execute: AzureDevOpsCli["Service"]["execute"] = (input) =>
402 process
403 .run({
404 operation: "AzureDevOpsCli.execute",
405 command: invocation.command,
406 args: [...invocation.args, ...input.args],
407 cwd: input.cwd,
408 ...(invocation.env === undefined ? {} : { env: invocation.env }),
409 classifyFailure: classifyAzFailure,
410 notFoundDetail: "Pull request not found.",
411 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
412 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
413 })
414 .pipe(
415 Effect.mapError((error) =>
416 AzureDevOpsCommandFailedError.fromVcsError(
417 {
418 operation: "execute",
419 command: "az",
420 cwd: input.cwd,
421 argumentCount: input.args.length,
422 },
423 error,
424 ),
425 ),
426 );
427
428 const executeJson = (input: Parameters<AzureDevOpsCli["Service"]["execute"]>[0]) =>
429 execute({
430 ...input,
431 args: [...input.args, "--only-show-errors", "--output", "json"],
432 });
433
434 return AzureDevOpsCli.of({
435 execute,
436 listPullRequests: Effect.fn("AzureDevOpsCli.listPullRequests")(function (input) {
437 const branch = SourceControlProvider.sourceBranch(input);
438 // az checks literal ref prefixes before constructing the request URL.
439 const refPrefix =
440 ["refs/heads/", "refs/pull/", "refs/tags/"].find((prefix) => branch.startsWith(prefix)) ??
441 "";
442 return executeJson({
443 cwd: input.cwd,
444 args: [
445 "repos",
446 "pr",
447 "list",
448 "--detect",
449 "true",
450 "--source-branch",
451 // az puts this in the query string unescaped; a `#` would cut the request.
452 refPrefix + encodeURIComponent(branch.slice(refPrefix.length)),
453 "--status",
454 toAzureStatus(input.state),
455 "--top",
456 String(input.limit ?? 20),
457 ],
458 }).pipe(
459 Effect.map((result) => result.stdout.trim()),
460 Effect.flatMap((raw) =>
461 raw.length === 0
462 ? Effect.succeed([])
463 : Effect.sync(() => decodeAzureDevOpsPullRequestListJson(raw)).pipe(
464 Effect.flatMap((decoded) => {
465 if (!Result.isSuccess(decoded)) {
466 return Effect.fail(
467 new AzureDevOpsPullRequestListDecodeError({
468 operation: "listPullRequests",
469 command: "az",
470 cwd: input.cwd,
471 outputLength: raw.length,
472 cause: decoded.failure,
473 }),
474 );
475 }
476
477 return Effect.succeed(decoded.success);
478 }),
479 ),
480 ),
481 );
482 }),
483 getPullRequest: Effect.fn("AzureDevOpsCli.getPullRequest")(function (input) {
484 return executeJson({
485 cwd: input.cwd,
486 args: [
487 "repos",
488 "pr",
489 "show",
490 "--detect",
491 "true",
492 "--id",
493 normalizeChangeRequestId(input.reference),
494 ],
495 }).pipe(
496 Effect.map((result) => result.stdout.trim()),
497 Effect.flatMap((raw) =>
498 Effect.sync(() => decodeAzureDevOpsPullRequestJson(raw)).pipe(
499 Effect.flatMap((decoded) => {
500 if (!Result.isSuccess(decoded)) {
501 return Effect.fail(
502 new AzureDevOpsPullRequestDecodeError({
503 operation: "getPullRequest",
504 command: "az",
505 cwd: input.cwd,
506 outputLength: raw.length,
507 cause: decoded.failure,
508 }),
509 );
510 }
511
512 return Effect.succeed(decoded.success);
513 }),
514 ),
515 ),
516 );
517 }),
518 getRepositoryCloneUrls: Effect.fn("AzureDevOpsCli.getRepositoryCloneUrls")(function (input) {
519 const repository = parseRepositorySpecifier(input.repository);
520 return executeJson({
521 cwd: input.cwd,
522 args: [
523 "repos",
524 "show",
525 "--detect",
526 "true",
527 "--repository",
528 repository.name,
529 ...(repository.project ? ["--project", repository.project] : []),
530 ],
531 }).pipe(
532 Effect.map((result) => result.stdout.trim()),
533 Effect.flatMap((raw) =>
534 decodeAzureDevOpsJson(
535 raw,
536 RawAzureDevOpsRepositorySchema,
537 "getRepositoryCloneUrls",
538 input.cwd,
539 ),
540 ),
541 Effect.map(normalizeRepositoryCloneUrls),
542 );
543 }),
544 createRepository: Effect.fn("AzureDevOpsCli.createRepository")(function (input) {
545 const repository = parseRepositorySpecifier(input.repository);
546 // Project/organization permissions control visibility; `az repos create` has no flag.
547 return executeJson({
548 cwd: input.cwd,
549 args: [
550 "repos",
551 "create",
552 "--detect",
553 "true",
554 "--name",
555 repository.name,
556 ...(repository.project ? ["--project", repository.project] : []),
557 ],
558 }).pipe(
559 Effect.map((result) => result.stdout.trim()),
560 Effect.flatMap((raw) =>
561 decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "createRepository", input.cwd),
562 ),
563 Effect.map(normalizeRepositoryCloneUrls),
564 );
565 }),
566 createPullRequest: Effect.fn("AzureDevOpsCli.createPullRequest")(function (input) {
567 return execute({
568 cwd: input.cwd,
569 args: [
570 "repos",
571 "pr",
572 "create",
573 "--only-show-errors",
574 "--detect",
575 "true",
576 "--target-branch",
577 input.target?.refName ?? input.baseBranch,
578 "--source-branch",
579 SourceControlProvider.sourceBranch(input),
580 "--title",
581 input.title,
582 "--description",
583 `@${input.bodyFile}`,
584 ],
585 }).pipe(Effect.asVoid);
586 }),
587 getDefaultBranch: Effect.fn("AzureDevOpsCli.getDefaultBranch")(function (input) {
588 const repository = parseRepositorySpecifier(input.repository);
589 return executeJson({
590 cwd: input.cwd,
591 args: [
592 "repos",
593 "show",
594 "--detect",
595 "true",
596 // Joined so a name starting with `-` stays the option's value.
597 `--repository=${repository.name}`,
598 ...(repository.project ? ["--project", repository.project] : []),
599 ],
600 }).pipe(
601 Effect.map((result) => result.stdout.trim()),
602 Effect.flatMap((raw) =>
603 decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "getDefaultBranch", input.cwd),
604 ),
605 Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),
606 );
607 }),
608 });
609});
610
611export const layer = Layer.effect(AzureDevOpsCli, make);