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

AzureDevOpsPullRequestCli.ts

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