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

AzureDevOpsCli.ts

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