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

AzureDevOpsPullRequestCli.ts

845 lines28.8 KB

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