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 Result from "effect/Result";
5import * as Schema from "effect/Schema";
6import * as SchemaIssue from "effect/SchemaIssue";
7import {
8 TrimmedNonEmptyString,
9 type SourceControlRepositoryVisibility,
10 type VcsError,
11} from "@t3tools/contracts";
12
13import * as VcsProcess from "../vcs/VcsProcess.ts";
14import * as AzureDevOpsPullRequests from "./azureDevOpsPullRequests.ts";
15import * as SourceControlProvider from "./SourceControlProvider.ts";
16
17const DEFAULT_TIMEOUT_MS = 30_000;
18
19export class AzureDevOpsCliError extends Schema.TaggedErrorClass<AzureDevOpsCliError>()(
20 "AzureDevOpsCliError",
21 {
22 operation: Schema.String,
23 detail: Schema.String,
24 cause: Schema.optional(Schema.Defect()),
25 },
26) {
27 override get message(): string {
28 return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
29 }
30}
31
32export interface AzureDevOpsRepositoryCloneUrls {
33 readonly nameWithOwner: string;
34 readonly url: string;
35 readonly sshUrl: string;
36}
37
38export interface AzureDevOpsCliShape {
39 readonly execute: (input: {
40 readonly cwd: string;
41 readonly args: ReadonlyArray<string>;
42 readonly timeoutMs?: number;
43 }) => Effect.Effect<VcsProcess.VcsProcessOutput, AzureDevOpsCliError>;
44
45 readonly listPullRequests: (input: {
46 readonly cwd: string;
47 readonly headSelector: string;
48 readonly source?: SourceControlProvider.SourceControlRefSelector;
49 readonly state: "open" | "closed" | "merged" | "all";
50 readonly limit?: number;
51 }) => Effect.Effect<
52 ReadonlyArray<AzureDevOpsPullRequests.NormalizedAzureDevOpsPullRequestRecord>,
53 AzureDevOpsCliError
54 >;
55
56 readonly getPullRequest: (input: {
57 readonly cwd: string;
58 readonly reference: string;
59 }) => Effect.Effect<
60 AzureDevOpsPullRequests.NormalizedAzureDevOpsPullRequestRecord,
61 AzureDevOpsCliError
62 >;
63
64 readonly getRepositoryCloneUrls: (input: {
65 readonly cwd: string;
66 readonly repository: string;
67 }) => Effect.Effect<AzureDevOpsRepositoryCloneUrls, AzureDevOpsCliError>;
68
69 readonly createRepository: (input: {
70 readonly cwd: string;
71 readonly repository: string;
72 readonly visibility: SourceControlRepositoryVisibility;
73 }) => Effect.Effect<AzureDevOpsRepositoryCloneUrls, AzureDevOpsCliError>;
74
75 readonly createPullRequest: (input: {
76 readonly cwd: string;
77 readonly baseBranch: string;
78 readonly headSelector: string;
79 readonly source?: SourceControlProvider.SourceControlRefSelector;
80 readonly target?: SourceControlProvider.SourceControlRefSelector;
81 readonly title: string;
82 readonly bodyFile: string;
83 }) => Effect.Effect<void, AzureDevOpsCliError>;
84
85 readonly getDefaultBranch: (input: {
86 readonly cwd: string;
87 }) => Effect.Effect<string | null, AzureDevOpsCliError>;
88
89 readonly checkoutPullRequest: (input: {
90 readonly cwd: string;
91 readonly reference: string;
92 readonly remoteName?: string;
93 }) => Effect.Effect<void, AzureDevOpsCliError>;
94}
95
96export class AzureDevOpsCli extends Context.Service<AzureDevOpsCli, AzureDevOpsCliShape>()(
97 "t3/sourceControl/AzureDevOpsCli",
98) {}
99
100function errorText(error: VcsError | unknown): string {
101 if (typeof error === "object" && error !== null) {
102 const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
103 const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
104 const message = "message" in error && typeof error.message === "string" ? error.message : "";
105 return [tag, detail, message].filter(Boolean).join("\n");
106 }
107
108 return String(error);
109}
110
111function normalizeAzureDevOpsCliError(
112 operation: "execute",
113 error: VcsError | unknown,
114): AzureDevOpsCliError {
115 const text = errorText(error);
116 const lower = text.toLowerCase();
117
118 if (lower.includes("command not found: az") || lower.includes("enoent")) {
119 return new AzureDevOpsCliError({
120 operation,
121 detail:
122 "Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.",
123 cause: error,
124 });
125 }
126
127 if (
128 lower.includes("az devops login") ||
129 lower.includes("please run az login") ||
130 lower.includes("not logged in") ||
131 lower.includes("authentication failed") ||
132 lower.includes("unauthorized")
133 ) {
134 return new AzureDevOpsCliError({
135 operation,
136 detail: "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.",
137 cause: error,
138 });
139 }
140
141 if (
142 lower.includes("pull request") &&
143 (lower.includes("not found") || lower.includes("does not exist"))
144 ) {
145 return new AzureDevOpsCliError({
146 operation,
147 detail: "Pull request not found. Check the PR number or URL and try again.",
148 cause: error,
149 });
150 }
151
152 return new AzureDevOpsCliError({
153 operation,
154 detail: text,
155 cause: error,
156 });
157}
158
159function normalizeChangeRequestId(reference: string): string {
160 const trimmed = reference.trim().replace(/^#/, "");
161 const urlMatch = /(?:pullrequest|pull-request|pull|_pulls?)\/(\d+)(?:\D.*)?$/i.exec(trimmed);
162 return urlMatch?.[1] ?? trimmed;
163}
164
165function toAzureStatus(state: "open" | "closed" | "merged" | "all"): string {
166 switch (state) {
167 case "open":
168 return "active";
169 case "closed":
170 return "abandoned";
171 case "merged":
172 return "completed";
173 case "all":
174 return "all";
175 }
176}
177
178const RawAzureDevOpsRepositorySchema = Schema.Struct({
179 name: TrimmedNonEmptyString,
180 webUrl: TrimmedNonEmptyString,
181 remoteUrl: TrimmedNonEmptyString,
182 sshUrl: TrimmedNonEmptyString,
183 project: Schema.optional(
184 Schema.Struct({
185 name: TrimmedNonEmptyString,
186 }),
187 ),
188 defaultBranch: Schema.optional(Schema.NullOr(Schema.String)),
189});
190
191function normalizeDefaultBranch(value: string | null | undefined): string | null {
192 const trimmed = value?.trim().replace(/^refs\/heads\//, "") ?? "";
193 return trimmed.length > 0 ? trimmed : null;
194}
195
196function normalizeRepositoryCloneUrls(
197 raw: Schema.Schema.Type<typeof RawAzureDevOpsRepositorySchema>,
198): AzureDevOpsRepositoryCloneUrls {
199 const projectName = raw.project?.name.trim();
200 return {
201 nameWithOwner: projectName ? `${projectName}/${raw.name}` : raw.name,
202 url: raw.remoteUrl,
203 sshUrl: raw.sshUrl,
204 };
205}
206
207function parseRepositorySpecifier(repository: string): {
208 readonly project: string | null;
209 readonly name: string;
210} {
211 const parts: Array<string> = [];
212 for (const part of repository.split("/")) {
213 const trimmed = part.trim();
214 if (trimmed.length > 0) {
215 parts.push(trimmed);
216 }
217 }
218 return {
219 project: parts.length > 1 ? (parts.at(-2) ?? null) : null,
220 name: parts.at(-1) ?? repository.trim(),
221 };
222}
223
224function decodeAzureDevOpsJson<S extends Schema.Top>(
225 raw: string,
226 schema: S,
227 operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
228 invalidDetail: string,
229): Effect.Effect<S["Type"], AzureDevOpsCliError, S["DecodingServices"]> {
230 return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
231 Effect.mapError(
232 (error) =>
233 new AzureDevOpsCliError({
234 operation,
235 detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
236 cause: error,
237 }),
238 ),
239 );
240}
241
242export const make = Effect.fn("makeAzureDevOpsCli")(function* () {
243 const process = yield* VcsProcess.VcsProcess;
244
245 const execute: AzureDevOpsCliShape["execute"] = (input) =>
246 process
247 .run({
248 operation: "AzureDevOpsCli.execute",
249 command: "az",
250 args: input.args,
251 cwd: input.cwd,
252 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
253 })
254 .pipe(Effect.mapError((error) => normalizeAzureDevOpsCliError("execute", error)));
255
256 const executeJson = (input: Parameters<AzureDevOpsCliShape["execute"]>[0]) =>
257 execute({
258 ...input,
259 args: [...input.args, "--only-show-errors", "--output", "json"],
260 });
261
262 return AzureDevOpsCli.of({
263 execute,
264 listPullRequests: (input) =>
265 executeJson({
266 cwd: input.cwd,
267 args: [
268 "repos",
269 "pr",
270 "list",
271 "--detect",
272 "true",
273 "--source-branch",
274 SourceControlProvider.sourceBranch(input),
275 "--status",
276 toAzureStatus(input.state),
277 "--top",
278 String(input.limit ?? 20),
279 ],
280 }).pipe(
281 Effect.map((result) => result.stdout.trim()),
282 Effect.flatMap((raw) =>
283 raw.length === 0
284 ? Effect.succeed([])
285 : Effect.sync(() =>
286 AzureDevOpsPullRequests.decodeAzureDevOpsPullRequestListJson(raw),
287 ).pipe(
288 Effect.flatMap((decoded) => {
289 if (!Result.isSuccess(decoded)) {
290 return Effect.fail(
291 new AzureDevOpsCliError({
292 operation: "listPullRequests",
293 detail: `Azure DevOps CLI returned invalid PR list JSON: ${AzureDevOpsPullRequests.formatAzureDevOpsJsonDecodeError(decoded.failure)}`,
294 cause: decoded.failure,
295 }),
296 );
297 }
298
299 return Effect.succeed(decoded.success);
300 }),
301 ),
302 ),
303 ),
304 getPullRequest: (input) =>
305 executeJson({
306 cwd: input.cwd,
307 args: [
308 "repos",
309 "pr",
310 "show",
311 "--detect",
312 "true",
313 "--id",
314 normalizeChangeRequestId(input.reference),
315 ],
316 }).pipe(
317 Effect.map((result) => result.stdout.trim()),
318 Effect.flatMap((raw) =>
319 Effect.sync(() => AzureDevOpsPullRequests.decodeAzureDevOpsPullRequestJson(raw)).pipe(
320 Effect.flatMap((decoded) => {
321 if (!Result.isSuccess(decoded)) {
322 return Effect.fail(
323 new AzureDevOpsCliError({
324 operation: "getPullRequest",
325 detail: `Azure DevOps CLI returned invalid pull request JSON: ${AzureDevOpsPullRequests.formatAzureDevOpsJsonDecodeError(decoded.failure)}`,
326 cause: decoded.failure,
327 }),
328 );
329 }
330
331 return Effect.succeed(decoded.success);
332 }),
333 ),
334 ),
335 ),
336 getRepositoryCloneUrls: (input) =>
337 executeJson({
338 cwd: input.cwd,
339 args: ["repos", "show", "--detect", "true", "--repository", input.repository],
340 }).pipe(
341 Effect.map((result) => result.stdout.trim()),
342 Effect.flatMap((raw) =>
343 decodeAzureDevOpsJson(
344 raw,
345 RawAzureDevOpsRepositorySchema,
346 "getRepositoryCloneUrls",
347 "Azure DevOps CLI returned invalid repository JSON.",
348 ),
349 ),
350 Effect.map(normalizeRepositoryCloneUrls),
351 ),
352 createRepository: (input) => {
353 const repository = parseRepositorySpecifier(input.repository);
354 // Azure Repos access is governed by project/organization permissions.
355 // `az repos create` does not expose a per-repository visibility flag, so
356 // the generic source-control visibility input is intentionally not
357 // translated into CLI args for this provider.
358 return executeJson({
359 cwd: input.cwd,
360 args: [
361 "repos",
362 "create",
363 "--detect",
364 "true",
365 "--name",
366 repository.name,
367 ...(repository.project ? ["--project", repository.project] : []),
368 ],
369 }).pipe(
370 Effect.map((result) => result.stdout.trim()),
371 Effect.flatMap((raw) =>
372 decodeAzureDevOpsJson(
373 raw,
374 RawAzureDevOpsRepositorySchema,
375 "createRepository",
376 "Azure DevOps CLI returned invalid repository JSON.",
377 ),
378 ),
379 Effect.map(normalizeRepositoryCloneUrls),
380 );
381 },
382 createPullRequest: (input) =>
383 execute({
384 cwd: input.cwd,
385 args: [
386 "repos",
387 "pr",
388 "create",
389 "--only-show-errors",
390 "--detect",
391 "true",
392 "--target-branch",
393 input.target?.refName ?? input.baseBranch,
394 "--source-branch",
395 SourceControlProvider.sourceBranch(input),
396 "--title",
397 input.title,
398 "--description",
399 `@${input.bodyFile}`,
400 ],
401 }).pipe(Effect.asVoid),
402 getDefaultBranch: (input) =>
403 executeJson({
404 cwd: input.cwd,
405 args: ["repos", "show", "--detect", "true"],
406 }).pipe(
407 Effect.map((result) => result.stdout.trim()),
408 Effect.flatMap((raw) =>
409 decodeAzureDevOpsJson(
410 raw,
411 RawAzureDevOpsRepositorySchema,
412 "getDefaultBranch",
413 "Azure DevOps CLI returned invalid repository JSON.",
414 ),
415 ),
416 Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),
417 ),
418 checkoutPullRequest: (input) =>
419 execute({
420 cwd: input.cwd,
421 args: [
422 "repos",
423 "pr",
424 "checkout",
425 "--only-show-errors",
426 "--detect",
427 "true",
428 "--id",
429 normalizeChangeRequestId(input.reference),
430 "--remote-name",
431 input.remoteName ?? "origin",
432 ],
433 }).pipe(Effect.asVoid),
434 });
435});
436
437export const layer = Layer.effect(AzureDevOpsCli, make());