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: (input) =>
404 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 getPullRequest: (input) =>
444 executeJson({
445 cwd: input.cwd,
446 args: [
447 "repos",
448 "pr",
449 "show",
450 "--detect",
451 "true",
452 "--id",
453 normalizeChangeRequestId(input.reference),
454 ],
455 }).pipe(
456 Effect.map((result) => result.stdout.trim()),
457 Effect.flatMap((raw) =>
458 Effect.sync(() => decodeAzureDevOpsPullRequestJson(raw)).pipe(
459 Effect.flatMap((decoded) => {
460 if (!Result.isSuccess(decoded)) {
461 return Effect.fail(
462 new AzureDevOpsPullRequestDecodeError({
463 operation: "getPullRequest",
464 command: "az",
465 cwd: input.cwd,
466 outputLength: raw.length,
467 cause: decoded.failure,
468 }),
469 );
470 }
471
472 return Effect.succeed(decoded.success);
473 }),
474 ),
475 ),
476 ),
477 getRepositoryCloneUrls: (input) =>
478 executeJson({
479 cwd: input.cwd,
480 args: ["repos", "show", "--detect", "true", "--repository", input.repository],
481 }).pipe(
482 Effect.map((result) => result.stdout.trim()),
483 Effect.flatMap((raw) =>
484 decodeAzureDevOpsJson(
485 raw,
486 RawAzureDevOpsRepositorySchema,
487 "getRepositoryCloneUrls",
488 input.cwd,
489 ),
490 ),
491 Effect.map(normalizeRepositoryCloneUrls),
492 ),
493 createRepository: (input) => {
494 const repository = parseRepositorySpecifier(input.repository);
495 // Project/organization permissions control visibility; `az repos create` has no flag.
496 return executeJson({
497 cwd: input.cwd,
498 args: [
499 "repos",
500 "create",
501 "--detect",
502 "true",
503 "--name",
504 repository.name,
505 ...(repository.project ? ["--project", repository.project] : []),
506 ],
507 }).pipe(
508 Effect.map((result) => result.stdout.trim()),
509 Effect.flatMap((raw) =>
510 decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "createRepository", input.cwd),
511 ),
512 Effect.map(normalizeRepositoryCloneUrls),
513 );
514 },
515 createPullRequest: (input) =>
516 execute({
517 cwd: input.cwd,
518 args: [
519 "repos",
520 "pr",
521 "create",
522 "--only-show-errors",
523 "--detect",
524 "true",
525 "--target-branch",
526 input.target?.refName ?? input.baseBranch,
527 "--source-branch",
528 SourceControlProvider.sourceBranch(input),
529 "--title",
530 input.title,
531 "--description",
532 `@${input.bodyFile}`,
533 ],
534 }).pipe(Effect.asVoid),
535 getDefaultBranch: (input) =>
536 executeJson({
537 cwd: input.cwd,
538 args: ["repos", "show", "--detect", "true"],
539 }).pipe(
540 Effect.map((result) => result.stdout.trim()),
541 Effect.flatMap((raw) =>
542 decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "getDefaultBranch", input.cwd),
543 ),
544 Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),
545 ),
546 checkoutPullRequest: (input) =>
547 execute({
548 cwd: input.cwd,
549 args: [
550 "repos",
551 "pr",
552 "checkout",
553 "--only-show-errors",
554 "--detect",
555 "true",
556 "--id",
557 normalizeChangeRequestId(input.reference),
558 "--remote-name",
559 input.remoteName ?? "origin",
560 ],
561 }).pipe(Effect.asVoid),
562 });
563});
564
565export const layer = Layer.effect(AzureDevOpsCli, make);