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

AzureDevOpsPullRequestCli.ts

487 lines16.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 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";
114​
115export class AzureDevOpsPullRequestCli extends Context.Service<
116 AzureDevOpsPullRequestCli,
117 {
118 readonly getViewer: (input: {
119 readonly cwd: string;
120 }) => Effect.Effect<string, AzureDevOpsPullRequestCliError>;
121​
122 readonly listPullRequests: (input: {
123 readonly cwd: string;
124 readonly repository: string;
125 readonly state: PullRequestListState;
126 readonly involvement: PullRequestInvolvement;
127 readonly viewer: string;
128 readonly limit: number;
129 /**
130 * Where to carry on from. Azure has no date filter for a pull request listing, so the only
131 * part of a cursor it can use is how many rows have already been handed over.
132 */
133 readonly cursor?: ProviderListCursor | undefined;
134 }) => Effect.Effect<
135 {
136 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
137 readonly truncated: boolean;
138 /** Raw Azure rows consumed to produce this page, including malformed rows. */
139 readonly cursorAdvance: number;
140 },
141 AzureDevOpsPullRequestCliError
142 >;
143​
144 readonly getPullRequest: (input: {
145 readonly cwd: string;
146 readonly number: number;
147 }) => Effect.Effect<AzureDevOpsPullRequest, AzureDevOpsPullRequestCliError>;
148​
149 /** Threads are not reachable through `az repos pr`, so they come from the REST API. */
150 readonly listThreads: (input: {
151 readonly cwd: string;
152 readonly threadsUrl: string;
153 }) => Effect.Effect<ReadonlyArray<PullRequestComment>, AzureDevOpsPullRequestCliError>;
154​
155 readonly runPullRequestAction: (input: {
156 readonly cwd: string;
157 readonly number: number;
158 readonly action: PullRequestAction;
159 readonly mergeMethod?: PullRequestMergeMethod;
160 }) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
161​
162 /**
163 * Adds reviewers to a pull request, or takes them off it. `az repos pr reviewer` is the whole
164 * of what Azure offers here: it adds and removes named identities, and has no counterpart that
165 * says who could be named.
166 */
167 readonly setPullRequestReviewers: (input: {
168 readonly cwd: string;
169 readonly number: number;
170 readonly reviewers: ReadonlyArray<string>;
171 readonly requested: boolean;
172 }) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
173 }
174>()("t3/pullRequest/AzureDevOpsPullRequestCli") {}
175​
176function statusArgs(state: PullRequestListState): ReadonlyArray<string> {
177 switch (state) {
178 case "open":
179 return ["--status", "active"];
180 case "merged":
181 return ["--status", "completed"];
182 case "closed":
183 return ["--status", "abandoned"];
184 case "all":
185 return ["--status", "all"];
186 }
188​
189function involvementArgs(input: {
190 readonly involvement: PullRequestInvolvement;
191 readonly viewer: string;
192}): ReadonlyArray<string> {
193 switch (input.involvement) {
194 case "authored":
195 return ["--creator", input.viewer];
196 case "reviewing":
197 return ["--reviewer", input.viewer];
198 case "all":
199 return [];
200 }
202​
203/**
204 * Azure moves a pull request by setting its state rather than by named commands: completing it
205 * is the merge, abandoning it is the close, and reactivating it is the reopen. Squashing is a
206 * completion option rather than a strategy of its own.
207 */
208function actionArgs(
209 action: PullRequestAction,
210 mergeMethod: PullRequestMergeMethod | undefined,
211): ReadonlyArray<string> {
212 switch (action) {
213 case "merge":
214 return ["--status", "completed", "--squash", mergeMethod === "squash" ? "true" : "false"];
215 case "ready":
216 return ["--draft", "false"];
217 case "draft":
218 return ["--draft", "true"];
219 case "close":
220 return ["--status", "abandoned"];
221 case "reopen":
222 return ["--status", "active"];
223 }
225​
226/**
227 * A reviewer Azure could be given: an email address, a display name or an identity guid, and
228 * nothing that starts with a dash. The dash is the whole point — these are argv, and a value that
229 * looks like a flag stops being a value.
230 */
231function isReviewerName(value: string): boolean {
232 const name = value.trim();
233 return name.length > 0 && !name.startsWith("-");
235​
236export const make = Effect.gen(function* () {
237 const azure = yield* AzureDevOpsCli.AzureDevOpsCli;
238​
239 // Every command resolves the organization, project and repository from the checkout, which is
240 // what the rest of the Azure wrapper does. The remote takes three shapes and only `az` knows
241 // how to read all of them.
242 const detectArgs = ["--detect", "true"] as const;
243​
244 const executeJson = (input: { readonly cwd: string; readonly args: ReadonlyArray<string> }) =>
245 azure.execute({
246 cwd: input.cwd,
247 args: [...input.args, "--only-show-errors", "--output", "json"],
248 });
249​
250 /**
251 * Azure pages by raw offset. Keep reading when malformed rows leave the decoded page short, and
252 * retain the raw count so the next public cursor skips every row this walk consumed.
253 */
254 const listPullRequestPage = (input: {
255 readonly cwd: string;
256 readonly repository: string;
257 readonly state: PullRequestListState;
258 readonly involvement: PullRequestInvolvement;
259 readonly viewer: string;
260 readonly limit: number;
261 readonly skip: number;
262 readonly cursorAdvance: number;
263 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
264 }): Effect.Effect<
265 {
266 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
267 readonly truncated: boolean;
268 readonly cursorAdvance: number;
269 },
270 AzureDevOpsPullRequestCliError
271 > => {
272 const remaining = input.limit - input.items.length;
273 const top = remaining + 1;
274 return executeJson({
275 cwd: input.cwd,
276 args: [
277 "repos",
278 "pr",
279 "list",
280 ...detectArgs,
281 "--repository",
282 input.repository,
283 ...statusArgs(input.state),
284 ...involvementArgs(input),
285 // A web link per row, which is the only url that needs no assembling.
286 "--include-links",
287 ...(input.skip === 0 ? [] : ["--skip", String(input.skip)]),
288 "--top",
289 String(top),
290 ],
291 }).pipe(
292 Effect.flatMap((result) => {
293 const raw = result.stdout.trim();
294 if (raw.length === 0) {
295 return Effect.succeed({
296 items: input.items,
297 truncated: false,
298 cursorAdvance: input.cursorAdvance,
299 });
300 }
301 const decoded = decodePullRequestListJson(raw);
302 if (!Result.isSuccess(decoded)) {
303 return Effect.fail(
304 new AzureDevOpsPullRequestReadError({
305 command: "az",
306 cwd: input.cwd,
307 operation: "listPullRequests",
308 cause: decoded.failure,
309 }),
310 );
311 }
312​
313 const lastItemIndex = decoded.success.rawIndexes[remaining - 1];
314 if (lastItemIndex !== undefined) {
315 const consumed = lastItemIndex + 1;
316 return Effect.succeed({
317 items: [...input.items, ...decoded.success.items.slice(0, remaining)],
318 // A full raw response may have more rows even when malformed entries used the probe.
319 truncated: consumed < decoded.success.rawCount || decoded.success.rawCount === top,
320 cursorAdvance: input.cursorAdvance + consumed,
321 });
322 }
323​
324 const items = [...input.items, ...decoded.success.items];
325 if (decoded.success.rawCount < top) {
326 return Effect.succeed({
327 items,
328 truncated: false,
329 cursorAdvance: input.cursorAdvance + decoded.success.rawCount,
330 });
331 }
332 return listPullRequestPage({
333 ...input,
334 skip: input.skip + decoded.success.rawCount,
335 cursorAdvance: input.cursorAdvance + decoded.success.rawCount,
336 items,
337 });
338 }),
339 );
340 };
341​
342 return AzureDevOpsPullRequestCli.of({
343 getViewer: (input) =>
344 executeJson({ cwd: input.cwd, args: ["account", "show", "--query", "user"] }).pipe(
345 Effect.flatMap((result): Effect.Effect<string, AzureDevOpsPullRequestCliError> => {
346 // `--query user` narrows the payload to the account, so it is nested back under the
347 // key the decoder reads to keep one shape for the signed-in user.
348 const decoded = decodeViewerJson(`{"user":${result.stdout.trim() || "null"}}`);
349 if (!Result.isSuccess(decoded)) {
350 return Effect.fail(
351 new AzureDevOpsPullRequestReadError({
352 command: "az",
353 cwd: input.cwd,
354 operation: "getViewer",
355 cause: decoded.failure,
356 }),
357 );
358 }
359 return decoded.success === null
360 ? Effect.fail(new AzureDevOpsViewerUnavailableError({ command: "az", cwd: input.cwd }))
361 : Effect.succeed(decoded.success);
362 }),
363 ),
364​
365 listPullRequests: (input) =>
366 listPullRequestPage({
367 cwd: input.cwd,
368 repository: input.repository,
369 state: input.state,
370 involvement: input.involvement,
371 viewer: input.viewer,
372 limit: input.limit,
373 // Azure counts rather than filters, so a slice carries on by stepping over every raw row
374 // the prior slice consumed. That is an offset into a list that can shift underneath it:
375 // a pull request opened between two slices moves everything down one, and the row on the
376 // seam is the one that pays for it.
377 skip: input.cursor?.delivered ?? 0,
378 cursorAdvance: 0,
379 items: [],
380 }),
381​
382 getPullRequest: (input) =>
383 executeJson({
384 cwd: input.cwd,
385 args: ["repos", "pr", "show", ...detectArgs, "--id", String(input.number)],
386 }).pipe(
387 Effect.flatMap(
388 (result): Effect.Effect<AzureDevOpsPullRequest, AzureDevOpsPullRequestCliError> => {
389 const decoded = decodePullRequestJson(result.stdout.trim());
390 if (!Result.isSuccess(decoded)) {
391 return Effect.fail(
392 new AzureDevOpsPullRequestReadError({
393 command: "az",
394 cwd: input.cwd,
395 operation: "getPullRequest",
396 cause: decoded.failure,
397 }),
398 );
399 }
400 // Null means Azure answered with too little to place the pull request. Nothing
401 // failed underneath it, so it is its own outcome rather than a decode failure.
402 return decoded.success === null
403 ? Effect.fail(
404 new AzureDevOpsPullRequestIncompleteError({
405 command: "az",
406 cwd: input.cwd,
407 number: input.number,
408 }),
409 )
410 : Effect.succeed(decoded.success);
411 },
412 ),
413 ),
414​
415 listThreads: (input) =>
416 executeJson({
417 cwd: input.cwd,
418 args: [
419 "rest",
420 "--method",
421 "get",
422 "--url",
423 `${input.threadsUrl}?api-version=${REST_API_VERSION}`,
424 ],
425 }).pipe(
426 Effect.flatMap((result) => {
427 const decoded = decodeThreadsJson(result.stdout.trim());
428 return Result.isSuccess(decoded)
429 ? Effect.succeed(decoded.success)
430 : Effect.fail(
431 new AzureDevOpsPullRequestReadError({
432 command: "az",
433 cwd: input.cwd,
434 operation: "listThreads",
435 cause: decoded.failure,
436 }),
437 );
438 }),
439 ),
440​
441 setPullRequestReviewers: (input) =>
442 input.reviewers.some((reviewer) => !isReviewerName(reviewer))
443 ? Effect.fail(new AzureDevOpsReviewerNameError({ command: "az", cwd: input.cwd }))
444 : azure
445 .execute({
446 cwd: input.cwd,
447 args: [
448 "repos",
449 "pr",
450 "reviewer",
451 input.requested ? "add" : "remove",
452 ...detectArgs,
453 "--id",
454 String(input.number),
455 // One `--reviewers` takes them all, because az reads the flag as a list and a
456 // second one would replace the first rather than add to it.
457 "--reviewers",
458 ...input.reviewers,
459 "--only-show-errors",
460 "--output",
461 "json",
462 ],
463 })
464 .pipe(Effect.asVoid),
465​
466 runPullRequestAction: (input) =>
467 azure
468 .execute({
469 cwd: input.cwd,
470 args: [
471 "repos",
472 "pr",
473 "update",
474 ...detectArgs,
475 "--id",
476 String(input.number),
477 ...actionArgs(input.action, input.mergeMethod),
478 "--only-show-errors",
479 "--output",
480 "json",
481 ],
482 })
483 .pipe(Effect.asVoid),
484 });
485});
486​
487export const layer = Layer.effect(AzureDevOpsPullRequestCli, make);