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 "./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 "@t3tools/source-control-core/server/PullRequestProvider";
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 could not name the signed-in account. Run `az login` and retry.";
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>()("@t3tools/source-control-azure-devops/server/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 // `az devops login` signs in with a personal access token, which `az account show` knows
548 // nothing about, and nothing in `az` prints whose token it is. `--creator me` is resolved
549 // by the extension itself, so the viewer's own pull request names them. Someone with none
550 // stays unnamed: `me` would read as nobody everywhere a row is compared with the viewer.
551 Effect.catchIf(
552 (error) => error._tag !== "AzureDevOpsCliUnavailableError",
553 () =>
554 executeJson({
555 cwd: input.cwd,
556 args: [
557 "repos",
558 "pr",
559 "list",
560 ...detectArgs,
561 "--creator",
562 "me",
563 "--status",
564 "all",
565 "--top",
566 "1",
567 ],
568 }).pipe(
569 Effect.flatMap((result): Effect.Effect<string, AzureDevOpsPullRequestCliError> => {
570 const decoded = decodePullRequestListJson(result.stdout.trim() || "[]");
571 const login = Result.isSuccess(decoded)
572 ? decoded.success.items[0]?.author?.login
573 : undefined;
574 return login === undefined
575 ? Effect.fail(
576 new AzureDevOpsViewerUnavailableError({ command: "az", cwd: input.cwd }),
577 )
578 : Effect.succeed(login);
579 }),
580 ),
581 ),
582 ),
583
584 listPullRequests: (input) =>
585 listPullRequestPage({
586 cwd: input.cwd,
587 repository: input.repository,
588 state: input.state,
589 involvement: input.involvement,
590 viewer: input.viewer,
591 limit: input.limit,
592 // Azure counts rather than filters, so a slice carries on by stepping over every raw row
593 // the prior slice consumed. That is an offset into a list that can shift underneath it:
594 // a pull request opened between two slices moves everything down one, and the row on the
595 // seam is the one that pays for it.
596 skip: input.cursor?.delivered ?? 0,
597 cursorAdvance: 0,
598 items: [],
599 }),
600
601 getPullRequest: (input) =>
602 executeJson({
603 cwd: input.cwd,
604 args: ["repos", "pr", "show", ...detectArgs, "--id", String(input.number)],
605 }).pipe(
606 Effect.flatMap(
607 (result): Effect.Effect<AzureDevOpsPullRequest, AzureDevOpsPullRequestCliError> => {
608 const decoded = decodePullRequestJson(result.stdout.trim());
609 if (!Result.isSuccess(decoded)) {
610 return Effect.fail(
611 new AzureDevOpsPullRequestReadError({
612 command: "az",
613 cwd: input.cwd,
614 operation: "getPullRequest",
615 cause: decoded.failure,
616 }),
617 );
618 }
619 // Null means Azure answered with too little to place the pull request. Nothing
620 // failed underneath it, so it is its own outcome rather than a decode failure.
621 return decoded.success === null
622 ? Effect.fail(
623 new AzureDevOpsPullRequestIncompleteError({
624 command: "az",
625 cwd: input.cwd,
626 number: input.number,
627 }),
628 )
629 : Effect.succeed(decoded.success);
630 },
631 ),
632 ),
633
634 listThreads: (input) =>
635 invoke({
636 cwd: input.cwd,
637 operation: "listThreads",
638 resource: "pullRequestThreads",
639 routeParameters: pullRequestRoute(input),
640 maxOutputBytes: REVIEW_HISTORY_MAX_OUTPUT_BYTES,
641 decode: decodeThreadsJson,
642 }),
643
644 listIterations: (input) =>
645 invoke({
646 cwd: input.cwd,
647 operation: "listIterations",
648 resource: "pullRequestIterations",
649 routeParameters: pullRequestRoute(input),
650 maxOutputBytes: REVIEW_HISTORY_MAX_OUTPUT_BYTES,
651 decode: decodeIterationsJson,
652 }),
653
654 listIterationChanges: (input) => {
655 const page = (skip: number) =>
656 invoke({
657 cwd: input.cwd,
658 operation: "listIterationChanges",
659 resource: "pullRequestIterationChanges",
660 routeParameters: [...pullRequestRoute(input), `iterationId=${input.iterationId}`],
661 // Azure pages this route at 1000 entries by default; this is its own maximum per page,
662 // and it names where the next page starts rather than answering with the whole change.
663 queryParameters: [`$top=${CHANGE_ENTRIES_PER_PAGE}`, `$skip=${skip}`],
664 maxOutputBytes: CHANGE_ENTRIES_MAX_OUTPUT_BYTES,
665 decode: decodeIterationChangesJson,
666 });
667 const from = (
668 skip: number,
669 collected: ReadonlyArray<AzureDevOpsChangeEntry>,
670 ): Effect.Effect<AzureDevOpsIterationChanges, AzureDevOpsPullRequestCliError> =>
671 page(skip).pipe(
672 Effect.flatMap((answer) => {
673 const changes = [...collected, ...answer.changes];
674 // The last page names no page after it, and only that is the end of the change.
675 if (answer.nextSkip === null) return Effect.succeed({ changes, truncated: false });
676 // A page pointing at where the read already is would be followed forever, and one
677 // past the ceiling is a change nobody will read to the end of. Both stop the read
678 // and both say so, rather than presenting part of a change as the whole of it.
679 return answer.nextSkip <= skip || answer.nextSkip >= MAX_CHANGE_ENTRIES
680 ? Effect.succeed({ changes, truncated: true })
681 : from(answer.nextSkip, changes);
682 }),
683 );
684 return from(0, []);
685 },
686
687 readItemContent: (input) =>
688 invoke({
689 cwd: input.cwd,
690 operation: "readItemContent",
691 resource: "items",
692 routeParameters: repositoryRoute(input.location),
693 queryParameters: [
694 `path=${toItemPath(input.path)}`,
695 "versionDescriptor.versionType=commit",
696 `versionDescriptor.version=${input.commit}`,
697 "includeContent=true",
698 // Azure leaves `contentMetadata` out unless this is asked for, and with it goes its own
699 // word on whether the file is binary, which is the only reliable one, since a binary
700 // file arrives encoded rather than as the bytes it is on the host.
701 "includeContentMetadata=true",
702 // Without this Azure answers with the file's own bytes rather than with a JSON
703 // envelope, and `az devops invoke` refuses anything it cannot parse as JSON.
704 "$format=json",
705 ],
706 maxOutputBytes: ITEM_CONTENT_MAX_OUTPUT_BYTES,
707 decode: decodeItemContentJson,
708 }),
709
710 setPullRequestReviewers: (input) =>
711 input.reviewers.some((reviewer) => !isReviewerName(reviewer))
712 ? Effect.fail(new AzureDevOpsReviewerNameError({ command: "az", cwd: input.cwd }))
713 : azure
714 .execute({
715 cwd: input.cwd,
716 args: [
717 "repos",
718 "pr",
719 "reviewer",
720 input.requested ? "add" : "remove",
721 ...detectArgs,
722 "--id",
723 String(input.number),
724 // One `--reviewers` takes them all, because az reads the flag as a list and a
725 // second one would replace the first rather than add to it.
726 "--reviewers",
727 ...input.reviewers,
728 "--only-show-errors",
729 "--output",
730 "json",
731 ],
732 })
733 .pipe(Effect.asVoid),
734
735 runPullRequestAction: (input) =>
736 azure
737 .execute({
738 cwd: input.cwd,
739 args: [
740 "repos",
741 "pr",
742 "update",
743 ...detectArgs,
744 "--id",
745 String(input.number),
746 ...actionArgs(input.action, input.mergeMethod),
747 "--only-show-errors",
748 "--output",
749 "json",
750 ],
751 })
752 .pipe(Effect.asVoid),
753
754 updatePullRequest: (input) =>
755 azure
756 .execute({
757 cwd: input.cwd,
758 args: [
759 "repos",
760 "pr",
761 "update",
762 ...detectArgs,
763 "--id",
764 String(input.number),
765 // One argument rather than a flag and a value beside it: a description usually opens
766 // with a bullet, and az reads a dash in the next argv slot as a flag of its own.
767 // `--description` also takes several strings, and this keeps the whole text as one.
768 ...(input.title === undefined ? [] : [`--title=${input.title}`]),
769 ...(input.body === undefined ? [] : [`--description=${input.body}`]),
770 "--only-show-errors",
771 "--output",
772 "json",
773 ],
774 })
775 .pipe(Effect.asVoid),
776 });
777});
778
779export const layer = Layer.effect(AzureDevOpsPullRequestCli, make);