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 type {
7 PullRequestAction,
8 PullRequestComment,
9 PullRequestInvolvement,
10 PullRequestListState,
11 PullRequestMergeMethod,
12} from "@t3tools/contracts";
13
14import * as AzureDevOpsCli from "../sourceControl/AzureDevOpsCli.ts";
15import {
16 decodePullRequestJson,
17 decodePullRequestListJson,
18 decodeThreadsJson,
19 decodeViewerJson,
20 type AzureDevOpsPullRequest,
21} from "./azureDevOpsPullRequestJson.ts";
22import type { ProviderListCursor } from "./PullRequestProvider.ts";
23
24/**
25 * Names the read that produced unusable output, so a failure reports the call it came from
26 * rather than borrowing another operation's message.
27 */
28export class AzureDevOpsPullRequestReadError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestReadError>()(
29 "AzureDevOpsPullRequestReadError",
30 {
31 command: Schema.Literal("az"),
32 cwd: Schema.String,
33 operation: Schema.String,
34 cause: Schema.Defect(),
35 },
36) {
37 get detail(): string {
38 return `Azure CLI returned an unreadable ${this.operation} response.`;
39 }
40
41 override get message(): string {
42 return `Azure CLI failed in ${this.operation}: ${this.detail}`;
43 }
44}
45
46/** Not a decode failure: az answered, the account it answered for just has no name. */
47export class AzureDevOpsViewerUnavailableError extends Schema.TaggedErrorClass<AzureDevOpsViewerUnavailableError>()(
48 "AzureDevOpsViewerUnavailableError",
49 {
50 command: Schema.Literal("az"),
51 cwd: Schema.String,
52 },
53) {
54 get detail(): string {
55 return "Azure CLI returned no account for the current sign-in.";
56 }
57
58 override get message(): string {
59 return `Azure CLI failed in getViewer: ${this.detail}`;
60 }
61}
62
63/**
64 * Not a decode failure either: az answered with a well-formed pull request that simply carries
65 * no branch or link, which is a response this cannot place rather than one it cannot read.
66 */
67export class AzureDevOpsPullRequestIncompleteError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestIncompleteError>()(
68 "AzureDevOpsPullRequestIncompleteError",
69 {
70 command: Schema.Literal("az"),
71 cwd: Schema.String,
72 number: Schema.Int,
73 },
74) {
75 get detail(): string {
76 return "Azure DevOps returned no branch or link for the pull request.";
77 }
78
79 override get message(): string {
80 return `Azure CLI failed in getPullRequest: ${this.detail}`;
81 }
82}
83
84/**
85 * Not a decode failure: the reader named a reviewer `az` would read as a flag of its own. The
86 * reviewers travel as argv rather than in a request body — `az repos pr reviewer` takes them no
87 * other way — so anything that could leave the value position is refused rather than sent.
88 */
89export class AzureDevOpsReviewerNameError extends Schema.TaggedErrorClass<AzureDevOpsReviewerNameError>()(
90 "AzureDevOpsReviewerNameError",
91 {
92 command: Schema.Literal("az"),
93 cwd: Schema.String,
94 },
95) {
96 get detail(): string {
97 return "A reviewer is named by an email address or an identity id.";
98 }
99
100 override get message(): string {
101 return `Azure CLI failed in setPullRequestReviewers: ${this.detail}`;
102 }
103}
104
105export type AzureDevOpsPullRequestCliError =
106 | AzureDevOpsCli.AzureDevOpsCliError
107 | AzureDevOpsPullRequestReadError
108 | AzureDevOpsPullRequestIncompleteError
109 | AzureDevOpsReviewerNameError
110 | AzureDevOpsViewerUnavailableError;
111
112/** The version every REST call below is pinned to, so a new default cannot reshape a response. */
113const REST_API_VERSION = "7.1";
114const PULL_REQUEST_LIST_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
115
116export class AzureDevOpsPullRequestCli extends Context.Service<
117 AzureDevOpsPullRequestCli,
118 {
119 readonly getViewer: (input: {
120 readonly cwd: string;
121 }) => Effect.Effect<string, AzureDevOpsPullRequestCliError>;
122
123 readonly listPullRequests: (input: {
124 readonly cwd: string;
125 readonly repository: string;
126 readonly state: PullRequestListState;
127 readonly involvement: PullRequestInvolvement;
128 readonly viewer: string;
129 readonly limit: number;
130 /**
131 * Where to carry on from. Azure has no date filter for a pull request listing, so the only
132 * part of a cursor it can use is how many rows have already been handed over.
133 */
134 readonly cursor?: ProviderListCursor | undefined;
135 }) => Effect.Effect<
136 {
137 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
138 readonly truncated: boolean;
139 /** Raw Azure rows consumed to produce this page, including malformed rows. */
140 readonly cursorAdvance: number;
141 },
142 AzureDevOpsPullRequestCliError
143 >;
144
145 readonly getPullRequest: (input: {
146 readonly cwd: string;
147 readonly number: number;
148 }) => Effect.Effect<AzureDevOpsPullRequest, AzureDevOpsPullRequestCliError>;
149
150 /** Threads are not reachable through `az repos pr`, so they come from the REST API. */
151 readonly listThreads: (input: {
152 readonly cwd: string;
153 readonly threadsUrl: string;
154 }) => Effect.Effect<ReadonlyArray<PullRequestComment>, AzureDevOpsPullRequestCliError>;
155
156 readonly runPullRequestAction: (input: {
157 readonly cwd: string;
158 readonly number: number;
159 readonly action: PullRequestAction;
160 readonly mergeMethod?: PullRequestMergeMethod;
161 }) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
162
163 /** Rewrites the pull request's own words, through the same command that moves it. */
164 readonly updatePullRequest: (input: {
165 readonly cwd: string;
166 readonly number: number;
167 readonly title?: string | undefined;
168 readonly body?: string | undefined;
169 }) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
170
171 /**
172 * Adds reviewers to a pull request, or takes them off it. `az repos pr reviewer` is the whole
173 * of what Azure offers here: it adds and removes named identities, and has no counterpart that
174 * says who could be named.
175 */
176 readonly setPullRequestReviewers: (input: {
177 readonly cwd: string;
178 readonly number: number;
179 readonly reviewers: ReadonlyArray<string>;
180 readonly requested: boolean;
181 }) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
182 }
183>()("t3/pullRequest/AzureDevOpsPullRequestCli") {}
184
185function statusArgs(state: PullRequestListState): ReadonlyArray<string> {
186 switch (state) {
187 case "open":
188 return ["--status", "active"];
189 case "merged":
190 return ["--status", "completed"];
191 case "closed":
192 return ["--status", "abandoned"];
193 case "all":
194 return ["--status", "all"];
195 }
196}
197
198function involvementArgs(input: {
199 readonly involvement: PullRequestInvolvement;
200 readonly viewer: string;
201}): ReadonlyArray<string> {
202 switch (input.involvement) {
203 case "authored":
204 return ["--creator", input.viewer];
205 case "reviewing":
206 return ["--reviewer", input.viewer];
207 case "all":
208 return [];
209 }
210}
211
212/**
213 * Azure moves a pull request by setting its state rather than by named commands: completing it
214 * is the merge, abandoning it is the close, and reactivating it is the reopen. Squashing is a
215 * completion option rather than a strategy of its own.
216 */
217function actionArgs(
218 action: PullRequestAction,
219 mergeMethod: PullRequestMergeMethod | undefined,
220): ReadonlyArray<string> {
221 switch (action) {
222 case "merge":
223 return ["--status", "completed", "--squash", mergeMethod === "squash" ? "true" : "false"];
224 // Auto-complete is Azure's own name for it: the pull request stays active and Azure completes
225 // it once its policies pass. The squash choice is stored with it, as it is for a merge now.
226 case "enable-auto-merge":
227 return [
228 "--auto-complete",
229 "true",
230 ...(mergeMethod === undefined
231 ? []
232 : ["--squash", mergeMethod === "squash" ? "true" : "false"]),
233 ];
234 case "disable-auto-merge":
235 return ["--auto-complete", "false"];
236 case "ready":
237 return ["--draft", "false"];
238 case "draft":
239 return ["--draft", "true"];
240 case "close":
241 return ["--status", "abandoned"];
242 // Never reached: this host does not declare the action, so nothing offers it.
243 case "update-branch":
244 return [];
245 case "reopen":
246 return ["--status", "active"];
247 // Never reached: this host does not declare the action, so the service refuses it first.
248 case "revert":
249 case "approve-workflows":
250 throw new Error(`Azure DevOps pull request action ${action} is unsupported`);
251 }
252}
253
254/**
255 * A reviewer Azure could be given: an email address, a display name or an identity guid, and
256 * nothing that starts with a dash. The dash is the whole point — these are argv, and a value that
257 * looks like a flag stops being a value.
258 */
259function isReviewerName(value: string): boolean {
260 const name = value.trim();
261 return name.length > 0 && !name.startsWith("-");
262}
263
264export const make = Effect.gen(function* () {
265 const azure = yield* AzureDevOpsCli.AzureDevOpsCli;
266
267 // Every command resolves the organization, project and repository from the checkout, which is
268 // what the rest of the Azure wrapper does. The remote takes three shapes and only `az` knows
269 // how to read all of them.
270 const detectArgs = ["--detect", "true"] as const;
271
272 const executeJson = (input: {
273 readonly cwd: string;
274 readonly args: ReadonlyArray<string>;
275 readonly maxOutputBytes?: number;
276 }) =>
277 azure.execute({
278 cwd: input.cwd,
279 args: [...input.args, "--only-show-errors", "--output", "json"],
280 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
281 });
282
283 /**
284 * Azure pages by raw offset. Keep reading when malformed rows leave the decoded page short, and
285 * retain the raw count so the next public cursor skips every row this walk consumed.
286 */
287 const listPullRequestPage = (input: {
288 readonly cwd: string;
289 readonly repository: string;
290 readonly state: PullRequestListState;
291 readonly involvement: PullRequestInvolvement;
292 readonly viewer: string;
293 readonly limit: number;
294 readonly skip: number;
295 readonly cursorAdvance: number;
296 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
297 }): Effect.Effect<
298 {
299 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
300 readonly truncated: boolean;
301 readonly cursorAdvance: number;
302 },
303 AzureDevOpsPullRequestCliError
304 > => {
305 const remaining = input.limit - input.items.length;
306 const top = remaining + 1;
307 return executeJson({
308 cwd: input.cwd,
309 maxOutputBytes: PULL_REQUEST_LIST_MAX_OUTPUT_BYTES,
310 args: [
311 "repos",
312 "pr",
313 "list",
314 ...detectArgs,
315 "--repository",
316 input.repository,
317 ...statusArgs(input.state),
318 ...involvementArgs(input),
319 // A web link per row, which is the only url that needs no assembling.
320 "--include-links",
321 ...(input.skip === 0 ? [] : ["--skip", String(input.skip)]),
322 "--top",
323 String(top),
324 ],
325 }).pipe(
326 Effect.flatMap((result) => {
327 const raw = result.stdout.trim();
328 if (raw.length === 0) {
329 return Effect.succeed({
330 items: input.items,
331 truncated: false,
332 cursorAdvance: input.cursorAdvance,
333 });
334 }
335 const decoded = decodePullRequestListJson(raw);
336 if (!Result.isSuccess(decoded)) {
337 return Effect.fail(
338 new AzureDevOpsPullRequestReadError({
339 command: "az",
340 cwd: input.cwd,
341 operation: "listPullRequests",
342 cause: decoded.failure,
343 }),
344 );
345 }
346
347 const lastItemIndex = decoded.success.rawIndexes[remaining - 1];
348 if (lastItemIndex !== undefined) {
349 const consumed = lastItemIndex + 1;
350 return Effect.succeed({
351 items: [...input.items, ...decoded.success.items.slice(0, remaining)],
352 // A full raw response may have more rows even when malformed entries used the probe.
353 truncated: consumed < decoded.success.rawCount || decoded.success.rawCount === top,
354 cursorAdvance: input.cursorAdvance + consumed,
355 });
356 }
357
358 const items = [...input.items, ...decoded.success.items];
359 if (decoded.success.rawCount < top) {
360 return Effect.succeed({
361 items,
362 truncated: false,
363 cursorAdvance: input.cursorAdvance + decoded.success.rawCount,
364 });
365 }
366 return listPullRequestPage({
367 ...input,
368 skip: input.skip + decoded.success.rawCount,
369 cursorAdvance: input.cursorAdvance + decoded.success.rawCount,
370 items,
371 });
372 }),
373 );
374 };
375
376 return AzureDevOpsPullRequestCli.of({
377 getViewer: (input) =>
378 executeJson({ cwd: input.cwd, args: ["account", "show", "--query", "user"] }).pipe(
379 Effect.flatMap((result): Effect.Effect<string, AzureDevOpsPullRequestCliError> => {
380 // `--query user` narrows the payload to the account, so it is nested back under the
381 // key the decoder reads to keep one shape for the signed-in user.
382 const decoded = decodeViewerJson(`{"user":${result.stdout.trim() || "null"}}`);
383 if (!Result.isSuccess(decoded)) {
384 return Effect.fail(
385 new AzureDevOpsPullRequestReadError({
386 command: "az",
387 cwd: input.cwd,
388 operation: "getViewer",
389 cause: decoded.failure,
390 }),
391 );
392 }
393 return decoded.success === null
394 ? Effect.fail(new AzureDevOpsViewerUnavailableError({ command: "az", cwd: input.cwd }))
395 : Effect.succeed(decoded.success);
396 }),
397 ),
398
399 listPullRequests: (input) =>
400 listPullRequestPage({
401 cwd: input.cwd,
402 repository: input.repository,
403 state: input.state,
404 involvement: input.involvement,
405 viewer: input.viewer,
406 limit: input.limit,
407 // Azure counts rather than filters, so a slice carries on by stepping over every raw row
408 // the prior slice consumed. That is an offset into a list that can shift underneath it:
409 // a pull request opened between two slices moves everything down one, and the row on the
410 // seam is the one that pays for it.
411 skip: input.cursor?.delivered ?? 0,
412 cursorAdvance: 0,
413 items: [],
414 }),
415
416 getPullRequest: (input) =>
417 executeJson({
418 cwd: input.cwd,
419 args: ["repos", "pr", "show", ...detectArgs, "--id", String(input.number)],
420 }).pipe(
421 Effect.flatMap(
422 (result): Effect.Effect<AzureDevOpsPullRequest, AzureDevOpsPullRequestCliError> => {
423 const decoded = decodePullRequestJson(result.stdout.trim());
424 if (!Result.isSuccess(decoded)) {
425 return Effect.fail(
426 new AzureDevOpsPullRequestReadError({
427 command: "az",
428 cwd: input.cwd,
429 operation: "getPullRequest",
430 cause: decoded.failure,
431 }),
432 );
433 }
434 // Null means Azure answered with too little to place the pull request. Nothing
435 // failed underneath it, so it is its own outcome rather than a decode failure.
436 return decoded.success === null
437 ? Effect.fail(
438 new AzureDevOpsPullRequestIncompleteError({
439 command: "az",
440 cwd: input.cwd,
441 number: input.number,
442 }),
443 )
444 : Effect.succeed(decoded.success);
445 },
446 ),
447 ),
448
449 listThreads: (input) =>
450 executeJson({
451 cwd: input.cwd,
452 args: [
453 "rest",
454 "--method",
455 "get",
456 "--url",
457 `${input.threadsUrl}?api-version=${REST_API_VERSION}`,
458 ],
459 }).pipe(
460 Effect.flatMap((result) => {
461 const decoded = decodeThreadsJson(result.stdout.trim());
462 return Result.isSuccess(decoded)
463 ? Effect.succeed(decoded.success)
464 : Effect.fail(
465 new AzureDevOpsPullRequestReadError({
466 command: "az",
467 cwd: input.cwd,
468 operation: "listThreads",
469 cause: decoded.failure,
470 }),
471 );
472 }),
473 ),
474
475 setPullRequestReviewers: (input) =>
476 input.reviewers.some((reviewer) => !isReviewerName(reviewer))
477 ? Effect.fail(new AzureDevOpsReviewerNameError({ command: "az", cwd: input.cwd }))
478 : azure
479 .execute({
480 cwd: input.cwd,
481 args: [
482 "repos",
483 "pr",
484 "reviewer",
485 input.requested ? "add" : "remove",
486 ...detectArgs,
487 "--id",
488 String(input.number),
489 // One `--reviewers` takes them all, because az reads the flag as a list and a
490 // second one would replace the first rather than add to it.
491 "--reviewers",
492 ...input.reviewers,
493 "--only-show-errors",
494 "--output",
495 "json",
496 ],
497 })
498 .pipe(Effect.asVoid),
499
500 runPullRequestAction: (input) =>
501 azure
502 .execute({
503 cwd: input.cwd,
504 args: [
505 "repos",
506 "pr",
507 "update",
508 ...detectArgs,
509 "--id",
510 String(input.number),
511 ...actionArgs(input.action, input.mergeMethod),
512 "--only-show-errors",
513 "--output",
514 "json",
515 ],
516 })
517 .pipe(Effect.asVoid),
518
519 updatePullRequest: (input) =>
520 azure
521 .execute({
522 cwd: input.cwd,
523 args: [
524 "repos",
525 "pr",
526 "update",
527 ...detectArgs,
528 "--id",
529 String(input.number),
530 // One argument rather than a flag and a value beside it: a description usually opens
531 // with a bullet, and az reads a dash in the next argv slot as a flag of its own.
532 // `--description` also takes several strings, and this keeps the whole text as one.
533 ...(input.title === undefined ? [] : [`--title=${input.title}`]),
534 ...(input.body === undefined ? [] : [`--description=${input.body}`]),
535 "--only-show-errors",
536 "--output",
537 "json",
538 ],
539 })
540 .pipe(Effect.asVoid),
541 });
542});
543
544export const layer = Layer.effect(AzureDevOpsPullRequestCli, make);