Open History to see the last commit
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 }
44}
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 }
57}
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 }
70}
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 }
83}
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 }
132}
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 }
155}
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 }
171}
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 }
193}
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;
211}
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;
274}
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 }
287}
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;
305}
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 };
316}
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 };
333}
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 );
353}
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 return normalized.includes("pull request") &&
361 (normalized.includes("not found") || normalized.includes("does not exist"))
362 ? "not-found"
363 : null;
364};
365
366/** @public */
367export const make = Effect.gen(function* () {
368 const { process } = yield* SourceControlHost.SourceControlHost;
369
370 const execute: AzureDevOpsCli["Service"]["execute"] = (input) =>
371 process
372 .run({
373 operation: "AzureDevOpsCli.execute",
374 command: "az",
375 args: input.args,
376 cwd: input.cwd,
377 classifyFailure: classifyAzFailure,
378 notFoundDetail: "Pull request not found.",
379 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
380 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
381 })
382 .pipe(
383 Effect.mapError((error) =>
384 AzureDevOpsCommandFailedError.fromVcsError(
385 {
386 operation: "execute",
387 command: "az",
388 cwd: input.cwd,
389 argumentCount: input.args.length,
390 },
391 error,
392 ),
393 ),
394 );
395
396 const executeJson = (input: Parameters<AzureDevOpsCli["Service"]["execute"]>[0]) =>
397 execute({
398 ...input,
399 args: [...input.args, "--only-show-errors", "--output", "json"],
400 });
401
402 return AzureDevOpsCli.of({
403 execute,
404 listPullRequests: Effect.fn("AzureDevOpsCli.listPullRequests")(function (input) {
405 const branch = SourceControlProvider.sourceBranch(input);
406 // az checks literal ref prefixes before constructing the request URL.
407 const refPrefix =
408 ["refs/heads/", "refs/pull/", "refs/tags/"].find((prefix) => branch.startsWith(prefix)) ??
409 "";
410 return executeJson({
411 cwd: input.cwd,
412 args: [
413 "repos",
414 "pr",
415 "list",
416 "--detect",
417 "true",
418 "--source-branch",
419 // az puts this in the query string unescaped; a `#` would cut the request.
420 refPrefix + encodeURIComponent(branch.slice(refPrefix.length)),
421 "--status",
422 toAzureStatus(input.state),
423 "--top",
424 String(input.limit ?? 20),
425 ],
426 }).pipe(
427 Effect.map((result) => result.stdout.trim()),
428 Effect.flatMap((raw) =>
429 raw.length === 0
430 ? Effect.succeed([])
431 : Effect.sync(() => decodeAzureDevOpsPullRequestListJson(raw)).pipe(
432 Effect.flatMap((decoded) => {
433 if (!Result.isSuccess(decoded)) {
434 return Effect.fail(
435 new AzureDevOpsPullRequestListDecodeError({
436 operation: "listPullRequests",
437 command: "az",
438 cwd: input.cwd,
439 outputLength: raw.length,
440 cause: decoded.failure,
441 }),
442 );
443 }
444
445 return Effect.succeed(decoded.success);
446 }),
447 ),
448 ),
449 );
450 }),
451 getPullRequest: Effect.fn("AzureDevOpsCli.getPullRequest")(function (input) {
452 return executeJson({
453 cwd: input.cwd,
454 args: [
455 "repos",
456 "pr",
457 "show",
458 "--detect",
459 "true",
460 "--id",
461 normalizeChangeRequestId(input.reference),
462 ],
463 }).pipe(
464 Effect.map((result) => result.stdout.trim()),
465 Effect.flatMap((raw) =>
466 Effect.sync(() => decodeAzureDevOpsPullRequestJson(raw)).pipe(
467 Effect.flatMap((decoded) => {
468 if (!Result.isSuccess(decoded)) {
469 return Effect.fail(
470 new AzureDevOpsPullRequestDecodeError({
471 operation: "getPullRequest",
472 command: "az",
473 cwd: input.cwd,
474 outputLength: raw.length,
475 cause: decoded.failure,
476 }),
477 );
478 }
479
480 return Effect.succeed(decoded.success);
481 }),
482 ),
483 ),
484 );
485 }),
486 getRepositoryCloneUrls: Effect.fn("AzureDevOpsCli.getRepositoryCloneUrls")(function (input) {
487 const repository = parseRepositorySpecifier(input.repository);
488 return executeJson({
489 cwd: input.cwd,
490 args: [
491 "repos",
492 "show",
493 "--detect",
494 "true",
495 "--repository",
496 repository.name,
497 ...(repository.project ? ["--project", repository.project] : []),
498 ],
499 }).pipe(
500 Effect.map((result) => result.stdout.trim()),
501 Effect.flatMap((raw) =>
502 decodeAzureDevOpsJson(
503 raw,
504 RawAzureDevOpsRepositorySchema,
505 "getRepositoryCloneUrls",
506 input.cwd,
507 ),
508 ),
509 Effect.map(normalizeRepositoryCloneUrls),
510 );
511 }),
512 createRepository: Effect.fn("AzureDevOpsCli.createRepository")(function (input) {
513 const repository = parseRepositorySpecifier(input.repository);
514 // Project/organization permissions control visibility; `az repos create` has no flag.
515 return executeJson({
516 cwd: input.cwd,
517 args: [
518 "repos",
519 "create",
520 "--detect",
521 "true",
522 "--name",
523 repository.name,
524 ...(repository.project ? ["--project", repository.project] : []),
525 ],
526 }).pipe(
527 Effect.map((result) => result.stdout.trim()),
528 Effect.flatMap((raw) =>
529 decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "createRepository", input.cwd),
530 ),
531 Effect.map(normalizeRepositoryCloneUrls),
532 );
533 }),
534 createPullRequest: Effect.fn("AzureDevOpsCli.createPullRequest")(function (input) {
535 return execute({
536 cwd: input.cwd,
537 args: [
538 "repos",
539 "pr",
540 "create",
541 "--only-show-errors",
542 "--detect",
543 "true",
544 "--target-branch",
545 input.target?.refName ?? input.baseBranch,
546 "--source-branch",
547 SourceControlProvider.sourceBranch(input),
548 "--title",
549 input.title,
550 "--description",
551 `@${input.bodyFile}`,
552 ],
553 }).pipe(Effect.asVoid);
554 }),
555 getDefaultBranch: Effect.fn("AzureDevOpsCli.getDefaultBranch")(function (input) {
556 const repository = parseRepositorySpecifier(input.repository);
557 return executeJson({
558 cwd: input.cwd,
559 args: [
560 "repos",
561 "show",
562 "--detect",
563 "true",
564 // Joined so a name starting with `-` stays the option's value.
565 `--repository=${repository.name}`,
566 ...(repository.project ? ["--project", repository.project] : []),
567 ],
568 }).pipe(
569 Effect.map((result) => result.stdout.trim()),
570 Effect.flatMap((raw) =>
571 decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "getDefaultBranch", input.cwd),
572 ),
573 Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),
574 );
575 }),
576 checkoutPullRequest: Effect.fn("AzureDevOpsCli.checkoutPullRequest")(function (input) {
577 return execute({
578 cwd: input.cwd,
579 args: [
580 "repos",
581 "pr",
582 "checkout",
583 "--only-show-errors",
584 "--detect",
585 "true",
586 "--id",
587 normalizeChangeRequestId(input.reference),
588 "--remote-name",
589 input.remoteName ?? "origin",
590 ],
591 }).pipe(Effect.asVoid);
592 }),
593 });
594});
595
596export const layer = Layer.effect(AzureDevOpsCli, make);