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

AzureDevOpsCli.ts

555 lines16.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} 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 readonly maxOutputBytes?: number;
222 }) => Effect.Effect<VcsProcess.VcsProcessOutput, AzureDevOpsCliError>;
223​
224 readonly listPullRequests: (input: {
225 readonly cwd: string;
226 readonly headSelector: string;
227 readonly source?: SourceControlProvider.SourceControlRefSelector;
228 readonly state: "open" | "closed" | "merged" | "all";
229 readonly limit?: number;
230 }) => Effect.Effect<ReadonlyArray<NormalizedAzureDevOpsPullRequestRecord>, AzureDevOpsCliError>;
231​
232 readonly getPullRequest: (input: {
233 readonly cwd: string;
234 readonly reference: string;
235 }) => Effect.Effect<NormalizedAzureDevOpsPullRequestRecord, AzureDevOpsCliError>;
236​
237 readonly getRepositoryCloneUrls: (input: {
238 readonly cwd: string;
239 readonly repository: string;
240 }) => Effect.Effect<AzureDevOpsRepositoryCloneUrls, AzureDevOpsCliError>;
241​
242 readonly createRepository: (input: {
243 readonly cwd: string;
244 readonly repository: string;
245 readonly visibility: SourceControlRepositoryVisibility;
246 }) => Effect.Effect<AzureDevOpsRepositoryCloneUrls, AzureDevOpsCliError>;
247​
248 readonly createPullRequest: (input: {
249 readonly cwd: string;
250 readonly baseBranch: string;
251 readonly headSelector: string;
252 readonly source?: SourceControlProvider.SourceControlRefSelector;
253 readonly target?: SourceControlProvider.SourceControlRefSelector;
254 readonly title: string;
255 readonly bodyFile: string;
256 }) => Effect.Effect<void, AzureDevOpsCliError>;
257​
258 readonly getDefaultBranch: (input: {
259 readonly cwd: 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>()("t3/sourceControl/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​
355export const make = Effect.gen(function* () {
356 const process = yield* VcsProcess.VcsProcess;
357​
358 const execute: AzureDevOpsCli["Service"]["execute"] = (input) =>
359 process
360 .run({
361 operation: "AzureDevOpsCli.execute",
362 command: "az",
363 args: input.args,
364 cwd: input.cwd,
365 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
366 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
367 })
368 .pipe(
369 Effect.mapError((error) =>
370 AzureDevOpsCommandFailedError.fromVcsError(
371 {
372 operation: "execute",
373 command: "az",
374 cwd: input.cwd,
375 argumentCount: input.args.length,
376 },
377 error,
378 ),
379 ),
380 );
381​
382 const executeJson = (input: Parameters<AzureDevOpsCli["Service"]["execute"]>[0]) =>
383 execute({
384 ...input,
385 args: [...input.args, "--only-show-errors", "--output", "json"],
386 });
387​
388 return AzureDevOpsCli.of({
389 execute,
390 listPullRequests: (input) =>
391 executeJson({
392 cwd: input.cwd,
393 args: [
394 "repos",
395 "pr",
396 "list",
397 "--detect",
398 "true",
399 "--source-branch",
400 SourceControlProvider.sourceBranch(input),
401 "--status",
402 toAzureStatus(input.state),
403 "--top",
404 String(input.limit ?? 20),
405 ],
406 }).pipe(
407 Effect.map((result) => result.stdout.trim()),
408 Effect.flatMap((raw) =>
409 raw.length === 0
410 ? Effect.succeed([])
411 : Effect.sync(() => decodeAzureDevOpsPullRequestListJson(raw)).pipe(
412 Effect.flatMap((decoded) => {
413 if (!Result.isSuccess(decoded)) {
414 return Effect.fail(
415 new AzureDevOpsPullRequestListDecodeError({
416 operation: "listPullRequests",
417 command: "az",
418 cwd: input.cwd,
419 outputLength: raw.length,
420 cause: decoded.failure,
421 }),
422 );
423 }
424​
425 return Effect.succeed(decoded.success);
426 }),
427 ),
428 ),
429 ),
430 getPullRequest: (input) =>
431 executeJson({
432 cwd: input.cwd,
433 args: [
434 "repos",
435 "pr",
436 "show",
437 "--detect",
438 "true",
439 "--id",
440 normalizeChangeRequestId(input.reference),
441 ],
442 }).pipe(
443 Effect.map((result) => result.stdout.trim()),
444 Effect.flatMap((raw) =>
445 Effect.sync(() => decodeAzureDevOpsPullRequestJson(raw)).pipe(
446 Effect.flatMap((decoded) => {
447 if (!Result.isSuccess(decoded)) {
448 return Effect.fail(
449 new AzureDevOpsPullRequestDecodeError({
450 operation: "getPullRequest",
451 command: "az",
452 cwd: input.cwd,
453 outputLength: raw.length,
454 cause: decoded.failure,
455 }),
456 );
457 }
458​
459 return Effect.succeed(decoded.success);
460 }),
461 ),
462 ),
463 ),
464 getRepositoryCloneUrls: (input) =>
465 executeJson({
466 cwd: input.cwd,
467 args: ["repos", "show", "--detect", "true", "--repository", input.repository],
468 }).pipe(
469 Effect.map((result) => result.stdout.trim()),
470 Effect.flatMap((raw) =>
471 decodeAzureDevOpsJson(
472 raw,
473 RawAzureDevOpsRepositorySchema,
474 "getRepositoryCloneUrls",
475 input.cwd,
476 ),
477 ),
478 Effect.map(normalizeRepositoryCloneUrls),
479 ),
480 createRepository: (input) => {
481 const repository = parseRepositorySpecifier(input.repository);
482 // Azure Repos access is governed by project/organization permissions.
483 // `az repos create` does not expose a per-repository visibility flag, so
484 // the generic source-control visibility input is intentionally not
485 // translated into CLI args for this provider.
486 return executeJson({
487 cwd: input.cwd,
488 args: [
489 "repos",
490 "create",
491 "--detect",
492 "true",
493 "--name",
494 repository.name,
495 ...(repository.project ? ["--project", repository.project] : []),
496 ],
497 }).pipe(
498 Effect.map((result) => result.stdout.trim()),
499 Effect.flatMap((raw) =>
500 decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "createRepository", input.cwd),
501 ),
502 Effect.map(normalizeRepositoryCloneUrls),
503 );
504 },
505 createPullRequest: (input) =>
506 execute({
507 cwd: input.cwd,
508 args: [
509 "repos",
510 "pr",
511 "create",
512 "--only-show-errors",
513 "--detect",
514 "true",
515 "--target-branch",
516 input.target?.refName ?? input.baseBranch,
517 "--source-branch",
518 SourceControlProvider.sourceBranch(input),
519 "--title",
520 input.title,
521 "--description",
522 `@${input.bodyFile}`,
523 ],
524 }).pipe(Effect.asVoid),
525 getDefaultBranch: (input) =>
526 executeJson({
527 cwd: input.cwd,
528 args: ["repos", "show", "--detect", "true"],
529 }).pipe(
530 Effect.map((result) => result.stdout.trim()),
531 Effect.flatMap((raw) =>
532 decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "getDefaultBranch", input.cwd),
533 ),
534 Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),
535 ),
536 checkoutPullRequest: (input) =>
537 execute({
538 cwd: input.cwd,
539 args: [
540 "repos",
541 "pr",
542 "checkout",
543 "--only-show-errors",
544 "--detect",
545 "true",
546 "--id",
547 normalizeChangeRequestId(input.reference),
548 "--remote-name",
549 input.remoteName ?? "origin",
550 ],
551 }).pipe(Effect.asVoid),
552 });
553});
554​
555export const layer = Layer.effect(AzureDevOpsCli, make);