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

AzureDevOpsCli.ts

807 lines28.9 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 trimAsciiWhitespace,
11 type SourceControlRepositoryVisibility,
12 type VcsError,
13 type VcsProcessExitFailureKind,
14} from "@t3tools/contracts";
15​
16import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
17import * as HostProcess from "@t3tools/shared/HostProcess";
18import { SpawnExecutableResolution } from "@t3tools/shared/shell";
19import { AzureCliInstallLocation } from "./azureCliLauncher.ts";
20import {
21 decodeAzureDevOpsPullRequestJson,
22 decodeAzureDevOpsPullRequestListJson,
23 type NormalizedAzureDevOpsPullRequestRecord,
24} from "./azureDevOpsPullRequests.ts";
25import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
26​
27// Endpoint security that scans each of the ~800 files az opens can make it take a minute to start.
28export const AZ_TIMEOUT_MS = 120_000;
29​
30const azureDevOpsCommandErrorFields = {
31 operation: Schema.Literal("execute"),
32 command: Schema.Literal("az"),
33 cwd: Schema.String,
34 argumentCount: NonNegativeInt,
35 cause: Schema.Defect(),
36};
37​
38export class AzureDevOpsCliUnavailableError extends Schema.TaggedError<AzureDevOpsCliUnavailableError>()(
39 "AzureDevOpsCliUnavailableError",
40 azureDevOpsCommandErrorFields,
41) {
42 get detail(): string {
43 return "Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.";
44 }
45​
46 override get message(): string {
47 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
48 }
50​
51export class AzureDevOpsCliAuthenticationError extends Schema.TaggedError<AzureDevOpsCliAuthenticationError>()(
52 "AzureDevOpsCliAuthenticationError",
53 azureDevOpsCommandErrorFields,
54) {
55 get detail(): string {
56 return "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.";
57 }
58​
59 override get message(): string {
60 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
61 }
63​
64export class AzureDevOpsCliRateLimitError extends Schema.TaggedError<AzureDevOpsCliRateLimitError>()(
65 "AzureDevOpsCliRateLimitError",
66 azureDevOpsCommandErrorFields,
67) {
68 get detail(): string {
69 return "Azure DevOps API rate limit exceeded.";
70 }
71​
72 override get message(): string {
73 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
74 }
76​
77export class AzureDevOpsPullRequestNotFoundError extends Schema.TaggedError<AzureDevOpsPullRequestNotFoundError>()(
78 "AzureDevOpsPullRequestNotFoundError",
79 // No cause when the reference holds no pull request number and az never runs.
80 { ...azureDevOpsCommandErrorFields, cause: Schema.optional(Schema.Defect()) },
81) {
82 get detail(): string {
83 return "Pull request not found. Check the PR number or URL and try again.";
84 }
85​
86 override get message(): string {
87 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
88 }
90​
91export class AzureDevOpsCommandFailedError extends Schema.TaggedError<AzureDevOpsCommandFailedError>()(
92 "AzureDevOpsCommandFailedError",
93 azureDevOpsCommandErrorFields,
94) {
95 get detail(): string {
96 return "Azure DevOps CLI command failed.";
97 }
98​
99 override get message(): string {
100 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
101 }
102​
103 static fromVcsError(
104 context: {
105 readonly operation: "execute";
106 readonly command: "az";
107 readonly cwd: string;
108 readonly argumentCount: number;
109 },
110 cause: VcsError,
111 ): AzureDevOpsCliError {
112 const fields = { ...context, cause };
113​
114 if (
115 cause._tag === "VcsProcessSpawnError" &&
116 cause.cause instanceof PlatformError.PlatformError &&
117 cause.cause.reason._tag === "NotFound" &&
118 cause.cause.reason.pathOrDescriptor !== context.cwd &&
119 cause.cause.reason.syscall !== "chdir"
120 ) {
121 return new AzureDevOpsCliUnavailableError(fields);
122 }
123​
124 if (cause._tag === "VcsProcessExitError") {
125 if (cause.failureKind === "authentication") {
126 return new AzureDevOpsCliAuthenticationError(fields);
127 }
128 if (cause.failureKind === "rate-limited") {
129 return new AzureDevOpsCliRateLimitError(fields);
130 }
131 if (cause.failureKind === "not-found") {
132 return new AzureDevOpsPullRequestNotFoundError(fields);
133 }
134 }
135​
136 return new AzureDevOpsCommandFailedError(fields);
137 }
139​
140const azureDevOpsDecodeErrorFields = {
141 command: Schema.Literal("az"),
142 cwd: Schema.String,
143 outputLength: NonNegativeInt,
144 cause: Schema.Defect(),
145};
146​
147export class AzureDevOpsPullRequestListDecodeError extends Schema.TaggedError<AzureDevOpsPullRequestListDecodeError>()(
148 "AzureDevOpsPullRequestListDecodeError",
149 {
150 operation: Schema.Literal("listPullRequests"),
151 ...azureDevOpsDecodeErrorFields,
152 },
153) {
154 get detail(): string {
155 return "Azure DevOps CLI returned invalid PR list JSON.";
156 }
157​
158 override get message(): string {
159 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
160 }
162​
163export class AzureDevOpsPullRequestDecodeError extends Schema.TaggedError<AzureDevOpsPullRequestDecodeError>()(
164 "AzureDevOpsPullRequestDecodeError",
165 {
166 operation: Schema.Literal("getPullRequest"),
167 ...azureDevOpsDecodeErrorFields,
168 },
169) {
170 get detail(): string {
171 return "Azure DevOps CLI returned invalid pull request JSON.";
172 }
173​
174 override get message(): string {
175 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
176 }
178​
179const AzureDevOpsRepositoryDecodeOperation = Schema.Literals([
180 "getRepositoryCloneUrls",
181 "getDefaultBranch",
182 "createRepository",
183]);
184​
185export class AzureDevOpsRepositoryDecodeError extends Schema.TaggedError<AzureDevOpsRepositoryDecodeError>()(
186 "AzureDevOpsRepositoryDecodeError",
187 {
188 operation: AzureDevOpsRepositoryDecodeOperation,
189 ...azureDevOpsDecodeErrorFields,
190 },
191) {
192 get detail(): string {
193 return "Azure DevOps CLI returned invalid repository JSON.";
194 }
195​
196 override get message(): string {
197 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
198 }
200​
201export const AzureDevOpsCliError = Schema.Union([
202 AzureDevOpsCliUnavailableError,
203 AzureDevOpsCliAuthenticationError,
204 AzureDevOpsCliRateLimitError,
205 AzureDevOpsPullRequestNotFoundError,
206 AzureDevOpsCommandFailedError,
207 AzureDevOpsPullRequestListDecodeError,
208 AzureDevOpsPullRequestDecodeError,
209 AzureDevOpsRepositoryDecodeError,
210]);
211export type AzureDevOpsCliError = typeof AzureDevOpsCliError.Type;
212​
213export interface AzureDevOpsRepositoryCloneUrls {
214 readonly nameWithOwner: string;
215 readonly url: string;
216 readonly sshUrl: string;
218​
219export class AzureDevOpsCli extends Context.Service<
220 AzureDevOpsCli,
221 {
222 readonly execute: (input: {
223 readonly cwd: string;
224 readonly args: ReadonlyArray<string>;
225 readonly timeoutMs?: number;
226 readonly maxOutputBytes?: number;
227 /** The remote T3 selected; without one, the checkout's primary remote scopes the command. */
228 readonly remoteUrl?: string;
229 readonly stdin?: string;
230 }) => Effect.Effect<SourceControlHost.SourceControlProcessOutput, AzureDevOpsCliError>;
231​
232 readonly listPullRequests: (input: {
233 readonly cwd: string;
234 readonly headSelector: string;
235 readonly source?: SourceControlProvider.SourceControlRefSelector;
236 readonly state: "open" | "closed" | "merged" | "all";
237 readonly limit?: number;
238 readonly remoteUrl?: string;
239 }) => Effect.Effect<ReadonlyArray<NormalizedAzureDevOpsPullRequestRecord>, AzureDevOpsCliError>;
240​
241 readonly getPullRequest: (input: {
242 readonly cwd: string;
243 readonly reference: string;
244 readonly remoteUrl?: string;
245 }) => Effect.Effect<NormalizedAzureDevOpsPullRequestRecord, AzureDevOpsCliError>;
246​
247 readonly getRepositoryCloneUrls: (input: {
248 readonly cwd: string;
249 readonly repository: string;
250 readonly remoteUrl?: string;
251 }) => Effect.Effect<AzureDevOpsRepositoryCloneUrls, AzureDevOpsCliError>;
252​
253 readonly createRepository: (input: {
254 readonly cwd: string;
255 readonly repository: string;
256 readonly visibility: SourceControlRepositoryVisibility;
257 }) => Effect.Effect<AzureDevOpsRepositoryCloneUrls, AzureDevOpsCliError>;
258​
259 readonly createPullRequest: (input: {
260 readonly cwd: string;
261 readonly baseBranch: string;
262 readonly headSelector: string;
263 readonly source?: SourceControlProvider.SourceControlRefSelector;
264 readonly target?: SourceControlProvider.SourceControlRefSelector;
265 readonly title: string;
266 readonly bodyFile: string;
267 readonly draft?: boolean;
268 readonly remoteUrl?: string;
269 }) => Effect.Effect<void, AzureDevOpsCliError>;
270​
271 readonly getDefaultBranch: (input: {
272 readonly cwd: string;
273 readonly repository: string;
274 readonly remoteUrl?: string;
275 }) => Effect.Effect<string | null, AzureDevOpsCliError>;
276 }
277>()("@t3tools/source-control-azure-devops/server/AzureDevOpsCli") {}
278​
279/** The pull request number in `42`, `#42` or a pull request URL. */
280function normalizeChangeRequestId(reference: string): string | null {
281 const trimmed = reference.trim().replace(/^#/, "");
282 const urlMatch = /(?:pullrequest|pull-request|pull|_pulls?)\/(\d+)(?:\D.*)?$/i.exec(trimmed);
283 const id = urlMatch?.[1] ?? trimmed;
284 return /^\d+$/.test(id) ? id : null;
286​
287function toAzureStatus(state: "open" | "closed" | "merged" | "all"): string {
288 switch (state) {
289 case "open":
290 return "active";
291 case "closed":
292 return "abandoned";
293 case "merged":
294 return "completed";
295 case "all":
296 return "all";
297 }
299​
300const RawAzureDevOpsRepositorySchema = Schema.Struct({
301 name: TrimmedNonEmptyString,
302 webUrl: TrimmedNonEmptyString,
303 remoteUrl: TrimmedNonEmptyString,
304 sshUrl: TrimmedNonEmptyString,
305 project: Schema.optional(
306 Schema.Struct({
307 name: TrimmedNonEmptyString,
308 }),
309 ),
310 defaultBranch: Schema.optional(Schema.NullOr(Schema.String)),
311});
312​
313const RawAzureDevOpsProjectSchema = Schema.Struct({
314 id: Schema.String.check(Schema.isPattern(/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i)),
315});
316​
317function normalizeDefaultBranch(value: string | null | undefined): string | null {
318 const trimmed = trimAsciiWhitespace(value ?? "").replace(/^refs\/heads\//, "");
319 return trimmed.length > 0 ? trimmed : null;
321​
322function normalizeRepositoryCloneUrls(
323 raw: Schema.Schema.Type<typeof RawAzureDevOpsRepositorySchema>,
324): AzureDevOpsRepositoryCloneUrls {
325 const projectName = raw.project?.name.trim();
326 return {
327 nameWithOwner: projectName ? `${projectName}/${raw.name}` : raw.name,
328 url: raw.remoteUrl,
329 sshUrl: raw.sshUrl,
330 };
332​
333function parseRepositorySpecifier(repository: string): {
334 readonly project: string | null;
335 readonly name: string;
336} {
337 const parts: Array<string> = [];
338 for (const part of repository.split("/")) {
339 const trimmed = part.trim();
340 if (trimmed.length > 0) {
341 parts.push(trimmed);
342 }
343 }
344 return {
345 project: parts.length > 1 ? (parts.at(-2) ?? null) : null,
346 name: parts.at(-1) ?? repository.trim(),
347 };
349​
350function decodeAzureDevOpsJson<S extends Schema.Top>(
351 raw: string,
352 schema: S,
353 operation: typeof AzureDevOpsRepositoryDecodeOperation.Type,
354 cwd: string,
355): Effect.Effect<S["Type"], AzureDevOpsRepositoryDecodeError, S["DecodingServices"]> {
356 return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
357 Effect.mapError(
358 (cause) =>
359 new AzureDevOpsRepositoryDecodeError({
360 operation,
361 command: "az",
362 cwd,
363 outputLength: raw.length,
364 cause,
365 }),
366 ),
367 );
369​
370/** The remote that scopes `az` when T3 selected none, from `git remote -v` output. */
371export function primaryRemoteUrl(output: string) {
372 if (!output.endsWith("\n")) return null;
373 const remotes = new Map<string, string>();
374 for (const line of output.split("\n")) {
375 const trimmed = line.trim();
376 if (trimmed.length === 0) continue;
377 // Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`.
378 const match = /^(\S+)\t(\S+(?: +\S+)*?) \((fetch|push)\)(?: \[[^[\]]+\])?$/u.exec(trimmed);
379 if (!match?.[1] || !match[2]) return null;
380 if (match[3] === "fetch" && !remotes.has(match[1])) remotes.set(match[1], match[2]);
381 }
382 // Match the provider context SourceControlProviderRegistry binds, and `az`'s own detection.
383 return (
384 remotes.get("origin") ??
385 [...remotes.values()].find((url) => scopeFromRemoteUrl(url) !== null) ??
386 null
387 );
389​
390function scopeFromRemoteUrl(remote: string) {
391 try {
392 const scp = /^(?:[^@/]+@)?([^/:]+):(.+)$/u.exec(remote);
393 const url = new URL(
394 remote.includes("://") ? remote : scp ? `ssh://${scp[1]}/${scp[2]}` : remote,
395 );
396 if (url.search || url.hash) return null;
397 const legacy = url.hostname.endsWith(".visualstudio.com");
398 const parts = url.pathname.slice(1).replace(/\/+$/u, "").split("/").map(decodeURIComponent);
399 let organization: string | undefined;
400 if (
401 url.protocol === "ssh:" &&
402 (url.hostname === "ssh.dev.azure.com" || url.hostname === "vs-ssh.visualstudio.com")
403 ) {
404 if (parts.length !== 4 || parts.shift() !== "v3") return null;
405 organization = parts.shift();
406 } else if (url.protocol === "https:") {
407 if (url.hostname === "dev.azure.com") organization = parts.shift();
408 else {
409 organization = /^([^.]+)\.visualstudio\.com$/u.exec(url.hostname)?.[1];
410 if (!organization) return null;
411 if (parts[0]?.toLowerCase() === "defaultcollection") parts.shift();
412 }
413 if (parts.length === 2 && parts[0] === "_git" && parts[1]) parts.unshift(parts[1]);
414 if (parts.length !== 3 || parts[1] !== "_git") return null;
415 parts.splice(1, 1);
416 } else return null;
417 const [project, repository] = parts;
418 if (!organization || !project || !repository) return null;
419 // `az` replaces a value starting with `@` by the contents of that local file.
420 if ([organization, project, repository].some((part) => /^@|[\p{Cc}/\\]/u.test(part))) {
421 return null;
422 }
423 if (legacy && !/^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/u.test(organization))
424 return null;
425 return {
426 // az keys organization-scoped credentials by the original host family.
427 organization: legacy
428 ? `https://${organization}.visualstudio.com`
429 : `https://dev.azure.com/${encodeURIComponent(organization)}`,
430 project,
431 repository,
432 };
433 } catch {
434 return null;
435 }
437​
438const remoteOf = (input: { readonly remoteUrl?: string }) =>
439 input.remoteUrl === undefined ? {} : { remoteUrl: input.remoteUrl };
440​
441const hasOption = (args: ReadonlyArray<string>, pattern: RegExp) =>
442 args.some((arg) => pattern.test(arg));
443​
444/** Whether `az` would run `--detect true`, which inspects the checkout from wherever `az` runs. */
445const detectsScope = (args: ReadonlyArray<string>) => {
446 const detect = args.indexOf("--detect");
447 return (
448 args[0] !== "account" &&
449 detect !== -1 &&
450 args[detect + 1] === "true" &&
451 !hasOption(args, /^(?:--organization|--org)(?:=|$)/u)
452 );
453};
454​
455/** Replaces `--detect true` with the scope of an Azure remote. */
456export function scopeAzureCliArgs(
457 args: ReadonlyArray<string>,
458 remoteUrl: string,
459): ReadonlyArray<string> {
460 const scope = detectsScope(args) ? scopeFromRemoteUrl(remoteUrl) : null;
461 if (!scope) return args;
462 const scoped = [...args, "--organization", scope.organization];
463 scoped[args.indexOf("--detect") + 1] = "false";
464 // PR-ID commands and devops invoke accept only organization scope.
465 const acceptsProject =
466 args[0] === "repos" &&
467 (args[1] === "show" ||
468 args[1] === "create" ||
469 (args[1] === "pr" && (args[2] === "list" || args[2] === "create")));
470 if (!acceptsProject) return scoped;
471 // Joined so a name starting with `-` stays the option's value.
472 if (!hasOption(args, /^(?:--project|-p)(?:=|$)/u)) scoped.push(`--project=${scope.project}`);
473 if (args[1] !== "create" && !hasOption(args, /^(?:--repository|-r)(?:=|$)/u)) {
474 scoped.push(`--repository=${scope.repository}`);
475 }
476 return scoped;
478​
479const classifyAzFailure = (stderr: string): VcsProcessExitFailureKind | null => {
480 const normalized = stderr.toLowerCase();
481 if (normalized.includes("az devops login") || /please run '?az login'?/.test(normalized)) {
482 return "authentication";
483 }
484 // Azure DevOps reports usage-limit throttling as TF400733, often without an HTTP status.
485 if (normalized.includes("tf400733")) return "rate-limited";
486 return normalized.includes("pull request") &&
487 (normalized.includes("not found") || normalized.includes("does not exist"))
488 ? "not-found"
489 : null;
490};
491​
492export interface AzureCliInvocation {
493 readonly command: string;
494 /** Arguments `az` needs before the caller's, to run the CLI in UTF-8 mode. */
495 readonly args: ReadonlyArray<string>;
496 readonly env?: NodeJS.ProcessEnv;
498​
499/**
500 * `-X utf8` is the only way in: the launcher's `-I` implies `-E`, so `PYTHONUTF8` and
501 * `PYTHONIOENCODING` are ignored, and the ANSI code page loses text `az` cannot encode.
502 * Resolved once when the service is built: installing `az` later needs a restart.
503 */
504export const azureCliInvocation = Effect.fn("AzureDevOpsCli.invocation")(function* () {
505 if ((yield* HostProcess.Platform) !== "win32") {
506 return { command: "az", args: [] } satisfies AzureCliInvocation;
507 }
508 const resolveExecutable = yield* SpawnExecutableResolution;
509 const env = yield* HostProcess.Environment;
510 const launcher = yield* Effect.promise(async () => resolveExecutable("az", "win32", env));
511 const installFor = yield* AzureCliInstallLocation;
512 const install = launcher === undefined ? undefined : installFor(launcher);
513 // Unrecognized installs (pipx's Scripts\az.exe) keep the launcher and today's decode.
514 return install === undefined
515 ? ({ command: "az", args: [] } satisfies AzureCliInvocation)
516 : ({
517 command: install.interpreter,
518 args: ["-X", "utf8", "-IBm", "azure.cli"],
519 // What the launcher sets before running this same interpreter.
520 env: { AZ_INSTALLER: install.installer },
521 } satisfies AzureCliInvocation);
522});
523​
524/**
525 * `--option=value` for free text. az replaces a value starting with `@` by that file's
526 * contents; `@-` reads it from stdin instead, which reaches az wherever it runs (WSL included).
527 */
528export const textOption = (option: string, value: string) =>
529 value.startsWith("@")
530 ? { arg: `${option}=@-`, stdin: value }
531 : { arg: `${option}=${value}`, stdin: undefined };
532​
533/** @public */
534export const make = Effect.gen(function* () {
535 const { process } = yield* SourceControlHost.SourceControlHost;
536 const invocation = yield* azureCliInvocation();
537​
538 const execute: AzureDevOpsCli["Service"]["execute"] = Effect.fn("AzureDevOpsCli.execute")(
539 function* (input) {
540 let args = input.args;
541 if (detectsScope(args)) {
542 // Windows az running in WSL cannot inspect the server's Linux checkout.
543 const remoteUrl =
544 input.remoteUrl ??
545 (yield* process
546 .run({
547 operation: "AzureDevOpsCli.resolveScope",
548 command: "git",
549 args: ["remote", "-v"],
550 cwd: input.cwd,
551 env: {
552 GIT_DIR: undefined,
553 GIT_WORK_TREE: undefined,
554 GIT_COMMON_DIR: undefined,
555 GIT_INDEX_FILE: undefined,
556 GIT_OBJECT_DIRECTORY: undefined,
557 GIT_ALTERNATE_OBJECT_DIRECTORIES: undefined,
558 },
559 timeoutMs: input.timeoutMs ?? AZ_TIMEOUT_MS,
560 maxOutputBytes: 64 * 1024,
561 allowNonZeroExit: true,
562 })
563 .pipe(
564 Effect.map((remotes) =>
565 remotes.exitCode === 0 && !remotes.stdoutTruncated && !remotes.stdoutInvalidUtf8
566 ? primaryRemoteUrl(remotes.stdout)
567 : null,
568 ),
569 Effect.orElseSucceed(() => null),
570 ));
571 if (remoteUrl !== null) args = scopeAzureCliArgs(args, remoteUrl);
572 }
573 return yield* process
574 .run({
575 operation: "AzureDevOpsCli.execute",
576 command: invocation.command,
577 args: [...invocation.args, ...args],
578 cwd: input.cwd,
579 ...(invocation.env === undefined ? {} : { env: invocation.env }),
580 ...(input.stdin === undefined ? {} : { stdin: input.stdin }),
581 classifyFailure: classifyAzFailure,
582 notFoundDetail: "Pull request not found.",
583 timeoutMs: input.timeoutMs ?? AZ_TIMEOUT_MS,
584 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
585 })
586 .pipe(
587 Effect.mapError((error) =>
588 AzureDevOpsCommandFailedError.fromVcsError(
589 {
590 operation: "execute",
591 command: "az",
592 cwd: input.cwd,
593 argumentCount: input.args.length,
594 },
595 error,
596 ),
597 ),
598 );
599 },
600 );
601​
602 const executeJson = (input: Parameters<AzureDevOpsCli["Service"]["execute"]>[0]) =>
603 execute({
604 ...input,
605 args: [...input.args, "--only-show-errors", "--output", "json"],
606 });
607​
608 /** The options naming a `project/name` repository, each a `textOption` so neither reads a file. */
609 const repositoryOptions = Effect.fn("AzureDevOpsCli.repositoryOptions")(function* (
610 input: { readonly cwd: string; readonly repository: string; readonly remoteUrl?: string },
611 nameOption: "--repository" | "--name",
612 operation: typeof AzureDevOpsRepositoryDecodeOperation.Type,
613 ) {
614 const repository = parseRepositorySpecifier(input.repository);
615 const name = textOption(nameOption, repository.name);
616 if (repository.project === null) return { args: [name.arg], stdin: name.stdin };
617 const project = textOption("--project", repository.project);
618 if (name.stdin === undefined || project.stdin === undefined) {
619 return { args: [name.arg, project.arg], stdin: name.stdin ?? project.stdin };
620 }
621 // az has one stdin, so the project is read in a call of its own and named by its ID here.
622 const { id } = yield* executeJson({
623 cwd: input.cwd,
624 ...remoteOf(input),
625 args: ["devops", "project", "show", "--detect", "true", project.arg],
626 stdin: project.stdin,
627 }).pipe(
628 Effect.flatMap((result) =>
629 decodeAzureDevOpsJson(
630 result.stdout.trim(),
631 RawAzureDevOpsProjectSchema,
632 operation,
633 input.cwd,
634 ),
635 ),
636 );
637 return { args: [name.arg, `--project=${id}`], stdin: name.stdin };
638 });
639​
640 return AzureDevOpsCli.of({
641 execute,
642 listPullRequests: Effect.fn("AzureDevOpsCli.listPullRequests")(function (input) {
643 const branch = SourceControlProvider.sourceBranch(input);
644 // az checks literal ref prefixes before constructing the request URL.
645 const refPrefix =
646 ["refs/heads/", "refs/pull/", "refs/tags/"].find((prefix) => branch.startsWith(prefix)) ??
647 "";
648 return executeJson({
649 cwd: input.cwd,
650 ...remoteOf(input),
651 args: [
652 "repos",
653 "pr",
654 "list",
655 "--detect",
656 "true",
657 // az puts this in the query string unescaped; a `#` would cut the request. Encoding
658 // also turns a leading `@` into `%40`; joined so a leading `-` stays the value.
659 `--source-branch=${refPrefix + encodeURIComponent(branch.slice(refPrefix.length))}`,
660 "--status",
661 toAzureStatus(input.state),
662 "--top",
663 String(input.limit ?? 20),
664 ],
665 }).pipe(
666 Effect.map((result) => result.stdout.trim()),
667 Effect.flatMap((raw) =>
668 raw.length === 0
669 ? Effect.succeed([])
670 : Effect.sync(() => decodeAzureDevOpsPullRequestListJson(raw)).pipe(
671 Effect.flatMap((decoded) => {
672 if (!Result.isSuccess(decoded)) {
673 return Effect.fail(
674 new AzureDevOpsPullRequestListDecodeError({
675 operation: "listPullRequests",
676 command: "az",
677 cwd: input.cwd,
678 outputLength: raw.length,
679 cause: decoded.failure,
680 }),
681 );
682 }
683​
684 return Effect.succeed(decoded.success);
685 }),
686 ),
687 ),
688 );
689 }),
690 getPullRequest: Effect.fn("AzureDevOpsCli.getPullRequest")(function (input) {
691 const id = normalizeChangeRequestId(input.reference);
692 if (id === null) {
693 // az takes only a number here, and would read `@path` as a file and `-x` as an option.
694 return Effect.fail(
695 new AzureDevOpsPullRequestNotFoundError({
696 operation: "execute",
697 command: "az",
698 cwd: input.cwd,
699 argumentCount: 0,
700 }),
701 );
702 }
703 return executeJson({
704 cwd: input.cwd,
705 ...remoteOf(input),
706 args: ["repos", "pr", "show", "--detect", "true", "--id", id],
707 }).pipe(
708 Effect.map((result) => result.stdout.trim()),
709 Effect.flatMap((raw) =>
710 Effect.sync(() => decodeAzureDevOpsPullRequestJson(raw)).pipe(
711 Effect.flatMap((decoded) => {
712 if (!Result.isSuccess(decoded)) {
713 return Effect.fail(
714 new AzureDevOpsPullRequestDecodeError({
715 operation: "getPullRequest",
716 command: "az",
717 cwd: input.cwd,
718 outputLength: raw.length,
719 cause: decoded.failure,
720 }),
721 );
722 }
723​
724 return Effect.succeed(decoded.success);
725 }),
726 ),
727 ),
728 );
729 }),
730 getRepositoryCloneUrls: Effect.fn("AzureDevOpsCli.getRepositoryCloneUrls")(function* (input) {
731 const repository = yield* repositoryOptions(input, "--repository", "getRepositoryCloneUrls");
732 return yield* executeJson({
733 cwd: input.cwd,
734 ...remoteOf(input),
735 args: ["repos", "show", "--detect", "true", ...repository.args],
736 ...(repository.stdin === undefined ? {} : { stdin: repository.stdin }),
737 }).pipe(
738 Effect.map((result) => result.stdout.trim()),
739 Effect.flatMap((raw) =>
740 decodeAzureDevOpsJson(
741 raw,
742 RawAzureDevOpsRepositorySchema,
743 "getRepositoryCloneUrls",
744 input.cwd,
745 ),
746 ),
747 Effect.map(normalizeRepositoryCloneUrls),
748 );
749 }),
750 createRepository: Effect.fn("AzureDevOpsCli.createRepository")(function* (input) {
751 const repository = yield* repositoryOptions(input, "--name", "createRepository");
752 // Project/organization permissions control visibility; `az repos create` has no flag.
753 return yield* executeJson({
754 cwd: input.cwd,
755 args: ["repos", "create", "--detect", "true", ...repository.args],
756 ...(repository.stdin === undefined ? {} : { stdin: repository.stdin }),
757 }).pipe(
758 Effect.map((result) => result.stdout.trim()),
759 Effect.flatMap((raw) =>
760 decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "createRepository", input.cwd),
761 ),
762 Effect.map(normalizeRepositoryCloneUrls),
763 );
764 }),
765 createPullRequest: Effect.fn("AzureDevOpsCli.createPullRequest")(function (input) {
766 // A full ref keeps a branch named `@...` from reading as a file; az accepts either form.
767 const branch = (name: string) => (name.startsWith("@") ? `refs/heads/${name}` : name);
768 const title = textOption("--title", input.title);
769 return execute({
770 cwd: input.cwd,
771 ...remoteOf(input),
772 args: [
773 "repos",
774 "pr",
775 "create",
776 "--only-show-errors",
777 "--detect",
778 "true",
779 `--target-branch=${branch(input.target?.refName ?? input.baseBranch)}`,
780 `--source-branch=${branch(SourceControlProvider.sourceBranch(input))}`,
781 title.arg,
782 // Joined: az expands a separate `@file` value again, so a body of `@path` read that file.
783 `--description=@${input.bodyFile}`,
784 ...(input.draft === true ? ["--draft", "true"] : []),
785 ],
786 ...(title.stdin === undefined ? {} : { stdin: title.stdin }),
787 }).pipe(Effect.asVoid);
788 }),
789 getDefaultBranch: Effect.fn("AzureDevOpsCli.getDefaultBranch")(function* (input) {
790 const repository = yield* repositoryOptions(input, "--repository", "getDefaultBranch");
791 return yield* executeJson({
792 cwd: input.cwd,
793 ...remoteOf(input),
794 args: ["repos", "show", "--detect", "true", ...repository.args],
795 ...(repository.stdin === undefined ? {} : { stdin: repository.stdin }),
796 }).pipe(
797 Effect.map((result) => result.stdout.trim()),
798 Effect.flatMap((raw) =>
799 decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "getDefaultBranch", input.cwd),
800 ),
801 Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),
802 );
803 }),
804 });
805});
806​
807export const layer = Layer.effect(AzureDevOpsCli, make);