Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Layer from "effect/Layer";
5import * as Result from "effect/Result";
6import * as Schema from "effect/Schema";
7import type {
8 PullRequestAction,
9 PullRequestCheck,
10 PullRequestComment,
11 PullRequestInvolvement,
12 PullRequestLabel,
13 PullRequestListState,
14 PullRequestMergeMethod,
15} from "@t3tools/contracts";
16
17import { sortChecks } from "@t3tools/source-control-core/server/pullRequestChecks";
18
19import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
20import { blobContent, readBlobZip } from "./azureDevOpsBlobZip.ts";
21import {
22 decodeItemContentJson,
23 decodeIterationChangesJson,
24 decodeIterationsJson,
25 decodeLabelsJson,
26 decodePolicyChecksJson,
27 decodePullRequestJson,
28 decodePullRequestListJson,
29 decodeThreadsJson,
30 decodeViewerJson,
31 type AzureDevOpsChangeEntry,
32 type AzureDevOpsItemContent,
33 type AzureDevOpsIteration,
34 type AzureDevOpsPullRequest,
35 type AzureDevOpsRepositoryLocation,
36} from "./azureDevOpsPullRequestJson.ts";
37import type { ProviderListCursor } from "@t3tools/source-control-core/server/PullRequestProvider";
38
39export class AzureDevOpsPullRequestReadError extends Schema.TaggedError<AzureDevOpsPullRequestReadError>()(
40 "AzureDevOpsPullRequestReadError",
41 {
42 command: Schema.Literal("az"),
43 cwd: Schema.String,
44 operation: Schema.String,
45 cause: Schema.Defect(),
46 },
47) {
48 get detail(): string {
49 return `Azure CLI returned an unreadable ${this.operation} response.`;
50 }
51
52 override get message(): string {
53 return `Azure CLI failed in ${this.operation}: ${this.detail}`;
54 }
55}
56
57export class AzureDevOpsViewerUnavailableError extends Schema.TaggedError<AzureDevOpsViewerUnavailableError>()(
58 "AzureDevOpsViewerUnavailableError",
59 {
60 command: Schema.Literal("az"),
61 cwd: Schema.String,
62 },
63) {
64 get detail(): string {
65 return "Azure CLI could not name the signed-in account. Run `az login` and retry.";
66 }
67
68 override get message(): string {
69 return `Azure CLI failed in getViewer: ${this.detail}`;
70 }
71}
72
73export class AzureDevOpsPullRequestIncompleteError extends Schema.TaggedError<AzureDevOpsPullRequestIncompleteError>()(
74 "AzureDevOpsPullRequestIncompleteError",
75 {
76 command: Schema.Literal("az"),
77 cwd: Schema.String,
78 number: Schema.Int,
79 },
80) {
81 get detail(): string {
82 return "Azure DevOps returned no branch or link for the pull request.";
83 }
84
85 override get message(): string {
86 return `Azure CLI failed in getPullRequest: ${this.detail}`;
87 }
88}
89
90export class AzureDevOpsReviewerNameError extends Schema.TaggedError<AzureDevOpsReviewerNameError>()(
91 "AzureDevOpsReviewerNameError",
92 {
93 command: Schema.Literal("az"),
94 cwd: Schema.String,
95 },
96) {
97 get detail(): string {
98 return "A reviewer is named by an email address or an identity id.";
99 }
100
101 override get message(): string {
102 return `Azure CLI failed in setPullRequestReviewers: ${this.detail}`;
103 }
104}
105
106export type AzureDevOpsPullRequestCliError =
107 | AzureDevOpsCli.AzureDevOpsCliError
108 | AzureDevOpsPullRequestReadError
109 | AzureDevOpsPullRequestIncompleteError
110 | AzureDevOpsReviewerNameError
111 | AzureDevOpsViewerUnavailableError;
112
113const REST_API_VERSION = "7.1";
114const PULL_REQUEST_LIST_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
115/** A 2,000-file page exceeds the default 1 MiB output budget. */
116const CHANGE_ENTRIES_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
117/** JSON escaping and base64 can exceed the decoded file's size. */
118const ITEM_CONTENT_MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
119/** A larger batch is left to per-file reads rather than held in memory at once. */
120const BLOB_ARCHIVE_MAX_BYTES = 64 * 1024 * 1024;
121/** Matches what a per-file read could carry. */
122const BLOB_MAX_BYTES = ITEM_CONTENT_MAX_OUTPUT_BYTES;
123/** Blobs past this, together, are left to per-file reads, which hold a few at a time. */
124const BLOB_BATCH_MAX_BYTES = 16 * 1024 * 1024;
125const BLOB_ID = /^[0-9a-f]{40}$/i;
126/** Review history is unpaged and independent of diff size. */
127const REVIEW_HISTORY_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
128
129const POLICY_EVALUATIONS_PER_PAGE = 100;
130const MAX_POLICY_EVALUATIONS = 1000;
131
132/** Azure's iteration-change page limit. */
133const CHANGE_ENTRIES_PER_PAGE = 2000;
134
135/** Count raw entries, including folders and malformed rows. */
136const MAX_CHANGE_ENTRIES = 10_000;
137
138export interface AzureDevOpsIterationChanges {
139 readonly changes: ReadonlyArray<AzureDevOpsChangeEntry>;
140 readonly truncated: boolean;
141}
142
143export class AzureDevOpsPullRequestCli extends Context.Service<
144 AzureDevOpsPullRequestCli,
145 {
146 readonly getViewer: (input: {
147 readonly cwd: string;
148 }) => Effect.Effect<string, AzureDevOpsPullRequestCliError>;
149
150 readonly listPullRequests: (input: {
151 readonly cwd: string;
152 readonly repository: string;
153 readonly state: PullRequestListState;
154 readonly involvement: PullRequestInvolvement;
155 readonly viewer: string;
156 readonly limit: number;
157 /** Matched by `--creator`, which takes the email a row shows as its login. */
158 readonly author?: string | undefined;
159 /**
160 * Where to carry on from. Azure has no date filter for a pull request listing, so the only
161 * part of a cursor it can use is how many rows have already been handed over.
162 */
163 readonly cursor?: ProviderListCursor | undefined;
164 }) => Effect.Effect<
165 {
166 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
167 readonly truncated: boolean;
168 readonly cursorAdvance: number;
169 },
170 AzureDevOpsPullRequestCliError
171 >;
172
173 readonly getPullRequest: (input: {
174 readonly cwd: string;
175 readonly number: number;
176 }) => Effect.Effect<AzureDevOpsPullRequest, AzureDevOpsPullRequestCliError>;
177
178 readonly listPolicyChecks: (input: {
179 readonly cwd: string;
180 readonly number: number;
181 /** Azure holds builds back on a draft, which reads the same as a build about to start. */
182 readonly isDraft: boolean;
183 }) => Effect.Effect<ReadonlyArray<PullRequestCheck>, AzureDevOpsPullRequestCliError>;
184
185 readonly listThreads: (input: {
186 readonly cwd: string;
187 readonly location: AzureDevOpsRepositoryLocation;
188 readonly number: number;
189 }) => Effect.Effect<ReadonlyArray<PullRequestComment>, AzureDevOpsPullRequestCliError>;
190
191 /** `az repos pr show` returns null labels, so the detail reads them here. */
192 readonly listLabels: (input: {
193 readonly cwd: string;
194 readonly location: AzureDevOpsRepositoryLocation;
195 readonly number: number;
196 }) => Effect.Effect<ReadonlyArray<PullRequestLabel>, AzureDevOpsPullRequestCliError>;
197
198 readonly listIterations: (input: {
199 readonly cwd: string;
200 readonly location: AzureDevOpsRepositoryLocation;
201 readonly number: number;
202 }) => Effect.Effect<ReadonlyArray<AzureDevOpsIteration>, AzureDevOpsPullRequestCliError>;
203
204 /** Changes cover the whole PR from its merge base. */
205 readonly listIterationChanges: (input: {
206 readonly cwd: string;
207 readonly location: AzureDevOpsRepositoryLocation;
208 readonly number: number;
209 readonly iterationId: number;
210 }) => Effect.Effect<AzureDevOpsIterationChanges, AzureDevOpsPullRequestCliError>;
211
212 readonly readItemContent: (input: {
213 readonly cwd: string;
214 readonly location: AzureDevOpsRepositoryLocation;
215 readonly path: string;
216 readonly commit: string;
217 }) => Effect.Effect<AzureDevOpsItemContent, AzureDevOpsPullRequestCliError>;
218
219 /**
220 * Many files in one `az` run, by blob id, keyed by lowercase id. A blob only Azure's item read
221 * decodes faithfully, or one too large to carry, is left out.
222 */
223 readonly readBlobs: (input: {
224 readonly cwd: string;
225 readonly location: AzureDevOpsRepositoryLocation;
226 readonly objectIds: ReadonlyArray<string>;
227 }) => Effect.Effect<
228 ReadonlyMap<string, AzureDevOpsItemContent>,
229 AzureDevOpsPullRequestCliError
230 >;
231
232 readonly runPullRequestAction: (input: {
233 readonly cwd: string;
234 readonly number: number;
235 readonly action: PullRequestAction;
236 readonly mergeMethod?: PullRequestMergeMethod;
237 }) => Effect.Effect<AzureDevOpsPullRequest | void, AzureDevOpsPullRequestCliError>;
238
239 readonly updatePullRequest: (input: {
240 readonly cwd: string;
241 readonly number: number;
242 readonly title?: string | undefined;
243 readonly body?: string | undefined;
244 }) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
245
246 readonly setPullRequestReviewers: (input: {
247 readonly cwd: string;
248 readonly number: number;
249 readonly reviewers: ReadonlyArray<string>;
250 readonly requested: boolean;
251 }) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
252 }
253>()("@t3tools/source-control-azure-devops/server/AzureDevOpsPullRequestCli") {}
254
255function statusArgs(state: PullRequestListState): ReadonlyArray<string> {
256 switch (state) {
257 case "open":
258 return ["--status", "active"];
259 case "merged":
260 return ["--status", "completed"];
261 case "closed":
262 return ["--status", "abandoned"];
263 case "all":
264 return ["--status", "all"];
265 }
266}
267
268function involvementFilters(input: {
269 readonly involvement: PullRequestInvolvement;
270 readonly viewer: string;
271 readonly author?: string | undefined;
272}): ReadonlyArray<readonly [option: string, value: string]> {
273 const author = input.author === undefined ? [] : [["--creator", input.author] as const];
274 switch (input.involvement) {
275 case "authored":
276 return [["--creator", input.viewer]];
277 case "reviewing":
278 return [["--reviewer", input.viewer], ...author];
279 case "all":
280 return author;
281 }
282}
283
284function actionArgs(
285 action: PullRequestAction,
286 mergeMethod: PullRequestMergeMethod | undefined,
287): ReadonlyArray<string> {
288 switch (action) {
289 case "merge":
290 return ["--status", "completed", "--squash", mergeMethod === "squash" ? "true" : "false"];
291 case "enable-auto-merge":
292 return [
293 "--auto-complete",
294 "true",
295 ...(mergeMethod === undefined
296 ? []
297 : ["--squash", mergeMethod === "squash" ? "true" : "false"]),
298 ];
299 case "disable-auto-merge":
300 return ["--auto-complete", "false"];
301 case "ready":
302 return ["--draft", "false"];
303 case "draft":
304 return ["--draft", "true"];
305 case "close":
306 return ["--status", "abandoned"];
307 case "update-branch":
308 return [];
309 case "reopen":
310 return ["--status", "active"];
311 case "revert":
312 case "approve-workflows":
313 case "delete-branch":
314 throw new Error(`Azure DevOps pull request action ${action} is unsupported`);
315 }
316}
317
318function isReviewerName(value: string): boolean {
319 const name = value.trim();
320 return name.length > 0 && !name.startsWith("-");
321}
322
323/** @public */
324export const make = Effect.gen(function* () {
325 const azure = yield* AzureDevOpsCli.AzureDevOpsCli;
326 const fileSystem = yield* FileSystem.FileSystem;
327
328 const detectArgs = ["--detect", "true"] as const;
329
330 const executeJson = (input: {
331 readonly cwd: string;
332 readonly args: ReadonlyArray<string>;
333 readonly maxOutputBytes?: number;
334 readonly stdin?: string | undefined;
335 }) =>
336 azure.execute({
337 cwd: input.cwd,
338 args: [...input.args, "--only-show-errors", "--output", "json"],
339 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
340 ...(input.stdin === undefined ? {} : { stdin: input.stdin }),
341 });
342
343 /**
344 * `textOption`s for one command. az has one stdin, so each further value starting with `@`
345 * goes in a file of its own, which az reads in place of the `@path` it was handed.
346 */
347 const textOptions = Effect.fn("AzureDevOpsPullRequestCli.textOptions")(function* (
348 cwd: string,
349 operation: string,
350 values: ReadonlyArray<readonly [option: string, value: string]>,
351 ) {
352 const options = values.map(([option, value]) => ({
353 option,
354 ...AzureDevOpsCli.textOption(option, value),
355 }));
356 const piped = options.find((option) => option.stdin !== undefined);
357 const filed = options.filter((option) => option.stdin !== undefined && option !== piped);
358 const readFailure = (cause: unknown) =>
359 new AzureDevOpsPullRequestReadError({ command: "az", cwd, operation, cause });
360 const directory =
361 filed.length === 0
362 ? ""
363 : yield* fileSystem
364 .makeTempDirectoryScoped({ prefix: "t3-azure-values-" })
365 .pipe(Effect.mapError(readFailure));
366 const fileOf = (option: (typeof options)[number]) => {
367 const index = filed.indexOf(option);
368 return index === -1 ? null : `${directory}/${index}`;
369 };
370 for (const option of filed) {
371 yield* fileSystem
372 .writeFileString(`${fileOf(option)}`, option.stdin ?? "")
373 .pipe(Effect.mapError(readFailure));
374 }
375 return {
376 args: options.map((option) => {
377 const file = fileOf(option);
378 return file === null ? option.arg : `${option.option}=@${file}`;
379 }),
380 stdin: piped?.stdin,
381 };
382 });
383
384 /** Use the extension's credentials; `az rest` uses the default tenant. */
385 const invoke = <A>(input: {
386 readonly cwd: string;
387 readonly operation: string;
388 readonly resource: string;
389 readonly routeParameters: ReadonlyArray<string>;
390 readonly queryParameters?: ReadonlyArray<string>;
391 readonly maxOutputBytes?: number;
392 readonly decode: (raw: string) => Result.Result<A, unknown>;
393 }): Effect.Effect<A, AzureDevOpsPullRequestCliError> =>
394 executeJson({
395 cwd: input.cwd,
396 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
397 args: [
398 "devops",
399 "invoke",
400 ...detectArgs,
401 "--area",
402 "git",
403 "--resource",
404 input.resource,
405 "--api-version",
406 REST_API_VERSION,
407 "--route-parameters",
408 ...input.routeParameters,
409 ...(input.queryParameters === undefined
410 ? []
411 : ["--query-parameters", ...input.queryParameters]),
412 ],
413 }).pipe(
414 Effect.flatMap((result) => {
415 const decoded = input.decode(result.stdout.trim());
416 return Result.isSuccess(decoded)
417 ? Effect.succeed(decoded.success)
418 : Effect.fail(
419 new AzureDevOpsPullRequestReadError({
420 command: "az",
421 cwd: input.cwd,
422 operation: input.operation,
423 cause: decoded.failure,
424 }),
425 );
426 }),
427 );
428
429 /** Azure's items route requires a leading slash. */
430 const toItemPath = (path: string) => (path.startsWith("/") ? path : `/${path}`);
431
432 const repositoryRoute = (location: AzureDevOpsRepositoryLocation): ReadonlyArray<string> => [
433 `project=${location.project}`,
434 `repositoryId=${location.repository}`,
435 ];
436
437 const pullRequestRoute = (input: {
438 readonly location: AzureDevOpsRepositoryLocation;
439 readonly number: number;
440 }): ReadonlyArray<string> => [
441 ...repositoryRoute(input.location),
442 `pullRequestId=${input.number}`,
443 ];
444
445 /** Decoding can shorten a non-final page; advance by raw rows. */
446 const listPullRequestPage = (input: {
447 readonly cwd: string;
448 readonly repository: string;
449 readonly state: PullRequestListState;
450 readonly involvement: PullRequestInvolvement;
451 readonly viewer: string;
452 readonly author?: string | undefined;
453 readonly limit: number;
454 readonly skip: number;
455 readonly cursorAdvance: number;
456 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
457 }): Effect.Effect<
458 {
459 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
460 readonly truncated: boolean;
461 readonly cursorAdvance: number;
462 },
463 AzureDevOpsPullRequestCliError
464 > => {
465 const remaining = input.limit - input.items.length;
466 const top = remaining + 1;
467 // The name, viewer and author filter come from a remote, Azure and the user.
468 return textOptions(input.cwd, "listPullRequests", [
469 ["--repository", input.repository],
470 ...involvementFilters(input),
471 ]).pipe(
472 Effect.flatMap((filters) =>
473 executeJson({
474 cwd: input.cwd,
475 maxOutputBytes: PULL_REQUEST_LIST_MAX_OUTPUT_BYTES,
476 stdin: filters.stdin,
477 args: [
478 "repos",
479 "pr",
480 "list",
481 ...detectArgs,
482 ...filters.args,
483 ...statusArgs(input.state),
484 "--include-links",
485 ...(input.skip === 0 ? [] : ["--skip", String(input.skip)]),
486 "--top",
487 String(top),
488 ],
489 }),
490 ),
491 // Scoped to the one az call that reads the files.
492 Effect.scoped,
493 Effect.flatMap((result) => {
494 const raw = result.stdout.trim();
495 if (raw.length === 0) {
496 return Effect.succeed({
497 items: input.items,
498 truncated: false,
499 cursorAdvance: input.cursorAdvance,
500 });
501 }
502 const decoded = decodePullRequestListJson(raw);
503 if (!Result.isSuccess(decoded)) {
504 return Effect.fail(
505 new AzureDevOpsPullRequestReadError({
506 command: "az",
507 cwd: input.cwd,
508 operation: "listPullRequests",
509 cause: decoded.failure,
510 }),
511 );
512 }
513
514 const lastItemIndex = decoded.success.rawIndexes[remaining - 1];
515 if (lastItemIndex !== undefined) {
516 const consumed = lastItemIndex + 1;
517 return Effect.succeed({
518 items: [...input.items, ...decoded.success.items.slice(0, remaining)],
519 truncated: consumed < decoded.success.rawCount || decoded.success.rawCount === top,
520 cursorAdvance: input.cursorAdvance + consumed,
521 });
522 }
523
524 const items = [...input.items, ...decoded.success.items];
525 if (decoded.success.rawCount < top) {
526 return Effect.succeed({
527 items,
528 truncated: false,
529 cursorAdvance: input.cursorAdvance + decoded.success.rawCount,
530 });
531 }
532 return listPullRequestPage({
533 ...input,
534 skip: input.skip + decoded.success.rawCount,
535 cursorAdvance: input.cursorAdvance + decoded.success.rawCount,
536 items,
537 });
538 }),
539 );
540 };
541
542 return AzureDevOpsPullRequestCli.of({
543 getViewer: Effect.fn("AzureDevOpsPullRequestCli.getViewer")(function (input) {
544 return executeJson({ cwd: input.cwd, args: ["account", "show", "--query", "user"] }).pipe(
545 Effect.flatMap((result): Effect.Effect<string, AzureDevOpsPullRequestCliError> => {
546 const decoded = decodeViewerJson(`{"user":${result.stdout.trim() || "null"}}`);
547 if (!Result.isSuccess(decoded)) {
548 return Effect.fail(
549 new AzureDevOpsPullRequestReadError({
550 command: "az",
551 cwd: input.cwd,
552 operation: "getViewer",
553 cause: decoded.failure,
554 }),
555 );
556 }
557 return decoded.success === null
558 ? Effect.fail(new AzureDevOpsViewerUnavailableError({ command: "az", cwd: input.cwd }))
559 : Effect.succeed(decoded.success);
560 }),
561 // `az account show` cannot identify PAT logins; the extension resolves `--creator me`.
562 Effect.catchIf(
563 (error) => error._tag !== "AzureDevOpsCliUnavailableError",
564 () =>
565 executeJson({
566 cwd: input.cwd,
567 args: [
568 "repos",
569 "pr",
570 "list",
571 ...detectArgs,
572 "--creator",
573 "me",
574 "--status",
575 "all",
576 "--top",
577 "1",
578 ],
579 }).pipe(
580 Effect.flatMap((result): Effect.Effect<string, AzureDevOpsPullRequestCliError> => {
581 const decoded = decodePullRequestListJson(result.stdout.trim() || "[]");
582 const login = Result.isSuccess(decoded)
583 ? decoded.success.items[0]?.author?.login
584 : undefined;
585 return login === undefined
586 ? Effect.fail(
587 new AzureDevOpsViewerUnavailableError({ command: "az", cwd: input.cwd }),
588 )
589 : Effect.succeed(login);
590 }),
591 ),
592 ),
593 );
594 }),
595
596 listPullRequests: Effect.fn("AzureDevOpsPullRequestCli.listPullRequests")(function (input) {
597 return listPullRequestPage({
598 cwd: input.cwd,
599 repository: input.repository,
600 state: input.state,
601 involvement: input.involvement,
602 viewer: input.viewer,
603 author: input.author,
604 limit: input.limit,
605 skip: input.cursor?.delivered ?? 0,
606 cursorAdvance: 0,
607 items: [],
608 });
609 }),
610
611 getPullRequest: Effect.fn("AzureDevOpsPullRequestCli.getPullRequest")(function (input) {
612 return executeJson({
613 cwd: input.cwd,
614 args: ["repos", "pr", "show", ...detectArgs, "--id", String(input.number)],
615 }).pipe(
616 Effect.flatMap(
617 (result): Effect.Effect<AzureDevOpsPullRequest, AzureDevOpsPullRequestCliError> => {
618 const decoded = decodePullRequestJson(result.stdout.trim());
619 if (!Result.isSuccess(decoded)) {
620 return Effect.fail(
621 new AzureDevOpsPullRequestReadError({
622 command: "az",
623 cwd: input.cwd,
624 operation: "getPullRequest",
625 cause: decoded.failure,
626 }),
627 );
628 }
629 return decoded.success === null
630 ? Effect.fail(
631 new AzureDevOpsPullRequestIncompleteError({
632 command: "az",
633 cwd: input.cwd,
634 number: input.number,
635 }),
636 )
637 : Effect.succeed(decoded.success);
638 },
639 ),
640 );
641 }),
642
643 listPolicyChecks: Effect.fn("AzureDevOpsPullRequestCli.listPolicyChecks")(function* (input) {
644 const unreadable = (cause: unknown) =>
645 new AzureDevOpsPullRequestReadError({
646 command: "az",
647 cwd: input.cwd,
648 operation: "listPolicyChecks",
649 cause,
650 });
651 const checks: PullRequestCheck[] = [];
652 for (let skip = 0; skip < MAX_POLICY_EVALUATIONS; skip += POLICY_EVALUATIONS_PER_PAGE) {
653 const result = yield* executeJson({
654 cwd: input.cwd,
655 args: [
656 "repos",
657 "pr",
658 "policy",
659 "list",
660 ...detectArgs,
661 "--id",
662 String(input.number),
663 "--top",
664 String(POLICY_EVALUATIONS_PER_PAGE),
665 "--skip",
666 String(skip),
667 ],
668 });
669 if (result.stdoutTruncated) return yield* unreadable("Policy output was truncated");
670 const page = decodePolicyChecksJson(result.stdout.trim(), { isDraft: input.isDraft });
671 if (!Result.isSuccess(page)) return yield* unreadable(page.failure);
672 checks.push(...page.success.checks);
673 if (page.success.rawCount < POLICY_EVALUATIONS_PER_PAGE) return sortChecks(checks);
674 }
675 return yield* unreadable("Policy evaluations exceeded the read limit");
676 }),
677
678 listThreads: Effect.fn("AzureDevOpsPullRequestCli.listThreads")(function (input) {
679 return invoke({
680 cwd: input.cwd,
681 operation: "listThreads",
682 resource: "pullRequestThreads",
683 routeParameters: pullRequestRoute(input),
684 maxOutputBytes: REVIEW_HISTORY_MAX_OUTPUT_BYTES,
685 decode: decodeThreadsJson,
686 });
687 }),
688
689 listLabels: Effect.fn("AzureDevOpsPullRequestCli.listLabels")(function (input) {
690 return invoke({
691 cwd: input.cwd,
692 operation: "listLabels",
693 resource: "pullRequestLabels",
694 routeParameters: pullRequestRoute(input),
695 decode: decodeLabelsJson,
696 });
697 }),
698
699 listIterations: Effect.fn("AzureDevOpsPullRequestCli.listIterations")(function (input) {
700 return invoke({
701 cwd: input.cwd,
702 operation: "listIterations",
703 resource: "pullRequestIterations",
704 routeParameters: pullRequestRoute(input),
705 maxOutputBytes: REVIEW_HISTORY_MAX_OUTPUT_BYTES,
706 decode: decodeIterationsJson,
707 });
708 }),
709
710 listIterationChanges: Effect.fn("AzureDevOpsPullRequestCli.listIterationChanges")(
711 function (input) {
712 const page = (skip: number) =>
713 invoke({
714 cwd: input.cwd,
715 operation: "listIterationChanges",
716 resource: "pullRequestIterationChanges",
717 routeParameters: [...pullRequestRoute(input), `iterationId=${input.iterationId}`],
718 queryParameters: [`$top=${CHANGE_ENTRIES_PER_PAGE}`, `$skip=${skip}`],
719 maxOutputBytes: CHANGE_ENTRIES_MAX_OUTPUT_BYTES,
720 decode: decodeIterationChangesJson,
721 });
722 const from = (
723 skip: number,
724 collected: ReadonlyArray<AzureDevOpsChangeEntry>,
725 ): Effect.Effect<AzureDevOpsIterationChanges, AzureDevOpsPullRequestCliError> =>
726 page(skip).pipe(
727 Effect.flatMap((answer) => {
728 const changes = [...collected, ...answer.changes];
729 if (answer.nextSkip === null) return Effect.succeed({ changes, truncated: false });
730 return answer.nextSkip <= skip || answer.nextSkip >= MAX_CHANGE_ENTRIES
731 ? Effect.succeed({ changes, truncated: true })
732 : from(answer.nextSkip, changes);
733 }),
734 );
735 return from(0, []);
736 },
737 ),
738
739 readBlobs: Effect.fn("AzureDevOpsPullRequestCli.readBlobs")(function* (input) {
740 const requested = new Map<string, string>();
741 // Azure states ids in uppercase and names entries in lowercase.
742 for (const id of input.objectIds) {
743 const key = id.toLowerCase();
744 if (BLOB_ID.test(id) && !requested.has(key)) requested.set(key, id);
745 }
746 if (requested.size === 0) return new Map<string, AzureDevOpsItemContent>();
747 const readFailure = (cause: unknown) =>
748 new AzureDevOpsPullRequestReadError({
749 command: "az",
750 cwd: input.cwd,
751 operation: "readBlobs",
752 cause,
753 });
754 return yield* Effect.scoped(
755 Effect.gen(function* () {
756 const directory = yield* fileSystem
757 .makeTempDirectoryScoped({ prefix: "t3-azure-blobs-" })
758 .pipe(Effect.mapError(readFailure));
759 const request = `${directory}/ids.json`;
760 // invoke refuses to overwrite its output, so the archive gets a name nothing holds yet.
761 const archive = `${directory}/blobs.zip`;
762 yield* fileSystem
763 .writeFileString(
764 request,
765 `[${[...requested.values()].map((id) => `"${id}"`).join(",")}]`,
766 )
767 .pipe(Effect.mapError(readFailure));
768 yield* azure.execute({
769 cwd: input.cwd,
770 args: [
771 "devops",
772 "invoke",
773 ...detectArgs,
774 "--area",
775 "git",
776 "--resource",
777 "blobs",
778 "--api-version",
779 REST_API_VERSION,
780 "--route-parameters",
781 ...repositoryRoute(input.location),
782 "--http-method",
783 "POST",
784 "--in-file",
785 request,
786 "--accept-media-type",
787 "application/zip",
788 "--out-file",
789 archive,
790 "--only-show-errors",
791 ],
792 });
793 const size = yield* fileSystem.stat(archive).pipe(
794 Effect.map((info) => Number(info.size)),
795 Effect.mapError(readFailure),
796 );
797 const contents = new Map<string, AzureDevOpsItemContent>();
798 if (size > BLOB_ARCHIVE_MAX_BYTES) return contents;
799 const zip = yield* fileSystem.readFile(archive).pipe(Effect.mapError(readFailure));
800 const entries = readBlobZip(zip, BLOB_MAX_BYTES, BLOB_BATCH_MAX_BYTES);
801 if (entries === null) return yield* readFailure("Azure returned an unreadable archive.");
802 for (const [id, bytes] of entries) {
803 const content = requested.has(id) ? blobContent(bytes) : null;
804 if (content !== null) contents.set(id, content);
805 }
806 return contents;
807 }),
808 );
809 }),
810
811 readItemContent: Effect.fn("AzureDevOpsPullRequestCli.readItemContent")(function (input) {
812 return invoke({
813 cwd: input.cwd,
814 operation: "readItemContent",
815 resource: "items",
816 routeParameters: repositoryRoute(input.location),
817 queryParameters: [
818 // `az devops invoke` does not escape query values, so `#` or `&` in a path would truncate it.
819 `path=${encodeURIComponent(toItemPath(input.path))}`,
820 "versionDescriptor.versionType=commit",
821 `versionDescriptor.version=${input.commit}`,
822 "includeContent=true",
823 // Encoded content cannot identify binaries; request Azure's binary flag.
824 "includeContentMetadata=true",
825 // `az devops invoke` requires JSON; otherwise Azure returns raw file bytes.
826 "$format=json",
827 ],
828 maxOutputBytes: ITEM_CONTENT_MAX_OUTPUT_BYTES,
829 decode: decodeItemContentJson,
830 });
831 }),
832
833 setPullRequestReviewers: Effect.fn("AzureDevOpsPullRequestCli.setPullRequestReviewers")(
834 function* (input) {
835 if (input.reviewers.some((reviewer) => !isReviewerName(reviewer))) {
836 return yield* new AzureDevOpsReviewerNameError({ command: "az", cwd: input.cwd });
837 }
838 return yield* azure
839 .execute({
840 cwd: input.cwd,
841 args: [
842 "repos",
843 "pr",
844 "reviewer",
845 input.requested ? "add" : "remove",
846 ...detectArgs,
847 "--id",
848 String(input.number),
849 // Repeating `--reviewers` replaces the earlier list.
850 "--reviewers",
851 ...input.reviewers,
852 "--only-show-errors",
853 "--output",
854 "json",
855 ],
856 })
857 .pipe(Effect.asVoid);
858 },
859 ),
860
861 runPullRequestAction: Effect.fn("AzureDevOpsPullRequestCli.runPullRequestAction")(
862 function (input) {
863 return azure
864 .execute({
865 cwd: input.cwd,
866 args: [
867 "repos",
868 "pr",
869 "update",
870 ...detectArgs,
871 "--id",
872 String(input.number),
873 ...actionArgs(input.action, input.mergeMethod),
874 "--only-show-errors",
875 "--output",
876 "json",
877 ],
878 })
879 .pipe(
880 // `pr update` prints the pull request it left, in the shape `pr show` prints.
881 Effect.map((result) => {
882 const decoded = decodePullRequestJson(result.stdout.trim());
883 return Result.isSuccess(decoded) ? (decoded.success ?? undefined) : undefined;
884 }),
885 );
886 },
887 ),
888
889 updatePullRequest: Effect.fn("AzureDevOpsPullRequestCli.updatePullRequest")(function (input) {
890 // One argv entry preserves leading dashes and multi-string descriptions.
891 const fields = [
892 ...(input.title === undefined ? [] : [AzureDevOpsCli.textOption("--title", input.title)]),
893 ...(input.body === undefined
894 ? []
895 : [AzureDevOpsCli.textOption("--description", input.body)]),
896 ];
897 // az has one stdin, so each value read from it needs its own call.
898 const batches =
899 fields.filter((field) => field.stdin !== undefined).length > 1
900 ? fields.map((field) => [field])
901 : [fields];
902 return Effect.forEach(
903 batches,
904 (batch) => {
905 const stdin = batch.find((field) => field.stdin !== undefined)?.stdin;
906 return azure.execute({
907 cwd: input.cwd,
908 args: [
909 "repos",
910 "pr",
911 "update",
912 ...detectArgs,
913 "--id",
914 String(input.number),
915 ...batch.map((field) => field.arg),
916 "--only-show-errors",
917 "--output",
918 "json",
919 ],
920 ...(stdin === undefined ? {} : { stdin }),
921 });
922 },
923 { discard: true },
924 );
925 }),
926 });
927});
928
929export const layer = Layer.effect(AzureDevOpsPullRequestCli, make);