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

AzureDevOpsCli.ts

553 lines16.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} from "@t3tools/contracts";
13​
14import * as VcsProcess from "../vcs/VcsProcess.ts";
15import {
16 decodeAzureDevOpsPullRequestJson,
17 decodeAzureDevOpsPullRequestListJson,
18 type NormalizedAzureDevOpsPullRequestRecord,
19} from "./azureDevOpsPullRequests.ts";
20import * as SourceControlProvider from "./SourceControlProvider.ts";
21​
22const DEFAULT_TIMEOUT_MS = 30_000;
23​
24const azureDevOpsCommandErrorFields = {
25 operation: Schema.Literal("execute"),
26 command: Schema.Literal("az"),
27 cwd: Schema.String,
28 argumentCount: NonNegativeInt,
29 cause: Schema.Defect(),
30};
31​
32export class AzureDevOpsCliUnavailableError extends Schema.TaggedErrorClass<AzureDevOpsCliUnavailableError>()(
33 "AzureDevOpsCliUnavailableError",
34 azureDevOpsCommandErrorFields,
35) {
36 get detail(): string {
37 return "Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.";
38 }
39​
40 override get message(): string {
41 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
42 }
44​
45export class AzureDevOpsCliAuthenticationError extends Schema.TaggedErrorClass<AzureDevOpsCliAuthenticationError>()(
46 "AzureDevOpsCliAuthenticationError",
47 azureDevOpsCommandErrorFields,
48) {
49 get detail(): string {
50 return "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.";
51 }
52​
53 override get message(): string {
54 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
55 }
57​
58export class AzureDevOpsCliRateLimitError extends Schema.TaggedErrorClass<AzureDevOpsCliRateLimitError>()(
59 "AzureDevOpsCliRateLimitError",
60 azureDevOpsCommandErrorFields,
61) {
62 get detail(): string {
63 return "Azure DevOps API rate limit exceeded.";
64 }
65​
66 override get message(): string {
67 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
68 }
70​
71export class AzureDevOpsPullRequestNotFoundError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestNotFoundError>()(
72 "AzureDevOpsPullRequestNotFoundError",
73 azureDevOpsCommandErrorFields,
74) {
75 get detail(): string {
76 return "Pull request not found. Check the PR number or URL and try again.";
77 }
78​
79 override get message(): string {
80 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
81 }
83​
84export class AzureDevOpsCommandFailedError extends Schema.TaggedErrorClass<AzureDevOpsCommandFailedError>()(
85 "AzureDevOpsCommandFailedError",
86 azureDevOpsCommandErrorFields,
87) {
88 get detail(): string {
89 return "Azure DevOps CLI command failed.";
90 }
91​
92 override get message(): string {
93 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
94 }
95​
96 static fromVcsError(
97 context: {
98 readonly operation: "execute";
99 readonly command: "az";
100 readonly cwd: string;
101 readonly argumentCount: number;
102 },
103 cause: VcsError,
104 ): AzureDevOpsCliError {
105 const fields = { ...context, cause };
106​
107 if (
108 cause._tag === "VcsProcessSpawnError" &&
109 cause.cause instanceof PlatformError.PlatformError &&
110 cause.cause.reason._tag === "NotFound" &&
111 cause.cause.reason.pathOrDescriptor !== context.cwd &&
112 cause.cause.reason.syscall !== "chdir"
113 ) {
114 return new AzureDevOpsCliUnavailableError(fields);
115 }
116​
117 if (cause._tag === "VcsProcessExitError") {
118 if (cause.failureKind === "authentication") {
119 return new AzureDevOpsCliAuthenticationError(fields);
120 }
121 if (cause.failureKind === "rate-limited") {
122 return new AzureDevOpsCliRateLimitError(fields);
123 }
124 if (cause.failureKind === "not-found") {
125 return new AzureDevOpsPullRequestNotFoundError(fields);
126 }
127 }
128​
129 return new AzureDevOpsCommandFailedError(fields);
130 }
132​
133const azureDevOpsDecodeErrorFields = {
134 command: Schema.Literal("az"),
135 cwd: Schema.String,
136 outputLength: NonNegativeInt,
137 cause: Schema.Defect(),
138};
139​
140export class AzureDevOpsPullRequestListDecodeError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestListDecodeError>()(
141 "AzureDevOpsPullRequestListDecodeError",
142 {
143 operation: Schema.Literal("listPullRequests"),
144 ...azureDevOpsDecodeErrorFields,
145 },
146) {
147 get detail(): string {
148 return "Azure DevOps CLI returned invalid PR list JSON.";
149 }
150​
151 override get message(): string {
152 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
153 }
155​
156export class AzureDevOpsPullRequestDecodeError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestDecodeError>()(
157 "AzureDevOpsPullRequestDecodeError",
158 {
159 operation: Schema.Literal("getPullRequest"),
160 ...azureDevOpsDecodeErrorFields,
161 },
162) {
163 get detail(): string {
164 return "Azure DevOps CLI returned invalid pull request JSON.";
165 }
166​
167 override get message(): string {
168 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
169 }
171​
172const AzureDevOpsRepositoryDecodeOperation = Schema.Literals([
173 "getRepositoryCloneUrls",
174 "getDefaultBranch",
175 "createRepository",
176]);
177​
178export class AzureDevOpsRepositoryDecodeError extends Schema.TaggedErrorClass<AzureDevOpsRepositoryDecodeError>()(
179 "AzureDevOpsRepositoryDecodeError",
180 {
181 operation: AzureDevOpsRepositoryDecodeOperation,
182 ...azureDevOpsDecodeErrorFields,
183 },
184) {
185 get detail(): string {
186 return "Azure DevOps CLI returned invalid repository JSON.";
187 }
188​
189 override get message(): string {
190 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
191 }
193​
194export const AzureDevOpsCliError = Schema.Union([
195 AzureDevOpsCliUnavailableError,
196 AzureDevOpsCliAuthenticationError,
197 AzureDevOpsCliRateLimitError,
198 AzureDevOpsPullRequestNotFoundError,
199 AzureDevOpsCommandFailedError,
200 AzureDevOpsPullRequestListDecodeError,
201 AzureDevOpsPullRequestDecodeError,
202 AzureDevOpsRepositoryDecodeError,
203]);
204export type AzureDevOpsCliError = typeof AzureDevOpsCliError.Type;
205​
206export const isAzureDevOpsCliError = Schema.is(AzureDevOpsCliError);
207​
208export interface AzureDevOpsRepositoryCloneUrls {
209 readonly nameWithOwner: string;
210 readonly url: string;
211 readonly sshUrl: string;
213​
214export class AzureDevOpsCli extends Context.Service<
215 AzureDevOpsCli,
216 {
217 readonly execute: (input: {
218 readonly cwd: string;
219 readonly args: ReadonlyArray<string>;
220 readonly timeoutMs?: number;
221 }) => Effect.Effect<VcsProcess.VcsProcessOutput, 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 }) => Effect.Effect<string | null, AzureDevOpsCliError>;
260​
261 readonly checkoutPullRequest: (input: {
262 readonly cwd: string;
263 readonly reference: string;
264 readonly remoteName?: string;
265 }) => Effect.Effect<void, AzureDevOpsCliError>;
266 }
267>()("t3/sourceControl/AzureDevOpsCli") {}
268​
269function normalizeChangeRequestId(reference: string): string {
270 const trimmed = reference.trim().replace(/^#/, "");
271 const urlMatch = /(?:pullrequest|pull-request|pull|_pulls?)\/(\d+)(?:\D.*)?$/i.exec(trimmed);
272 return urlMatch?.[1] ?? trimmed;
274​
275function toAzureStatus(state: "open" | "closed" | "merged" | "all"): string {
276 switch (state) {
277 case "open":
278 return "active";
279 case "closed":
280 return "abandoned";
281 case "merged":
282 return "completed";
283 case "all":
284 return "all";
285 }
287​
288const RawAzureDevOpsRepositorySchema = Schema.Struct({
289 name: TrimmedNonEmptyString,
290 webUrl: TrimmedNonEmptyString,
291 remoteUrl: TrimmedNonEmptyString,
292 sshUrl: TrimmedNonEmptyString,
293 project: Schema.optional(
294 Schema.Struct({
295 name: TrimmedNonEmptyString,
296 }),
297 ),
298 defaultBranch: Schema.optional(Schema.NullOr(Schema.String)),
299});
300​
301function normalizeDefaultBranch(value: string | null | undefined): string | null {
302 const trimmed = value?.trim().replace(/^refs\/heads\//, "") ?? "";
303 return trimmed.length > 0 ? trimmed : null;
305​
306function normalizeRepositoryCloneUrls(
307 raw: Schema.Schema.Type<typeof RawAzureDevOpsRepositorySchema>,
308): AzureDevOpsRepositoryCloneUrls {
309 const projectName = raw.project?.name.trim();
310 return {
311 nameWithOwner: projectName ? `${projectName}/${raw.name}` : raw.name,
312 url: raw.remoteUrl,
313 sshUrl: raw.sshUrl,
314 };
316​
317function parseRepositorySpecifier(repository: string): {
318 readonly project: string | null;
319 readonly name: string;
320} {
321 const parts: Array<string> = [];
322 for (const part of repository.split("/")) {
323 const trimmed = part.trim();
324 if (trimmed.length > 0) {
325 parts.push(trimmed);
326 }
327 }
328 return {
329 project: parts.length > 1 ? (parts.at(-2) ?? null) : null,
330 name: parts.at(-1) ?? repository.trim(),
331 };
333​
334function decodeAzureDevOpsJson<S extends Schema.Top>(
335 raw: string,
336 schema: S,
337 operation: typeof AzureDevOpsRepositoryDecodeOperation.Type,
338 cwd: string,
339): Effect.Effect<S["Type"], AzureDevOpsRepositoryDecodeError, S["DecodingServices"]> {
340 return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
341 Effect.mapError(
342 (cause) =>
343 new AzureDevOpsRepositoryDecodeError({
344 operation,
345 command: "az",
346 cwd,
347 outputLength: raw.length,
348 cause,
349 }),
350 ),
351 );
353​
354export const make = Effect.gen(function* () {
355 const process = yield* VcsProcess.VcsProcess;
356​
357 const execute: AzureDevOpsCli["Service"]["execute"] = (input) =>
358 process
359 .run({
360 operation: "AzureDevOpsCli.execute",
361 command: "az",
362 args: input.args,
363 cwd: input.cwd,
364 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
365 })
366 .pipe(
367 Effect.mapError((error) =>
368 AzureDevOpsCommandFailedError.fromVcsError(
369 {
370 operation: "execute",
371 command: "az",
372 cwd: input.cwd,
373 argumentCount: input.args.length,
374 },
375 error,
376 ),
377 ),
378 );
379​
380 const executeJson = (input: Parameters<AzureDevOpsCli["Service"]["execute"]>[0]) =>
381 execute({
382 ...input,
383 args: [...input.args, "--only-show-errors", "--output", "json"],
384 });
385​
386 return AzureDevOpsCli.of({
387 execute,
388 listPullRequests: (input) =>
389 executeJson({
390 cwd: input.cwd,
391 args: [
392 "repos",
393 "pr",
394 "list",
395 "--detect",
396 "true",
397 "--source-branch",
398 SourceControlProvider.sourceBranch(input),
399 "--status",
400 toAzureStatus(input.state),
401 "--top",
402 String(input.limit ?? 20),
403 ],
404 }).pipe(
405 Effect.map((result) => result.stdout.trim()),
406 Effect.flatMap((raw) =>
407 raw.length === 0
408 ? Effect.succeed([])
409 : Effect.sync(() => decodeAzureDevOpsPullRequestListJson(raw)).pipe(
410 Effect.flatMap((decoded) => {
411 if (!Result.isSuccess(decoded)) {
412 return Effect.fail(
413 new AzureDevOpsPullRequestListDecodeError({
414 operation: "listPullRequests",
415 command: "az",
416 cwd: input.cwd,
417 outputLength: raw.length,
418 cause: decoded.failure,
419 }),
420 );
421 }
422​
423 return Effect.succeed(decoded.success);
424 }),
425 ),
426 ),
427 ),
428 getPullRequest: (input) =>
429 executeJson({
430 cwd: input.cwd,
431 args: [
432 "repos",
433 "pr",
434 "show",
435 "--detect",
436 "true",
437 "--id",
438 normalizeChangeRequestId(input.reference),
439 ],
440 }).pipe(
441 Effect.map((result) => result.stdout.trim()),
442 Effect.flatMap((raw) =>
443 Effect.sync(() => decodeAzureDevOpsPullRequestJson(raw)).pipe(
444 Effect.flatMap((decoded) => {
445 if (!Result.isSuccess(decoded)) {
446 return Effect.fail(
447 new AzureDevOpsPullRequestDecodeError({
448 operation: "getPullRequest",
449 command: "az",
450 cwd: input.cwd,
451 outputLength: raw.length,
452 cause: decoded.failure,
453 }),
454 );
455 }
456​
457 return Effect.succeed(decoded.success);
458 }),
459 ),
460 ),
461 ),
462 getRepositoryCloneUrls: (input) =>
463 executeJson({
464 cwd: input.cwd,
465 args: ["repos", "show", "--detect", "true", "--repository", input.repository],
466 }).pipe(
467 Effect.map((result) => result.stdout.trim()),
468 Effect.flatMap((raw) =>
469 decodeAzureDevOpsJson(
470 raw,
471 RawAzureDevOpsRepositorySchema,
472 "getRepositoryCloneUrls",
473 input.cwd,
474 ),
475 ),
476 Effect.map(normalizeRepositoryCloneUrls),
477 ),
478 createRepository: (input) => {
479 const repository = parseRepositorySpecifier(input.repository);
480 // Azure Repos access is governed by project/organization permissions.
481 // `az repos create` does not expose a per-repository visibility flag, so
482 // the generic source-control visibility input is intentionally not
483 // translated into CLI args for this provider.
484 return executeJson({
485 cwd: input.cwd,
486 args: [
487 "repos",
488 "create",
489 "--detect",
490 "true",
491 "--name",
492 repository.name,
493 ...(repository.project ? ["--project", repository.project] : []),
494 ],
495 }).pipe(
496 Effect.map((result) => result.stdout.trim()),
497 Effect.flatMap((raw) =>
498 decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "createRepository", input.cwd),
499 ),
500 Effect.map(normalizeRepositoryCloneUrls),
501 );
502 },
503 createPullRequest: (input) =>
504 execute({
505 cwd: input.cwd,
506 args: [
507 "repos",
508 "pr",
509 "create",
510 "--only-show-errors",
511 "--detect",
512 "true",
513 "--target-branch",
514 input.target?.refName ?? input.baseBranch,
515 "--source-branch",
516 SourceControlProvider.sourceBranch(input),
517 "--title",
518 input.title,
519 "--description",
520 `@${input.bodyFile}`,
521 ],
522 }).pipe(Effect.asVoid),
523 getDefaultBranch: (input) =>
524 executeJson({
525 cwd: input.cwd,
526 args: ["repos", "show", "--detect", "true"],
527 }).pipe(
528 Effect.map((result) => result.stdout.trim()),
529 Effect.flatMap((raw) =>
530 decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "getDefaultBranch", input.cwd),
531 ),
532 Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),
533 ),
534 checkoutPullRequest: (input) =>
535 execute({
536 cwd: input.cwd,
537 args: [
538 "repos",
539 "pr",
540 "checkout",
541 "--only-show-errors",
542 "--detect",
543 "true",
544 "--id",
545 normalizeChangeRequestId(input.reference),
546 "--remote-name",
547 input.remoteName ?? "origin",
548 ],
549 }).pipe(Effect.asVoid),
550 });
551});
552​
553export const layer = Layer.effect(AzureDevOpsCli, make);