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

AzureDevOpsPullRequestCli.ts

545 lines18.5 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 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.TaggedError<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 }
45​
46/** Not a decode failure: az answered, the account it answered for just has no name. */
47export class AzureDevOpsViewerUnavailableError extends Schema.TaggedError<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 }
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.TaggedError<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 }
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.TaggedError<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 }
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 }
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 }
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 }
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("-");
263​
264/** @public Service construction is part of the canonical Effect module API. */
265export const make = Effect.gen(function* () {
266 const azure = yield* AzureDevOpsCli.AzureDevOpsCli;
267​
268 // Every command resolves the organization, project and repository from the checkout, which is
269 // what the rest of the Azure wrapper does. The remote takes three shapes and only `az` knows
270 // how to read all of them.
271 const detectArgs = ["--detect", "true"] as const;
272​
273 const executeJson = (input: {
274 readonly cwd: string;
275 readonly args: ReadonlyArray<string>;
276 readonly maxOutputBytes?: number;
277 }) =>
278 azure.execute({
279 cwd: input.cwd,
280 args: [...input.args, "--only-show-errors", "--output", "json"],
281 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
282 });
283​
284 /**
285 * Azure pages by raw offset. Keep reading when malformed rows leave the decoded page short, and
286 * retain the raw count so the next public cursor skips every row this walk consumed.
287 */
288 const listPullRequestPage = (input: {
289 readonly cwd: string;
290 readonly repository: string;
291 readonly state: PullRequestListState;
292 readonly involvement: PullRequestInvolvement;
293 readonly viewer: string;
294 readonly limit: number;
295 readonly skip: number;
296 readonly cursorAdvance: number;
297 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
298 }): Effect.Effect<
299 {
300 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
301 readonly truncated: boolean;
302 readonly cursorAdvance: number;
303 },
304 AzureDevOpsPullRequestCliError
305 > => {
306 const remaining = input.limit - input.items.length;
307 const top = remaining + 1;
308 return executeJson({
309 cwd: input.cwd,
310 maxOutputBytes: PULL_REQUEST_LIST_MAX_OUTPUT_BYTES,
311 args: [
312 "repos",
313 "pr",
314 "list",
315 ...detectArgs,
316 "--repository",
317 input.repository,
318 ...statusArgs(input.state),
319 ...involvementArgs(input),
320 // A web link per row, which is the only url that needs no assembling.
321 "--include-links",
322 ...(input.skip === 0 ? [] : ["--skip", String(input.skip)]),
323 "--top",
324 String(top),
325 ],
326 }).pipe(
327 Effect.flatMap((result) => {
328 const raw = result.stdout.trim();
329 if (raw.length === 0) {
330 return Effect.succeed({
331 items: input.items,
332 truncated: false,
333 cursorAdvance: input.cursorAdvance,
334 });
335 }
336 const decoded = decodePullRequestListJson(raw);
337 if (!Result.isSuccess(decoded)) {
338 return Effect.fail(
339 new AzureDevOpsPullRequestReadError({
340 command: "az",
341 cwd: input.cwd,
342 operation: "listPullRequests",
343 cause: decoded.failure,
344 }),
345 );
346 }
347​
348 const lastItemIndex = decoded.success.rawIndexes[remaining - 1];
349 if (lastItemIndex !== undefined) {
350 const consumed = lastItemIndex + 1;
351 return Effect.succeed({
352 items: [...input.items, ...decoded.success.items.slice(0, remaining)],
353 // A full raw response may have more rows even when malformed entries used the probe.
354 truncated: consumed < decoded.success.rawCount || decoded.success.rawCount === top,
355 cursorAdvance: input.cursorAdvance + consumed,
356 });
357 }
358​
359 const items = [...input.items, ...decoded.success.items];
360 if (decoded.success.rawCount < top) {
361 return Effect.succeed({
362 items,
363 truncated: false,
364 cursorAdvance: input.cursorAdvance + decoded.success.rawCount,
365 });
366 }
367 return listPullRequestPage({
368 ...input,
369 skip: input.skip + decoded.success.rawCount,
370 cursorAdvance: input.cursorAdvance + decoded.success.rawCount,
371 items,
372 });
373 }),
374 );
375 };
376​
377 return AzureDevOpsPullRequestCli.of({
378 getViewer: (input) =>
379 executeJson({ cwd: input.cwd, args: ["account", "show", "--query", "user"] }).pipe(
380 Effect.flatMap((result): Effect.Effect<string, AzureDevOpsPullRequestCliError> => {
381 // `--query user` narrows the payload to the account, so it is nested back under the
382 // key the decoder reads to keep one shape for the signed-in user.
383 const decoded = decodeViewerJson(`{"user":${result.stdout.trim() || "null"}}`);
384 if (!Result.isSuccess(decoded)) {
385 return Effect.fail(
386 new AzureDevOpsPullRequestReadError({
387 command: "az",
388 cwd: input.cwd,
389 operation: "getViewer",
390 cause: decoded.failure,
391 }),
392 );
393 }
394 return decoded.success === null
395 ? Effect.fail(new AzureDevOpsViewerUnavailableError({ command: "az", cwd: input.cwd }))
396 : Effect.succeed(decoded.success);
397 }),
398 ),
399​
400 listPullRequests: (input) =>
401 listPullRequestPage({
402 cwd: input.cwd,
403 repository: input.repository,
404 state: input.state,
405 involvement: input.involvement,
406 viewer: input.viewer,
407 limit: input.limit,
408 // Azure counts rather than filters, so a slice carries on by stepping over every raw row
409 // the prior slice consumed. That is an offset into a list that can shift underneath it:
410 // a pull request opened between two slices moves everything down one, and the row on the
411 // seam is the one that pays for it.
412 skip: input.cursor?.delivered ?? 0,
413 cursorAdvance: 0,
414 items: [],
415 }),
416​
417 getPullRequest: (input) =>
418 executeJson({
419 cwd: input.cwd,
420 args: ["repos", "pr", "show", ...detectArgs, "--id", String(input.number)],
421 }).pipe(
422 Effect.flatMap(
423 (result): Effect.Effect<AzureDevOpsPullRequest, AzureDevOpsPullRequestCliError> => {
424 const decoded = decodePullRequestJson(result.stdout.trim());
425 if (!Result.isSuccess(decoded)) {
426 return Effect.fail(
427 new AzureDevOpsPullRequestReadError({
428 command: "az",
429 cwd: input.cwd,
430 operation: "getPullRequest",
431 cause: decoded.failure,
432 }),
433 );
434 }
435 // Null means Azure answered with too little to place the pull request. Nothing
436 // failed underneath it, so it is its own outcome rather than a decode failure.
437 return decoded.success === null
438 ? Effect.fail(
439 new AzureDevOpsPullRequestIncompleteError({
440 command: "az",
441 cwd: input.cwd,
442 number: input.number,
443 }),
444 )
445 : Effect.succeed(decoded.success);
446 },
447 ),
448 ),
449​
450 listThreads: (input) =>
451 executeJson({
452 cwd: input.cwd,
453 args: [
454 "rest",
455 "--method",
456 "get",
457 "--url",
458 `${input.threadsUrl}?api-version=${REST_API_VERSION}`,
459 ],
460 }).pipe(
461 Effect.flatMap((result) => {
462 const decoded = decodeThreadsJson(result.stdout.trim());
463 return Result.isSuccess(decoded)
464 ? Effect.succeed(decoded.success)
465 : Effect.fail(
466 new AzureDevOpsPullRequestReadError({
467 command: "az",
468 cwd: input.cwd,
469 operation: "listThreads",
470 cause: decoded.failure,
471 }),
472 );
473 }),
474 ),
475​
476 setPullRequestReviewers: (input) =>
477 input.reviewers.some((reviewer) => !isReviewerName(reviewer))
478 ? Effect.fail(new AzureDevOpsReviewerNameError({ command: "az", cwd: input.cwd }))
479 : azure
480 .execute({
481 cwd: input.cwd,
482 args: [
483 "repos",
484 "pr",
485 "reviewer",
486 input.requested ? "add" : "remove",
487 ...detectArgs,
488 "--id",
489 String(input.number),
490 // One `--reviewers` takes them all, because az reads the flag as a list and a
491 // second one would replace the first rather than add to it.
492 "--reviewers",
493 ...input.reviewers,
494 "--only-show-errors",
495 "--output",
496 "json",
497 ],
498 })
499 .pipe(Effect.asVoid),
500​
501 runPullRequestAction: (input) =>
502 azure
503 .execute({
504 cwd: input.cwd,
505 args: [
506 "repos",
507 "pr",
508 "update",
509 ...detectArgs,
510 "--id",
511 String(input.number),
512 ...actionArgs(input.action, input.mergeMethod),
513 "--only-show-errors",
514 "--output",
515 "json",
516 ],
517 })
518 .pipe(Effect.asVoid),
519​
520 updatePullRequest: (input) =>
521 azure
522 .execute({
523 cwd: input.cwd,
524 args: [
525 "repos",
526 "pr",
527 "update",
528 ...detectArgs,
529 "--id",
530 String(input.number),
531 // One argument rather than a flag and a value beside it: a description usually opens
532 // with a bullet, and az reads a dash in the next argv slot as a flag of its own.
533 // `--description` also takes several strings, and this keeps the whole text as one.
534 ...(input.title === undefined ? [] : [`--title=${input.title}`]),
535 ...(input.body === undefined ? [] : [`--description=${input.body}`]),
536 "--only-show-errors",
537 "--output",
538 "json",
539 ],
540 })
541 .pipe(Effect.asVoid),
542 });
543});
544​
545export const layer = Layer.effect(AzureDevOpsPullRequestCli, make);