Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AzureDevOpsCli.ts

778 lines26.4 KB

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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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;
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 /** The remote T3 selected; without one, the checkout's primary remote scopes the command. */
225 readonly remoteUrl?: string;
226 readonly stdin?: string;
227 }) => Effect.Effect<SourceControlHost.SourceControlProcessOutput, AzureDevOpsCliError>;
228​
229 readonly listPullRequests: (input: {
230 readonly cwd: string;
231 readonly headSelector: string;
232 readonly source?: SourceControlProvider.SourceControlRefSelector;
233 readonly state: "open" | "closed" | "merged" | "all";
234 readonly limit?: number;
235 readonly remoteUrl?: string;
236 }) => Effect.Effect<ReadonlyArray<NormalizedAzureDevOpsPullRequestRecord>, AzureDevOpsCliError>;
237​
238 readonly getPullRequest: (input: {
239 readonly cwd: string;
240 readonly reference: string;
241 readonly remoteUrl?: string;
242 }) => Effect.Effect<NormalizedAzureDevOpsPullRequestRecord, AzureDevOpsCliError>;
243​
244 readonly getRepositoryCloneUrls: (input: {
245 readonly cwd: string;
246 readonly repository: string;
247 readonly remoteUrl?: string;
248 }) => Effect.Effect<AzureDevOpsRepositoryCloneUrls, AzureDevOpsCliError>;
249​
250 readonly createRepository: (input: {
251 readonly cwd: string;
252 readonly repository: string;
253 readonly visibility: SourceControlRepositoryVisibility;
254 }) => Effect.Effect<AzureDevOpsRepositoryCloneUrls, AzureDevOpsCliError>;
255​
256 readonly createPullRequest: (input: {
257 readonly cwd: string;
258 readonly baseBranch: string;
259 readonly headSelector: string;
260 readonly source?: SourceControlProvider.SourceControlRefSelector;
261 readonly target?: SourceControlProvider.SourceControlRefSelector;
262 readonly title: string;
263 readonly bodyFile: string;
264 readonly remoteUrl?: string;
265 }) => Effect.Effect<void, AzureDevOpsCliError>;
266​
267 readonly getDefaultBranch: (input: {
268 readonly cwd: string;
269 readonly repository: string;
270 readonly remoteUrl?: string;
271 }) => Effect.Effect<string | null, AzureDevOpsCliError>;
272 }
273>()("@t3tools/source-control-azure-devops/server/AzureDevOpsCli") {}
274​
275function normalizeChangeRequestId(reference: string): string {
276 const trimmed = reference.trim().replace(/^#/, "");
277 const urlMatch = /(?:pullrequest|pull-request|pull|_pulls?)\/(\d+)(?:\D.*)?$/i.exec(trimmed);
278 return urlMatch?.[1] ?? trimmed;
280​
281function toAzureStatus(state: "open" | "closed" | "merged" | "all"): string {
282 switch (state) {
283 case "open":
284 return "active";
285 case "closed":
286 return "abandoned";
287 case "merged":
288 return "completed";
289 case "all":
290 return "all";
291 }
293​
294const RawAzureDevOpsRepositorySchema = Schema.Struct({
295 name: TrimmedNonEmptyString,
296 webUrl: TrimmedNonEmptyString,
297 remoteUrl: TrimmedNonEmptyString,
298 sshUrl: TrimmedNonEmptyString,
299 project: Schema.optional(
300 Schema.Struct({
301 name: TrimmedNonEmptyString,
302 }),
303 ),
304 defaultBranch: Schema.optional(Schema.NullOr(Schema.String)),
305});
306​
307function normalizeDefaultBranch(value: string | null | undefined): string | null {
308 const trimmed = value?.trim().replace(/^refs\/heads\//, "") ?? "";
309 return trimmed.length > 0 ? trimmed : null;
311​
312function normalizeRepositoryCloneUrls(
313 raw: Schema.Schema.Type<typeof RawAzureDevOpsRepositorySchema>,
314): AzureDevOpsRepositoryCloneUrls {
315 const projectName = raw.project?.name.trim();
316 return {
317 nameWithOwner: projectName ? `${projectName}/${raw.name}` : raw.name,
318 url: raw.remoteUrl,
319 sshUrl: raw.sshUrl,
320 };
322​
323function parseRepositorySpecifier(repository: string): {
324 readonly project: string | null;
325 readonly name: string;
326} {
327 const parts: Array<string> = [];
328 for (const part of repository.split("/")) {
329 const trimmed = part.trim();
330 if (trimmed.length > 0) {
331 parts.push(trimmed);
332 }
333 }
334 return {
335 project: parts.length > 1 ? (parts.at(-2) ?? null) : null,
336 name: parts.at(-1) ?? repository.trim(),
337 };
339​
340function decodeAzureDevOpsJson<S extends Schema.Top>(
341 raw: string,
342 schema: S,
343 operation: typeof AzureDevOpsRepositoryDecodeOperation.Type,
344 cwd: string,
345): Effect.Effect<S["Type"], AzureDevOpsRepositoryDecodeError, S["DecodingServices"]> {
346 return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
347 Effect.mapError(
348 (cause) =>
349 new AzureDevOpsRepositoryDecodeError({
350 operation,
351 command: "az",
352 cwd,
353 outputLength: raw.length,
354 cause,
355 }),
356 ),
357 );
359​
360/** The remote that scopes `az` when T3 selected none, from `git remote -v` output. */
361export function primaryRemoteUrl(output: string) {
362 if (!output.endsWith("\n")) return null;
363 const remotes = new Map<string, string>();
364 for (const line of output.split("\n")) {
365 const trimmed = line.trim();
366 if (trimmed.length === 0) continue;
367 const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/u.exec(trimmed);
368 if (!match?.[1] || !match[2]) return null;
369 if (match[3] === "fetch" && !remotes.has(match[1])) remotes.set(match[1], match[2]);
370 }
371 // Match the provider context SourceControlProviderRegistry binds, and `az`'s own detection.
372 return (
373 remotes.get("origin") ??
374 [...remotes.values()].find((url) => scopeFromRemoteUrl(url) !== null) ??
375 null
376 );
378​
379function scopeFromRemoteUrl(remote: string) {
380 try {
381 const scp = /^(?:[^@/]+@)?([^/:]+):(.+)$/u.exec(remote);
382 const url = new URL(
383 remote.includes("://") ? remote : scp ? `ssh://${scp[1]}/${scp[2]}` : remote,
384 );
385 if (url.search || url.hash) return null;
386 const legacy = url.hostname.endsWith(".visualstudio.com");
387 const parts = url.pathname.slice(1).split("/").map(decodeURIComponent);
388 let organization: string | undefined;
389 if (
390 url.protocol === "ssh:" &&
391 (url.hostname === "ssh.dev.azure.com" || url.hostname === "vs-ssh.visualstudio.com")
392 ) {
393 if (parts.length !== 4 || parts.shift() !== "v3") return null;
394 organization = parts.shift();
395 } else if (url.protocol === "https:") {
396 if (url.hostname === "dev.azure.com") organization = parts.shift();
397 else {
398 organization = /^([^.]+)\.visualstudio\.com$/u.exec(url.hostname)?.[1];
399 if (!organization) return null;
400 if (parts[0]?.toLowerCase() === "defaultcollection") parts.shift();
401 }
402 if (parts.length !== 3 || parts[1] !== "_git") return null;
403 parts.splice(1, 1);
404 } else return null;
405 const [project, repository] = parts;
406 if (!organization || !project || !repository) return null;
407 // `az` replaces a value starting with `@` by the contents of that local file.
408 if ([organization, project, repository].some((part) => /^@|[\p{Cc}/\\]/u.test(part))) {
409 return null;
410 }
411 if (legacy && !/^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/u.test(organization))
412 return null;
413 return {
414 // az keys organization-scoped credentials by the original host family.
415 organization: legacy
416 ? `https://${organization}.visualstudio.com`
417 : `https://dev.azure.com/${encodeURIComponent(organization)}`,
418 project,
419 repository,
420 };
421 } catch {
422 return null;
423 }
425​
426const remoteOf = (input: { readonly remoteUrl?: string }) =>
427 input.remoteUrl === undefined ? {} : { remoteUrl: input.remoteUrl };
428​
429const hasOption = (args: ReadonlyArray<string>, pattern: RegExp) =>
430 args.some((arg) => pattern.test(arg));
431​
432/** Whether `az` would run `--detect true`, which inspects the checkout from wherever `az` runs. */
433const detectsScope = (args: ReadonlyArray<string>) => {
434 const detect = args.indexOf("--detect");
435 return (
436 args[0] !== "account" &&
437 detect !== -1 &&
438 args[detect + 1] === "true" &&
439 !hasOption(args, /^(?:--organization|--org)(?:=|$)/u)
440 );
441};
442​
443/** Replaces `--detect true` with the scope of an Azure remote. */
444export function scopeAzureCliArgs(
445 args: ReadonlyArray<string>,
446 remoteUrl: string,
447): ReadonlyArray<string> {
448 const scope = detectsScope(args) ? scopeFromRemoteUrl(remoteUrl) : null;
449 if (!scope) return args;
450 const scoped = [...args, "--organization", scope.organization];
451 scoped[args.indexOf("--detect") + 1] = "false";
452 // PR-ID commands and devops invoke accept only organization scope.
453 const acceptsProject =
454 args[0] === "repos" &&
455 (args[1] === "show" ||
456 args[1] === "create" ||
457 (args[1] === "pr" && (args[2] === "list" || args[2] === "create")));
458 if (!acceptsProject) return scoped;
459 // Joined so a name starting with `-` stays the option's value.
460 if (!hasOption(args, /^(?:--project|-p)(?:=|$)/u)) scoped.push(`--project=${scope.project}`);
461 if (args[1] !== "create" && !hasOption(args, /^(?:--repository|-r)(?:=|$)/u)) {
462 scoped.push(`--repository=${scope.repository}`);
463 }
464 return scoped;
466​
467const classifyAzFailure = (stderr: string): VcsProcessExitFailureKind | null => {
468 const normalized = stderr.toLowerCase();
469 if (normalized.includes("az devops login") || /please run '?az login'?/.test(normalized)) {
470 return "authentication";
471 }
472 // Azure DevOps reports usage-limit throttling as TF400733, often without an HTTP status.
473 if (normalized.includes("tf400733")) return "rate-limited";
474 return normalized.includes("pull request") &&
475 (normalized.includes("not found") || normalized.includes("does not exist"))
476 ? "not-found"
477 : null;
478};
479​
480export interface AzureCliInvocation {
481 readonly command: string;
482 /** Arguments `az` needs before the caller's, to run the CLI in UTF-8 mode. */
483 readonly args: ReadonlyArray<string>;
484 readonly env?: NodeJS.ProcessEnv;
486​
487/**
488 * `-X utf8` is the only way in: the launcher's `-I` implies `-E`, so `PYTHONUTF8` and
489 * `PYTHONIOENCODING` are ignored, and the ANSI code page loses text `az` cannot encode.
490 * Resolved once when the service is built: installing `az` later needs a restart.
491 */
492export const azureCliInvocation = Effect.fn("AzureDevOpsCli.invocation")(function* () {
493 if ((yield* HostProcess.Platform) !== "win32") {
494 return { command: "az", args: [] } satisfies AzureCliInvocation;
495 }
496 const resolveExecutable = yield* SpawnExecutableResolution;
497 const launcher = resolveExecutable("az", "win32", yield* HostProcess.Environment);
498 const installFor = yield* AzureCliInstallLocation;
499 const install = launcher === undefined ? undefined : installFor(launcher);
500 // Unrecognized installs (pipx's Scripts\az.exe) keep the launcher and today's decode.
501 return install === undefined
502 ? ({ command: "az", args: [] } satisfies AzureCliInvocation)
503 : ({
504 command: install.interpreter,
505 args: ["-X", "utf8", "-IBm", "azure.cli"],
506 // What the launcher sets before running this same interpreter.
507 env: { AZ_INSTALLER: install.installer },
508 } satisfies AzureCliInvocation);
509});
510​
511/**
512 * `--option=value` for free text. az replaces a value starting with `@` by that file's
513 * contents; `@-` reads it from stdin instead, which reaches az wherever it runs (WSL included).
514 */
515export const textOption = (option: string, value: string) =>
516 value.startsWith("@")
517 ? { arg: `${option}=@-`, stdin: value }
518 : { arg: `${option}=${value}`, stdin: undefined };
519​
520/** @public */
521export const make = Effect.gen(function* () {
522 const { process } = yield* SourceControlHost.SourceControlHost;
523 const invocation = yield* azureCliInvocation();
524​
525 const execute: AzureDevOpsCli["Service"]["execute"] = Effect.fn("AzureDevOpsCli.execute")(
526 function* (input) {
527 let args = input.args;
528 if (detectsScope(args)) {
529 // Windows az running in WSL cannot inspect the server's Linux checkout.
530 const remoteUrl =
531 input.remoteUrl ??
532 (yield* process
533 .run({
534 operation: "AzureDevOpsCli.resolveScope",
535 command: "git",
536 args: ["remote", "-v"],
537 cwd: input.cwd,
538 env: {
539 GIT_DIR: undefined,
540 GIT_WORK_TREE: undefined,
541 GIT_COMMON_DIR: undefined,
542 GIT_INDEX_FILE: undefined,
543 GIT_OBJECT_DIRECTORY: undefined,
544 GIT_ALTERNATE_OBJECT_DIRECTORIES: undefined,
545 },
546 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
547 maxOutputBytes: 64 * 1024,
548 allowNonZeroExit: true,
549 })
550 .pipe(
551 Effect.map((remotes) =>
552 remotes.exitCode === 0 && !remotes.stdoutTruncated && !remotes.stdoutInvalidUtf8
553 ? primaryRemoteUrl(remotes.stdout)
554 : null,
555 ),
556 Effect.orElseSucceed(() => null),
557 ));
558 if (remoteUrl !== null) args = scopeAzureCliArgs(args, remoteUrl);
559 }
560 return yield* process
561 .run({
562 operation: "AzureDevOpsCli.execute",
563 command: invocation.command,
564 args: [...invocation.args, ...args],
565 cwd: input.cwd,
566 ...(invocation.env === undefined ? {} : { env: invocation.env }),
567 ...(input.stdin === undefined ? {} : { stdin: input.stdin }),
568 classifyFailure: classifyAzFailure,
569 notFoundDetail: "Pull request not found.",
570 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
571 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
572 })
573 .pipe(
574 Effect.mapError((error) =>
575 AzureDevOpsCommandFailedError.fromVcsError(
576 {
577 operation: "execute",
578 command: "az",
579 cwd: input.cwd,
580 argumentCount: input.args.length,
581 },
582 error,
583 ),
584 ),
585 );
586 },
587 );
588​
589 const executeJson = (input: Parameters<AzureDevOpsCli["Service"]["execute"]>[0]) =>
590 execute({
591 ...input,
592 args: [...input.args, "--only-show-errors", "--output", "json"],
593 });
594​
595 return AzureDevOpsCli.of({
596 execute,
597 listPullRequests: Effect.fn("AzureDevOpsCli.listPullRequests")(function (input) {
598 const branch = SourceControlProvider.sourceBranch(input);
599 // az checks literal ref prefixes before constructing the request URL.
600 const refPrefix =
601 ["refs/heads/", "refs/pull/", "refs/tags/"].find((prefix) => branch.startsWith(prefix)) ??
602 "";
603 return executeJson({
604 cwd: input.cwd,
605 ...remoteOf(input),
606 args: [
607 "repos",
608 "pr",
609 "list",
610 "--detect",
611 "true",
612 "--source-branch",
613 // az puts this in the query string unescaped; a `#` would cut the request.
614 refPrefix + encodeURIComponent(branch.slice(refPrefix.length)),
615 "--status",
616 toAzureStatus(input.state),
617 "--top",
618 String(input.limit ?? 20),
619 ],
620 }).pipe(
621 Effect.map((result) => result.stdout.trim()),
622 Effect.flatMap((raw) =>
623 raw.length === 0
624 ? Effect.succeed([])
625 : Effect.sync(() => decodeAzureDevOpsPullRequestListJson(raw)).pipe(
626 Effect.flatMap((decoded) => {
627 if (!Result.isSuccess(decoded)) {
628 return Effect.fail(
629 new AzureDevOpsPullRequestListDecodeError({
630 operation: "listPullRequests",
631 command: "az",
632 cwd: input.cwd,
633 outputLength: raw.length,
634 cause: decoded.failure,
635 }),
636 );
637 }
638​
639 return Effect.succeed(decoded.success);
640 }),
641 ),
642 ),
643 );
644 }),
645 getPullRequest: Effect.fn("AzureDevOpsCli.getPullRequest")(function (input) {
646 return executeJson({
647 cwd: input.cwd,
648 ...remoteOf(input),
649 args: [
650 "repos",
651 "pr",
652 "show",
653 "--detect",
654 "true",
655 "--id",
656 normalizeChangeRequestId(input.reference),
657 ],
658 }).pipe(
659 Effect.map((result) => result.stdout.trim()),
660 Effect.flatMap((raw) =>
661 Effect.sync(() => decodeAzureDevOpsPullRequestJson(raw)).pipe(
662 Effect.flatMap((decoded) => {
663 if (!Result.isSuccess(decoded)) {
664 return Effect.fail(
665 new AzureDevOpsPullRequestDecodeError({
666 operation: "getPullRequest",
667 command: "az",
668 cwd: input.cwd,
669 outputLength: raw.length,
670 cause: decoded.failure,
671 }),
672 );
673 }
674​
675 return Effect.succeed(decoded.success);
676 }),
677 ),
678 ),
679 );
680 }),
681 getRepositoryCloneUrls: Effect.fn("AzureDevOpsCli.getRepositoryCloneUrls")(function (input) {
682 const repository = parseRepositorySpecifier(input.repository);
683 return executeJson({
684 cwd: input.cwd,
685 ...remoteOf(input),
686 args: [
687 "repos",
688 "show",
689 "--detect",
690 "true",
691 "--repository",
692 repository.name,
693 ...(repository.project ? ["--project", repository.project] : []),
694 ],
695 }).pipe(
696 Effect.map((result) => result.stdout.trim()),
697 Effect.flatMap((raw) =>
698 decodeAzureDevOpsJson(
699 raw,
700 RawAzureDevOpsRepositorySchema,
701 "getRepositoryCloneUrls",
702 input.cwd,
703 ),
704 ),
705 Effect.map(normalizeRepositoryCloneUrls),
706 );
707 }),
708 createRepository: Effect.fn("AzureDevOpsCli.createRepository")(function (input) {
709 const repository = parseRepositorySpecifier(input.repository);
710 // Project/organization permissions control visibility; `az repos create` has no flag.
711 return executeJson({
712 cwd: input.cwd,
713 args: [
714 "repos",
715 "create",
716 "--detect",
717 "true",
718 "--name",
719 repository.name,
720 ...(repository.project ? ["--project", repository.project] : []),
721 ],
722 }).pipe(
723 Effect.map((result) => result.stdout.trim()),
724 Effect.flatMap((raw) =>
725 decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "createRepository", input.cwd),
726 ),
727 Effect.map(normalizeRepositoryCloneUrls),
728 );
729 }),
730 createPullRequest: Effect.fn("AzureDevOpsCli.createPullRequest")(function (input) {
731 // A full ref keeps a branch named `@...` from reading as a file; az accepts either form.
732 const branch = (name: string) => (name.startsWith("@") ? `refs/heads/${name}` : name);
733 const title = textOption("--title", input.title);
734 return execute({
735 cwd: input.cwd,
736 ...remoteOf(input),
737 args: [
738 "repos",
739 "pr",
740 "create",
741 "--only-show-errors",
742 "--detect",
743 "true",
744 `--target-branch=${branch(input.target?.refName ?? input.baseBranch)}`,
745 `--source-branch=${branch(SourceControlProvider.sourceBranch(input))}`,
746 title.arg,
747 // Joined: az expands a separate `@file` value again, so a body of `@path` read that file.
748 `--description=@${input.bodyFile}`,
749 ],
750 ...(title.stdin === undefined ? {} : { stdin: title.stdin }),
751 }).pipe(Effect.asVoid);
752 }),
753 getDefaultBranch: Effect.fn("AzureDevOpsCli.getDefaultBranch")(function (input) {
754 const repository = parseRepositorySpecifier(input.repository);
755 return executeJson({
756 cwd: input.cwd,
757 ...remoteOf(input),
758 args: [
759 "repos",
760 "show",
761 "--detect",
762 "true",
763 // Joined so a name starting with `-` stays the option's value.
764 `--repository=${repository.name}`,
765 ...(repository.project ? ["--project", repository.project] : []),
766 ],
767 }).pipe(
768 Effect.map((result) => result.stdout.trim()),
769 Effect.flatMap((raw) =>
770 decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "getDefaultBranch", input.cwd),
771 ),
772 Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),
773 );
774 }),
775 });
776});
777​
778export const layer = Layer.effect(AzureDevOpsCli, make);