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