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

AzureDevOpsCli.ts

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