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