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