Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AzureDevOpsCli.ts

434 lines13.2 KB

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 }
31​
32export interface AzureDevOpsRepositoryCloneUrls {
33 readonly nameWithOwner: string;
34 readonly url: string;
35 readonly sshUrl: string;
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>;
95​
96export class AzureDevOpsCli extends Context.Service<AzureDevOpsCli, AzureDevOpsCliShape>()(
97 "t3/source-control/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);
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 });
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;
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 }
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;
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 };
206​
207function parseRepositorySpecifier(repository: string): {
208 readonly project: string | null;
209 readonly name: string;
210} {
211 const parts = repository
212 .split("/")
213 .map((part) => part.trim())
214 .filter((part) => part.length > 0);
215 return {
216 project: parts.length > 1 ? (parts.at(-2) ?? null) : null,
217 name: parts.at(-1) ?? repository.trim(),
218 };
220​
221function decodeAzureDevOpsJson<S extends Schema.Top>(
222 raw: string,
223 schema: S,
224 operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
225 invalidDetail: string,
226): Effect.Effect<S["Type"], AzureDevOpsCliError, S["DecodingServices"]> {
227 return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
228 Effect.mapError(
229 (error) =>
230 new AzureDevOpsCliError({
231 operation,
232 detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
233 cause: error,
234 }),
235 ),
236 );
238​
239export const make = Effect.fn("makeAzureDevOpsCli")(function* () {
240 const process = yield* VcsProcess.VcsProcess;
241​
242 const execute: AzureDevOpsCliShape["execute"] = (input) =>
243 process
244 .run({
245 operation: "AzureDevOpsCli.execute",
246 command: "az",
247 args: input.args,
248 cwd: input.cwd,
249 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
250 })
251 .pipe(Effect.mapError((error) => normalizeAzureDevOpsCliError("execute", error)));
252​
253 const executeJson = (input: Parameters<AzureDevOpsCliShape["execute"]>[0]) =>
254 execute({
255 ...input,
256 args: [...input.args, "--only-show-errors", "--output", "json"],
257 });
258​
259 return AzureDevOpsCli.of({
260 execute,
261 listPullRequests: (input) =>
262 executeJson({
263 cwd: input.cwd,
264 args: [
265 "repos",
266 "pr",
267 "list",
268 "--detect",
269 "true",
270 "--source-branch",
271 SourceControlProvider.sourceBranch(input),
272 "--status",
273 toAzureStatus(input.state),
274 "--top",
275 String(input.limit ?? 20),
276 ],
277 }).pipe(
278 Effect.map((result) => result.stdout.trim()),
279 Effect.flatMap((raw) =>
280 raw.length === 0
281 ? Effect.succeed([])
282 : Effect.sync(() =>
283 AzureDevOpsPullRequests.decodeAzureDevOpsPullRequestListJson(raw),
284 ).pipe(
285 Effect.flatMap((decoded) => {
286 if (!Result.isSuccess(decoded)) {
287 return Effect.fail(
288 new AzureDevOpsCliError({
289 operation: "listPullRequests",
290 detail: `Azure DevOps CLI returned invalid PR list JSON: ${AzureDevOpsPullRequests.formatAzureDevOpsJsonDecodeError(decoded.failure)}`,
291 cause: decoded.failure,
292 }),
293 );
294 }
295​
296 return Effect.succeed(decoded.success);
297 }),
298 ),
299 ),
300 ),
301 getPullRequest: (input) =>
302 executeJson({
303 cwd: input.cwd,
304 args: [
305 "repos",
306 "pr",
307 "show",
308 "--detect",
309 "true",
310 "--id",
311 normalizeChangeRequestId(input.reference),
312 ],
313 }).pipe(
314 Effect.map((result) => result.stdout.trim()),
315 Effect.flatMap((raw) =>
316 Effect.sync(() => AzureDevOpsPullRequests.decodeAzureDevOpsPullRequestJson(raw)).pipe(
317 Effect.flatMap((decoded) => {
318 if (!Result.isSuccess(decoded)) {
319 return Effect.fail(
320 new AzureDevOpsCliError({
321 operation: "getPullRequest",
322 detail: `Azure DevOps CLI returned invalid pull request JSON: ${AzureDevOpsPullRequests.formatAzureDevOpsJsonDecodeError(decoded.failure)}`,
323 cause: decoded.failure,
324 }),
325 );
326 }
327​
328 return Effect.succeed(decoded.success);
329 }),
330 ),
331 ),
332 ),
333 getRepositoryCloneUrls: (input) =>
334 executeJson({
335 cwd: input.cwd,
336 args: ["repos", "show", "--detect", "true", "--repository", input.repository],
337 }).pipe(
338 Effect.map((result) => result.stdout.trim()),
339 Effect.flatMap((raw) =>
340 decodeAzureDevOpsJson(
341 raw,
342 RawAzureDevOpsRepositorySchema,
343 "getRepositoryCloneUrls",
344 "Azure DevOps CLI returned invalid repository JSON.",
345 ),
346 ),
347 Effect.map(normalizeRepositoryCloneUrls),
348 ),
349 createRepository: (input) => {
350 const repository = parseRepositorySpecifier(input.repository);
351 // Azure Repos access is governed by project/organization permissions.
352 // `az repos create` does not expose a per-repository visibility flag, so
353 // the generic source-control visibility input is intentionally not
354 // translated into CLI args for this provider.
355 return executeJson({
356 cwd: input.cwd,
357 args: [
358 "repos",
359 "create",
360 "--detect",
361 "true",
362 "--name",
363 repository.name,
364 ...(repository.project ? ["--project", repository.project] : []),
365 ],
366 }).pipe(
367 Effect.map((result) => result.stdout.trim()),
368 Effect.flatMap((raw) =>
369 decodeAzureDevOpsJson(
370 raw,
371 RawAzureDevOpsRepositorySchema,
372 "createRepository",
373 "Azure DevOps CLI returned invalid repository JSON.",
374 ),
375 ),
376 Effect.map(normalizeRepositoryCloneUrls),
377 );
378 },
379 createPullRequest: (input) =>
380 execute({
381 cwd: input.cwd,
382 args: [
383 "repos",
384 "pr",
385 "create",
386 "--only-show-errors",
387 "--detect",
388 "true",
389 "--target-branch",
390 input.target?.refName ?? input.baseBranch,
391 "--source-branch",
392 SourceControlProvider.sourceBranch(input),
393 "--title",
394 input.title,
395 "--description",
396 `@${input.bodyFile}`,
397 ],
398 }).pipe(Effect.asVoid),
399 getDefaultBranch: (input) =>
400 executeJson({
401 cwd: input.cwd,
402 args: ["repos", "show", "--detect", "true"],
403 }).pipe(
404 Effect.map((result) => result.stdout.trim()),
405 Effect.flatMap((raw) =>
406 decodeAzureDevOpsJson(
407 raw,
408 RawAzureDevOpsRepositorySchema,
409 "getDefaultBranch",
410 "Azure DevOps CLI returned invalid repository JSON.",
411 ),
412 ),
413 Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),
414 ),
415 checkoutPullRequest: (input) =>
416 execute({
417 cwd: input.cwd,
418 args: [
419 "repos",
420 "pr",
421 "checkout",
422 "--only-show-errors",
423 "--detect",
424 "true",
425 "--id",
426 normalizeChangeRequestId(input.reference),
427 "--remote-name",
428 input.remoteName ?? "origin",
429 ],
430 }).pipe(Effect.asVoid),
431 });
432});
433​
434export const layer = Layer.effect(AzureDevOpsCli, make());