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 decodeItemContentJson,
17 decodeIterationChangesJson,
18 decodeIterationsJson,
19 decodePullRequestJson,
20 decodePullRequestListJson,
21 decodeThreadsJson,
22 decodeViewerJson,
23 type AzureDevOpsChangeEntry,
24 type AzureDevOpsItemContent,
25 type AzureDevOpsIteration,
26 type AzureDevOpsPullRequest,
27 type AzureDevOpsRepositoryLocation,
28} from "./azureDevOpsPullRequestJson.ts";
29import type { ProviderListCursor } from "./PullRequestProvider.ts";
30
31/**
32 * Names the read that produced unusable output, so a failure reports the call it came from
33 * rather than borrowing another operation's message.
34 */
35export class AzureDevOpsPullRequestReadError extends Schema.TaggedError<AzureDevOpsPullRequestReadError>()(
36 "AzureDevOpsPullRequestReadError",
37 {
38 command: Schema.Literal("az"),
39 cwd: Schema.String,
40 operation: Schema.String,
41 cause: Schema.Defect(),
42 },
43) {
44 get detail(): string {
45 return `Azure CLI returned an unreadable ${this.operation} response.`;
46 }
47
48 override get message(): string {
49 return `Azure CLI failed in ${this.operation}: ${this.detail}`;
50 }
51}
52
53/** Not a decode failure: az answered, the account it answered for just has no name. */
54export class AzureDevOpsViewerUnavailableError extends Schema.TaggedError<AzureDevOpsViewerUnavailableError>()(
55 "AzureDevOpsViewerUnavailableError",
56 {
57 command: Schema.Literal("az"),
58 cwd: Schema.String,
59 },
60) {
61 get detail(): string {
62 return "Azure CLI returned no account for the current sign-in.";
63 }
64
65 override get message(): string {
66 return `Azure CLI failed in getViewer: ${this.detail}`;
67 }
68}
69
70/**
71 * Not a decode failure either: az answered with a well-formed pull request that simply carries
72 * no branch or link, which is a response this cannot place rather than one it cannot read.
73 */
74export class AzureDevOpsPullRequestIncompleteError extends Schema.TaggedError<AzureDevOpsPullRequestIncompleteError>()(
75 "AzureDevOpsPullRequestIncompleteError",
76 {
77 command: Schema.Literal("az"),
78 cwd: Schema.String,
79 number: Schema.Int,
80 },
81) {
82 get detail(): string {
83 return "Azure DevOps returned no branch or link for the pull request.";
84 }
85
86 override get message(): string {
87 return `Azure CLI failed in getPullRequest: ${this.detail}`;
88 }
89}
90
91/**
92 * Not a decode failure: the reader named a reviewer `az` would read as a flag of its own. The
93 * reviewers travel as argv rather than in a request body — `az repos pr reviewer` takes them no
94 * other way — so anything that could leave the value position is refused rather than sent.
95 */
96export class AzureDevOpsReviewerNameError extends Schema.TaggedError<AzureDevOpsReviewerNameError>()(
97 "AzureDevOpsReviewerNameError",
98 {
99 command: Schema.Literal("az"),
100 cwd: Schema.String,
101 },
102) {
103 get detail(): string {
104 return "A reviewer is named by an email address or an identity id.";
105 }
106
107 override get message(): string {
108 return `Azure CLI failed in setPullRequestReviewers: ${this.detail}`;
109 }
110}
111
112export type AzureDevOpsPullRequestCliError =
113 | AzureDevOpsCli.AzureDevOpsCliError
114 | AzureDevOpsPullRequestReadError
115 | AzureDevOpsPullRequestIncompleteError
116 | AzureDevOpsReviewerNameError
117 | AzureDevOpsViewerUnavailableError;
118
119/** The version every REST call below is pinned to, so a new default cannot reshape a response. */
120const REST_API_VERSION = "7.1";
121const PULL_REQUEST_LIST_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
122/**
123 * A full page of change entries is two thousand files, each carrying its path, its url and
124 * several object ids, which is past the megabyte a read is given by default. Output cut at that
125 * ceiling arrives here as JSON that will not parse, so a change large enough to be paged would
126 * report itself as a host returning nonsense rather than as the ordinary page it is.
127 */
128const CHANGE_ENTRIES_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
129/**
130 * Four times the megabyte of file the other hosts hand over, because Azure has no route that
131 * serves the bytes themselves: the file arrives inside a JSON envelope, escaped if it is text and
132 * base64 if it is not, and both are larger than the file they carry.
133 */
134const ITEM_CONTENT_MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
135/**
136 * What a review's own history is given. Neither route pages, so each answers with the whole of it
137 * at once and grows with how long the review ran rather than with how large the change is. Cut at
138 * the default, both arrive as JSON that stops mid-string, and a long review would report its host
139 * as answering with nonsense.
140 */
141const REVIEW_HISTORY_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
142
143/** Azure's own ceiling for one page of an iteration's changes. */
144const CHANGE_ENTRIES_PER_PAGE = 2000;
145
146/**
147 * Where following the pages stops, counted in the entries Azure was asked to skip rather than in
148 * the files that survived decoding: a page can be entirely folders and other entries a review has
149 * nothing to show for, and bounding on what was kept would follow such a change forever. Every
150 * page is an `az` process of its own, so the read gives up and reports itself incomplete rather
151 * than presenting five pages as the whole change.
152 */
153const MAX_CHANGE_ENTRIES = 10_000;
154
155/** What an iteration changed, and whether following its pages reached the end of it. */
156export interface AzureDevOpsIterationChanges {
157 readonly changes: ReadonlyArray<AzureDevOpsChangeEntry>;
158 readonly truncated: boolean;
159}
160
161export class AzureDevOpsPullRequestCli extends Context.Service<
162 AzureDevOpsPullRequestCli,
163 {
164 readonly getViewer: (input: {
165 readonly cwd: string;
166 }) => Effect.Effect<string, AzureDevOpsPullRequestCliError>;
167
168 readonly listPullRequests: (input: {
169 readonly cwd: string;
170 readonly repository: string;
171 readonly state: PullRequestListState;
172 readonly involvement: PullRequestInvolvement;
173 readonly viewer: string;
174 readonly limit: number;
175 /**
176 * Where to carry on from. Azure has no date filter for a pull request listing, so the only
177 * part of a cursor it can use is how many rows have already been handed over.
178 */
179 readonly cursor?: ProviderListCursor | undefined;
180 }) => Effect.Effect<
181 {
182 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
183 readonly truncated: boolean;
184 /** Raw Azure rows consumed to produce this page, including malformed rows. */
185 readonly cursorAdvance: number;
186 },
187 AzureDevOpsPullRequestCliError
188 >;
189
190 readonly getPullRequest: (input: {
191 readonly cwd: string;
192 readonly number: number;
193 }) => Effect.Effect<AzureDevOpsPullRequest, AzureDevOpsPullRequestCliError>;
194
195 /** Threads are not reachable through `az repos pr`, so they come from the REST API. */
196 readonly listThreads: (input: {
197 readonly cwd: string;
198 readonly location: AzureDevOpsRepositoryLocation;
199 readonly number: number;
200 }) => Effect.Effect<ReadonlyArray<PullRequestComment>, AzureDevOpsPullRequestCliError>;
201
202 /**
203 * The pushes a pull request has had, oldest first. Azure hangs the changed files off an
204 * iteration rather than off the pull request, so reading a diff starts here.
205 */
206 readonly listIterations: (input: {
207 readonly cwd: string;
208 readonly location: AzureDevOpsRepositoryLocation;
209 readonly number: number;
210 }) => Effect.Effect<ReadonlyArray<AzureDevOpsIteration>, AzureDevOpsPullRequestCliError>;
211
212 /**
213 * What one iteration changed, against the merge base rather than against the previous push,
214 * which is the whole of the pull request rather than the latest slice of it.
215 */
216 readonly listIterationChanges: (input: {
217 readonly cwd: string;
218 readonly location: AzureDevOpsRepositoryLocation;
219 readonly number: number;
220 readonly iterationId: number;
221 }) => Effect.Effect<AzureDevOpsIterationChanges, AzureDevOpsPullRequestCliError>;
222
223 /**
224 * One file's text at one commit. Azure has no diff route that carries content, so both sides
225 * of every changed file are read this way and the patch is made from them here.
226 */
227 readonly readItemContent: (input: {
228 readonly cwd: string;
229 readonly location: AzureDevOpsRepositoryLocation;
230 readonly path: string;
231 readonly commit: string;
232 }) => Effect.Effect<AzureDevOpsItemContent, AzureDevOpsPullRequestCliError>;
233
234 readonly runPullRequestAction: (input: {
235 readonly cwd: string;
236 readonly number: number;
237 readonly action: PullRequestAction;
238 readonly mergeMethod?: PullRequestMergeMethod;
239 }) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
240
241 /** Rewrites the pull request's own words, through the same command that moves it. */
242 readonly updatePullRequest: (input: {
243 readonly cwd: string;
244 readonly number: number;
245 readonly title?: string | undefined;
246 readonly body?: string | undefined;
247 }) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
248
249 /**
250 * Adds reviewers to a pull request, or takes them off it. `az repos pr reviewer` is the whole
251 * of what Azure offers here: it adds and removes named identities, and has no counterpart that
252 * says who could be named.
253 */
254 readonly setPullRequestReviewers: (input: {
255 readonly cwd: string;
256 readonly number: number;
257 readonly reviewers: ReadonlyArray<string>;
258 readonly requested: boolean;
259 }) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
260 }
261>()("t3/pullRequest/AzureDevOpsPullRequestCli") {}
262
263function statusArgs(state: PullRequestListState): ReadonlyArray<string> {
264 switch (state) {
265 case "open":
266 return ["--status", "active"];
267 case "merged":
268 return ["--status", "completed"];
269 case "closed":
270 return ["--status", "abandoned"];
271 case "all":
272 return ["--status", "all"];
273 }
274}
275
276function involvementArgs(input: {
277 readonly involvement: PullRequestInvolvement;
278 readonly viewer: string;
279}): ReadonlyArray<string> {
280 switch (input.involvement) {
281 case "authored":
282 return ["--creator", input.viewer];
283 case "reviewing":
284 return ["--reviewer", input.viewer];
285 case "all":
286 return [];
287 }
288}
289
290/**
291 * Azure moves a pull request by setting its state rather than by named commands: completing it
292 * is the merge, abandoning it is the close, and reactivating it is the reopen. Squashing is a
293 * completion option rather than a strategy of its own.
294 */
295function actionArgs(
296 action: PullRequestAction,
297 mergeMethod: PullRequestMergeMethod | undefined,
298): ReadonlyArray<string> {
299 switch (action) {
300 case "merge":
301 return ["--status", "completed", "--squash", mergeMethod === "squash" ? "true" : "false"];
302 // Auto-complete is Azure's own name for it: the pull request stays active and Azure completes
303 // it once its policies pass. The squash choice is stored with it, as it is for a merge now.
304 case "enable-auto-merge":
305 return [
306 "--auto-complete",
307 "true",
308 ...(mergeMethod === undefined
309 ? []
310 : ["--squash", mergeMethod === "squash" ? "true" : "false"]),
311 ];
312 case "disable-auto-merge":
313 return ["--auto-complete", "false"];
314 case "ready":
315 return ["--draft", "false"];
316 case "draft":
317 return ["--draft", "true"];
318 case "close":
319 return ["--status", "abandoned"];
320 // Never reached: this host does not declare the action, so nothing offers it.
321 case "update-branch":
322 return [];
323 case "reopen":
324 return ["--status", "active"];
325 // Never reached: this host does not declare the action, so the service refuses it first.
326 case "revert":
327 case "approve-workflows":
328 throw new Error(`Azure DevOps pull request action ${action} is unsupported`);
329 }
330}
331
332/**
333 * A reviewer Azure could be given: an email address, a display name or an identity guid, and
334 * nothing that starts with a dash. The dash is the whole point — these are argv, and a value that
335 * looks like a flag stops being a value.
336 */
337function isReviewerName(value: string): boolean {
338 const name = value.trim();
339 return name.length > 0 && !name.startsWith("-");
340}
341
342/** @public Service construction is part of the canonical Effect module API. */
343export const make = Effect.gen(function* () {
344 const azure = yield* AzureDevOpsCli.AzureDevOpsCli;
345
346 // Every command resolves the organization, project and repository from the checkout, which is
347 // what the rest of the Azure wrapper does. The remote takes three shapes and only `az` knows
348 // how to read all of them.
349 const detectArgs = ["--detect", "true"] as const;
350
351 const executeJson = (input: {
352 readonly cwd: string;
353 readonly args: ReadonlyArray<string>;
354 readonly maxOutputBytes?: number;
355 }) =>
356 azure.execute({
357 cwd: input.cwd,
358 args: [...input.args, "--only-show-errors", "--output", "json"],
359 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
360 });
361
362 /**
363 * A REST route reached through `az devops invoke`, which addresses it by area, resource and
364 * route parameters rather than by URL. Used in place of `az rest` because it signs in the way
365 * the azure-devops extension does: `az rest` mints its own token against the tenant `az`
366 * defaults to, and an organisation in any other tenant answers that with a sign-in page, which
367 * arrives here as unreadable output rather than as a failure.
368 */
369 const invoke = <A>(input: {
370 readonly cwd: string;
371 readonly operation: string;
372 readonly resource: string;
373 readonly routeParameters: ReadonlyArray<string>;
374 readonly queryParameters?: ReadonlyArray<string>;
375 readonly maxOutputBytes?: number;
376 readonly decode: (raw: string) => Result.Result<A, unknown>;
377 }): Effect.Effect<A, AzureDevOpsPullRequestCliError> =>
378 executeJson({
379 cwd: input.cwd,
380 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
381 args: [
382 "devops",
383 "invoke",
384 ...detectArgs,
385 "--area",
386 "git",
387 "--resource",
388 input.resource,
389 "--api-version",
390 REST_API_VERSION,
391 "--route-parameters",
392 ...input.routeParameters,
393 ...(input.queryParameters === undefined
394 ? []
395 : ["--query-parameters", ...input.queryParameters]),
396 ],
397 }).pipe(
398 Effect.flatMap((result) => {
399 const decoded = input.decode(result.stdout.trim());
400 return Result.isSuccess(decoded)
401 ? Effect.succeed(decoded.success)
402 : Effect.fail(
403 new AzureDevOpsPullRequestReadError({
404 command: "az",
405 cwd: input.cwd,
406 operation: input.operation,
407 cause: decoded.failure,
408 }),
409 );
410 }),
411 );
412
413 /**
414 * Azure names its own items with a leading slash, which the repository paths carried around
415 * here have had taken off so they match the patch and the viewed mark. Put it back on the way
416 * out, because the items route is documented in Azure's own spelling.
417 */
418 const toItemPath = (path: string) => (path.startsWith("/") ? path : `/${path}`);
419
420 const repositoryRoute = (location: AzureDevOpsRepositoryLocation): ReadonlyArray<string> => [
421 `project=${location.project}`,
422 `repositoryId=${location.repository}`,
423 ];
424
425 const pullRequestRoute = (input: {
426 readonly location: AzureDevOpsRepositoryLocation;
427 readonly number: number;
428 }): ReadonlyArray<string> => [
429 ...repositoryRoute(input.location),
430 `pullRequestId=${input.number}`,
431 ];
432
433 /**
434 * Azure pages by raw offset. Keep reading when malformed rows leave the decoded page short, and
435 * retain the raw count so the next public cursor skips every row this walk consumed.
436 */
437 const listPullRequestPage = (input: {
438 readonly cwd: string;
439 readonly repository: string;
440 readonly state: PullRequestListState;
441 readonly involvement: PullRequestInvolvement;
442 readonly viewer: string;
443 readonly limit: number;
444 readonly skip: number;
445 readonly cursorAdvance: number;
446 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
447 }): Effect.Effect<
448 {
449 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
450 readonly truncated: boolean;
451 readonly cursorAdvance: number;
452 },
453 AzureDevOpsPullRequestCliError
454 > => {
455 const remaining = input.limit - input.items.length;
456 const top = remaining + 1;
457 return executeJson({
458 cwd: input.cwd,
459 maxOutputBytes: PULL_REQUEST_LIST_MAX_OUTPUT_BYTES,
460 args: [
461 "repos",
462 "pr",
463 "list",
464 ...detectArgs,
465 "--repository",
466 input.repository,
467 ...statusArgs(input.state),
468 ...involvementArgs(input),
469 // A web link per row, which is the only url that needs no assembling.
470 "--include-links",
471 ...(input.skip === 0 ? [] : ["--skip", String(input.skip)]),
472 "--top",
473 String(top),
474 ],
475 }).pipe(
476 Effect.flatMap((result) => {
477 const raw = result.stdout.trim();
478 if (raw.length === 0) {
479 return Effect.succeed({
480 items: input.items,
481 truncated: false,
482 cursorAdvance: input.cursorAdvance,
483 });
484 }
485 const decoded = decodePullRequestListJson(raw);
486 if (!Result.isSuccess(decoded)) {
487 return Effect.fail(
488 new AzureDevOpsPullRequestReadError({
489 command: "az",
490 cwd: input.cwd,
491 operation: "listPullRequests",
492 cause: decoded.failure,
493 }),
494 );
495 }
496
497 const lastItemIndex = decoded.success.rawIndexes[remaining - 1];
498 if (lastItemIndex !== undefined) {
499 const consumed = lastItemIndex + 1;
500 return Effect.succeed({
501 items: [...input.items, ...decoded.success.items.slice(0, remaining)],
502 // A full raw response may have more rows even when malformed entries used the probe.
503 truncated: consumed < decoded.success.rawCount || decoded.success.rawCount === top,
504 cursorAdvance: input.cursorAdvance + consumed,
505 });
506 }
507
508 const items = [...input.items, ...decoded.success.items];
509 if (decoded.success.rawCount < top) {
510 return Effect.succeed({
511 items,
512 truncated: false,
513 cursorAdvance: input.cursorAdvance + decoded.success.rawCount,
514 });
515 }
516 return listPullRequestPage({
517 ...input,
518 skip: input.skip + decoded.success.rawCount,
519 cursorAdvance: input.cursorAdvance + decoded.success.rawCount,
520 items,
521 });
522 }),
523 );
524 };
525
526 return AzureDevOpsPullRequestCli.of({
527 getViewer: (input) =>
528 executeJson({ cwd: input.cwd, args: ["account", "show", "--query", "user"] }).pipe(
529 Effect.flatMap((result): Effect.Effect<string, AzureDevOpsPullRequestCliError> => {
530 // `--query user` narrows the payload to the account, so it is nested back under the
531 // key the decoder reads to keep one shape for the signed-in user.
532 const decoded = decodeViewerJson(`{"user":${result.stdout.trim() || "null"}}`);
533 if (!Result.isSuccess(decoded)) {
534 return Effect.fail(
535 new AzureDevOpsPullRequestReadError({
536 command: "az",
537 cwd: input.cwd,
538 operation: "getViewer",
539 cause: decoded.failure,
540 }),
541 );
542 }
543 return decoded.success === null
544 ? Effect.fail(new AzureDevOpsViewerUnavailableError({ command: "az", cwd: input.cwd }))
545 : Effect.succeed(decoded.success);
546 }),
547 ),
548
549 listPullRequests: (input) =>
550 listPullRequestPage({
551 cwd: input.cwd,
552 repository: input.repository,
553 state: input.state,
554 involvement: input.involvement,
555 viewer: input.viewer,
556 limit: input.limit,
557 // Azure counts rather than filters, so a slice carries on by stepping over every raw row
558 // the prior slice consumed. That is an offset into a list that can shift underneath it:
559 // a pull request opened between two slices moves everything down one, and the row on the
560 // seam is the one that pays for it.
561 skip: input.cursor?.delivered ?? 0,
562 cursorAdvance: 0,
563 items: [],
564 }),
565
566 getPullRequest: (input) =>
567 executeJson({
568 cwd: input.cwd,
569 args: ["repos", "pr", "show", ...detectArgs, "--id", String(input.number)],
570 }).pipe(
571 Effect.flatMap(
572 (result): Effect.Effect<AzureDevOpsPullRequest, AzureDevOpsPullRequestCliError> => {
573 const decoded = decodePullRequestJson(result.stdout.trim());
574 if (!Result.isSuccess(decoded)) {
575 return Effect.fail(
576 new AzureDevOpsPullRequestReadError({
577 command: "az",
578 cwd: input.cwd,
579 operation: "getPullRequest",
580 cause: decoded.failure,
581 }),
582 );
583 }
584 // Null means Azure answered with too little to place the pull request. Nothing
585 // failed underneath it, so it is its own outcome rather than a decode failure.
586 return decoded.success === null
587 ? Effect.fail(
588 new AzureDevOpsPullRequestIncompleteError({
589 command: "az",
590 cwd: input.cwd,
591 number: input.number,
592 }),
593 )
594 : Effect.succeed(decoded.success);
595 },
596 ),
597 ),
598
599 listThreads: (input) =>
600 invoke({
601 cwd: input.cwd,
602 operation: "listThreads",
603 resource: "pullRequestThreads",
604 routeParameters: pullRequestRoute(input),
605 maxOutputBytes: REVIEW_HISTORY_MAX_OUTPUT_BYTES,
606 decode: decodeThreadsJson,
607 }),
608
609 listIterations: (input) =>
610 invoke({
611 cwd: input.cwd,
612 operation: "listIterations",
613 resource: "pullRequestIterations",
614 routeParameters: pullRequestRoute(input),
615 maxOutputBytes: REVIEW_HISTORY_MAX_OUTPUT_BYTES,
616 decode: decodeIterationsJson,
617 }),
618
619 listIterationChanges: (input) => {
620 const page = (skip: number) =>
621 invoke({
622 cwd: input.cwd,
623 operation: "listIterationChanges",
624 resource: "pullRequestIterationChanges",
625 routeParameters: [...pullRequestRoute(input), `iterationId=${input.iterationId}`],
626 // Azure pages this route at 1000 entries by default; this is its own maximum per page,
627 // and it names where the next page starts rather than answering with the whole change.
628 queryParameters: [`$top=${CHANGE_ENTRIES_PER_PAGE}`, `$skip=${skip}`],
629 maxOutputBytes: CHANGE_ENTRIES_MAX_OUTPUT_BYTES,
630 decode: decodeIterationChangesJson,
631 });
632 const from = (
633 skip: number,
634 collected: ReadonlyArray<AzureDevOpsChangeEntry>,
635 ): Effect.Effect<AzureDevOpsIterationChanges, AzureDevOpsPullRequestCliError> =>
636 page(skip).pipe(
637 Effect.flatMap((answer) => {
638 const changes = [...collected, ...answer.changes];
639 // The last page names no page after it, and only that is the end of the change.
640 if (answer.nextSkip === null) return Effect.succeed({ changes, truncated: false });
641 // A page pointing at where the read already is would be followed forever, and one
642 // past the ceiling is a change nobody will read to the end of. Both stop the read
643 // and both say so, rather than presenting part of a change as the whole of it.
644 return answer.nextSkip <= skip || answer.nextSkip >= MAX_CHANGE_ENTRIES
645 ? Effect.succeed({ changes, truncated: true })
646 : from(answer.nextSkip, changes);
647 }),
648 );
649 return from(0, []);
650 },
651
652 readItemContent: (input) =>
653 invoke({
654 cwd: input.cwd,
655 operation: "readItemContent",
656 resource: "items",
657 routeParameters: repositoryRoute(input.location),
658 queryParameters: [
659 `path=${toItemPath(input.path)}`,
660 "versionDescriptor.versionType=commit",
661 `versionDescriptor.version=${input.commit}`,
662 "includeContent=true",
663 // Azure leaves `contentMetadata` out unless this is asked for, and with it goes its own
664 // word on whether the file is binary, which is the only reliable one, since a binary
665 // file arrives encoded rather than as the bytes it is on the host.
666 "includeContentMetadata=true",
667 // Without this Azure answers with the file's own bytes rather than with a JSON
668 // envelope, and `az devops invoke` refuses anything it cannot parse as JSON.
669 "$format=json",
670 ],
671 maxOutputBytes: ITEM_CONTENT_MAX_OUTPUT_BYTES,
672 decode: decodeItemContentJson,
673 }),
674
675 setPullRequestReviewers: (input) =>
676 input.reviewers.some((reviewer) => !isReviewerName(reviewer))
677 ? Effect.fail(new AzureDevOpsReviewerNameError({ command: "az", cwd: input.cwd }))
678 : azure
679 .execute({
680 cwd: input.cwd,
681 args: [
682 "repos",
683 "pr",
684 "reviewer",
685 input.requested ? "add" : "remove",
686 ...detectArgs,
687 "--id",
688 String(input.number),
689 // One `--reviewers` takes them all, because az reads the flag as a list and a
690 // second one would replace the first rather than add to it.
691 "--reviewers",
692 ...input.reviewers,
693 "--only-show-errors",
694 "--output",
695 "json",
696 ],
697 })
698 .pipe(Effect.asVoid),
699
700 runPullRequestAction: (input) =>
701 azure
702 .execute({
703 cwd: input.cwd,
704 args: [
705 "repos",
706 "pr",
707 "update",
708 ...detectArgs,
709 "--id",
710 String(input.number),
711 ...actionArgs(input.action, input.mergeMethod),
712 "--only-show-errors",
713 "--output",
714 "json",
715 ],
716 })
717 .pipe(Effect.asVoid),
718
719 updatePullRequest: (input) =>
720 azure
721 .execute({
722 cwd: input.cwd,
723 args: [
724 "repos",
725 "pr",
726 "update",
727 ...detectArgs,
728 "--id",
729 String(input.number),
730 // One argument rather than a flag and a value beside it: a description usually opens
731 // with a bullet, and az reads a dash in the next argv slot as a flag of its own.
732 // `--description` also takes several strings, and this keeps the whole text as one.
733 ...(input.title === undefined ? [] : [`--title=${input.title}`]),
734 ...(input.body === undefined ? [] : [`--description=${input.body}`]),
735 "--only-show-errors",
736 "--output",
737 "json",
738 ],
739 })
740 .pipe(Effect.asVoid),
741 });
742});
743
744export const layer = Layer.effect(AzureDevOpsPullRequestCli, make);