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

GitHubPullRequestProvider.ts

759 lines28.0 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { removeAgentCredits } from "@t3tools/source-control-core/server/mergeMessage";
3import * as Cache from "effect/Cache";
4import * as Duration from "effect/Duration";
5import * as Equal from "effect/Equal";
6import * as Exit from "effect/Exit";
7import * as Hash from "effect/Hash";
8import * as Effect from "effect/Effect";
9import type {
10 PullRequestActor,
11 PullRequestCapabilities,
12 PullRequestCheck,
13 PullRequestReaction,
14 PullRequestViewerPermissions,
15} from "@t3tools/contracts";
16​
17import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
18import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts";
19import {
20 PullRequestProviderError,
21 type PullRequestProviderFailure,
22 type ProviderChangeRequestActivity,
23 type ProviderChangeRequestDetail,
24 type PullRequestProviderApi,
25 type ProviderRepositoryRef,
26} from "@t3tools/source-control-core/server/PullRequestProvider";
27import type {
28 GitHubRepositoryAccess,
29 GitHubViewerAccess,
30 GitHubWorkflowRunApproval,
31} from "./gitHubPullRequestJson.ts";
32import { definition } from "../shared/definition.ts";
33​
34const CAPABILITIES: PullRequestCapabilities = {
35 diff: true,
36 comment: true,
37 actions: [...definition.changeRequestActions],
38 mergeMethods: ["merge", "squash", "rebase"],
39 deleteBranch: true,
40 updateMethods: ["merge", "rebase"],
41 search: true,
42 reactions: true,
43 viewedFiles: "host",
44 review: {
45 inlineComment: true,
46 rangeComment: true,
47 reply: true,
48 resolve: true,
49 verdicts: ["comment", "approve", "request-changes"],
50 },
51 reviewers: { request: true, listCandidates: true },
52 edit: { changeRequest: true, comment: true },
53 stacks: true,
54 stackActions: true,
55 labels: true,
56 // Statuses and check runs land on the head commit itself and are read whole, so an empty list
57 // after a push is CI that never started rather than a read that saw nothing.
58 checksAlwaysReport: true,
59};
60​
61const UNAVAILABLE_REQUIREMENT = {
62 missing:
63 "No GitHub credential on the server. Set GH_TOKEN, or install the GitHub CLI (https://cli.github.com/) and run `gh auth login`.",
64 unauthenticated:
65 "GitHub has no working credential for this host. Run `gh auth login`, or check the account and hosts in Settings → Source Control.",
66};
67​
68/**
69 * Asking somebody else for a review needs write access, which is the one thing here an author
70 * cannot do on their own pull request: GitHub shows an outside contributor the reviewer control
71 * and refuses the request behind it.
72 */
73export function gitHubViewerPermissions(
74 access: GitHubViewerAccess & Pick<GitHubRepositoryAccess, "autoMergeAllowed">,
75): PullRequestViewerPermissions {
76 return {
77 ...(access.canWrite ? { stackRebase: true } : {}),
78 actions: [
79 ...(access.canDeleteBranch === true ? (["delete-branch"] as const) : []),
80 // Keep disabling available if the repository has since turned auto-merge off.
81 ...(access.canWrite
82 ? ([
83 "merge",
84 ...(access.autoMergeAllowed && access.canMergeNow !== true
85 ? (["enable-auto-merge"] as const)
86 : []),
87 "disable-auto-merge",
88 "revert",
89 "approve-workflows",
90 ] as const)
91 : []),
92 ...(access.canUpdate ? (["ready", "draft", "close", "reopen"] as const) : []),
93 // Whether this viewer may update the branch is GitHub's own answer, read with the
94 // comparison; without it the action is offered to nobody rather than to everybody.
95 ...(access.canUpdateBranch === true ? (["update-branch"] as const) : []),
96 ],
97 comment: true,
98 resolve: access.canWrite || access.didAuthor,
99 // Anyone may review a pull request they can see, except their own: GitHub refuses an author's
100 // approval and their request for changes ("Can not approve your own pull request"), and
101 // leaves them commenting, which is what an author has to say about their own change anyway.
102 verdicts: access.didAuthor ? (["comment"] as const) : CAPABILITIES.review.verdicts,
103 requestReviewers: access.canWrite,
104 ...(access.canUpdateBranch === true ? { updateMethods: CAPABILITIES.updateMethods } : {}),
105 labels: access.canTriage,
106 };
108​
109function gitHubProviderFailure(
110 error: GitHubPullRequestApi.GitHubPullRequestApiError,
111): PullRequestProviderFailure {
112 switch (error._tag) {
113 case "GitHubCliMissingError":
114 return { reason: "missing-tool" };
115 case "GitHubNotSignedInError":
116 case "GitHubHostDisabledError":
117 case "GitHubApiAuthenticationError":
118 return { reason: "unauthenticated" };
119 case "GitHubApiRateLimitError":
120 return {
121 reason: "rate-limited",
122 ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
123 };
124 case "SourceControlRateLimitPausedError":
125 return { reason: "rate-limited", retryAt: error.retryAt };
126 case "GitHubApiNotFoundError":
127 return { reason: "not-found" };
128 default:
129 return { reason: "failed" };
130 }
132​
133/**
134 * `gh pr view --json` reports no avatar for anyone, so the ones the GraphQL read collected are
135 * applied here by login.
136 */
137function withAvatar(
138 actor: PullRequestActor | null,
139 avatarsByLogin: ReadonlyMap<string, string>,
140 host: string,
141 botLogins?: ReadonlySet<string>,
142): PullRequestActor | null {
143 if (actor === null) return actor;
144 if (botLogins?.has(actor.login)) actor = { ...actor, isBot: true };
145 if (actor.avatarUrl !== null) return actor;
146 const avatarUrl = avatarsByLogin.get(actor.login) ?? loginAvatarUrl(actor.login, host);
147 return avatarUrl === null ? actor : { ...actor, avatarUrl };
149​
150function withWorkflowApprovals(
151 checks: ReadonlyArray<PullRequestCheck>,
152 runs: ReadonlyArray<GitHubWorkflowRunApproval>,
153 unavailable: boolean,
154): ReadonlyArray<PullRequestCheck> {
155 const representedRunIds = new Set<number>();
156 for (const check of checks) {
157 if (check.status !== "action-required" || check.url === null) continue;
158 const id = check.url.match(/\/actions\/runs\/(\d+)(?:\/|$)/)?.[1];
159 if (id !== undefined) representedRunIds.add(Number(id));
160 }
161 const approvalChecks = runs
162 .filter((run) => !representedRunIds.has(run.id))
163 .map((run): PullRequestCheck => ({
164 name: run.name,
165 status: "action-required",
166 description: "A maintainer must approve this workflow before it can run.",
167 url: run.url,
168 }));
169 return [
170 ...checks,
171 ...approvalChecks,
172 ...(unavailable
173 ? [
174 {
175 name: "Workflow approval status",
176 status: "action-required" as const,
177 description: "GitHub could not determine whether workflows are awaiting approval.",
178 url: null,
179 },
180 ]
181 : []),
182 ];
184​
185/**
186 * Null for anything that is not a plain user login: an app posts as `dependabot[bot]`, which
187 * names no page, and a guessed URL that 404s is worse than the initials it would replace.
188 */
189export function loginAvatarUrl(login: string, host: string): string | null {
190 return /^[a-z0-9][a-z0-9-]{0,38}$/iu.test(login) ? `https://${host}/${login}.png?size=80` : null;
192​
193// Whether search covers a repository changes only when the repository is renamed or moved.
194const SEARCH_COVERAGE_TTL = Duration.hours(1);
195const SEARCH_COVERAGE_CAPACITY = 4096;
196const SEARCH_COVERAGE_CONCURRENCY = 4;
197​
198/**
199 * Whether GitHub search covers a repository. `cwd` only says where to ask, so equality ignores
200 * it and `lookup`, and every checkout of a repository shares one answer.
201 */
202class SearchCoverage {
203 readonly key: string;
204 readonly lookup: Effect.Effect<boolean, GitHubPullRequestApi.GitHubPullRequestApiError>;
205​
206 constructor(
207 host: string,
208 repository: string,
209 lookup: Effect.Effect<boolean, GitHubPullRequestApi.GitHubPullRequestApiError>,
210 ) {
211 this.key = `${host.toLowerCase()}\n${repository.trim().toLowerCase()}`;
212 this.lookup = lookup;
213 }
214​
215 [Equal.symbol](that: unknown): boolean {
216 return that instanceof SearchCoverage && that.key === this.key;
217 }
218 [Hash.symbol](): number {
219 return Hash.string(this.key);
220 }
222​
223const rendersEmpty = (body: string): boolean =>
224 body.replace(/<!--[\s\S]*?-->/g, "").trim().length === 0;
225​
226export const make = Effect.gen(function* () {
227 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
228​
229 // GitHub does not index every repository for search: a renamed one answers for its old name
230 // with silence rather than with an error. Where search has any pull request for a repository it
231 // covers it, so its silence on a page is a real empty answer; any other the caller reads on its
232 // own. A failed check is not kept.
233 const searchCoverage = yield* Cache.makeWith((request: SearchCoverage) => request.lookup, {
234 capacity: SEARCH_COVERAGE_CAPACITY,
235 timeToLive: (exit) => (Exit.isSuccess(exit) ? SEARCH_COVERAGE_TTL : Duration.zero),
236 });
237 const coverageOf = (
238 input: Parameters<NonNullable<PullRequestProviderApi["listChangeRequestsAcross"]>>[0],
239 repository: string,
240 ) =>
241 new SearchCoverage(
242 input.host,
243 repository,
244 Effect.suspend(() =>
245 cli.searchPullRequests({
246 cwd: input.cwd,
247 host: input.host,
248 repositories: [repository],
249 state: "all",
250 involvement: "all",
251 viewer: input.viewer,
252 limit: 1,
253 }),
254 ).pipe(Effect.map((batch) => batch.items.length > 0)),
255 );
256 const unresolvedBySearch = Effect.fn("GitHubPullRequestProvider.unresolvedBySearch")(function* (
257 input: Parameters<NonNullable<PullRequestProviderApi["listChangeRequestsAcross"]>>[0],
258 batch: GitHubPullRequestApi.GitHubPullRequestSearchBatch,
259 ) {
260 // A repository a page has rows for is covered without asking.
261 yield* Effect.forEach(
262 batch.items,
263 (item) => Cache.set(searchCoverage, coverageOf(input, item.repository), true),
264 { discard: true },
265 );
266 const answered = new Set(batch.items.map((item) => item.repository.trim().toLowerCase()));
267 const silent = input.repositories.filter(
268 (repository) => !answered.has(repository.trim().toLowerCase()),
269 );
270 // A truncated first slice can be silent about a covered repository whose rows are just
271 // older than the cut, so it vouches for none. Past the first slice silence from a covered
272 // repository means its rows are older rather than absent.
273 if (input.cursor === undefined && batch.truncated) return silent;
274 return yield* Effect.filter(
275 silent,
276 (repository) =>
277 Cache.get(searchCoverage, coverageOf(input, repository)).pipe(
278 Effect.map((covered) => !covered),
279 Effect.orElseSucceed(() => true),
280 ),
281 { concurrency: SEARCH_COVERAGE_CONCURRENCY },
282 );
283 });
284​
285 const fail = (operation: string) => (error: GitHubPullRequestApi.GitHubPullRequestApiError) =>
286 new PullRequestProviderError({
287 provider: SourceControlProviderKind.make("github"),
288 operation,
289 ...gitHubProviderFailure(error),
290 detail: error.message,
291 cause: error,
292 });
293​
294 const readChecks = (input: ProviderRepositoryRef & { readonly number: number }) =>
295 cli.getPullRequestDetail(input).pipe(
296 Effect.flatMap((pullRequest) =>
297 (pullRequest.state !== "open" || pullRequest.isCrossRepository !== true
298 ? Effect.succeed({
299 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
300 unavailable: false,
301 })
302 : pullRequest.headSha == null || pullRequest.headRepositoryOwner == null
303 ? Effect.succeed({
304 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
305 unavailable: true,
306 })
307 : cli
308 .listWorkflowRunsRequiringApproval({
309 ...input,
310 headSha: pullRequest.headSha,
311 headBranch: pullRequest.headBranch,
312 headRepositoryOwner: pullRequest.headRepositoryOwner,
313 isCrossRepository: true,
314 })
315 .pipe(
316 Effect.matchEffect({
317 onFailure: (error) =>
318 error._tag === "GitHubApiRateLimitError" ||
319 error._tag === "SourceControlRateLimitPausedError"
320 ? Effect.fail(error)
321 : Effect.succeed({
322 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
323 unavailable: true,
324 }),
325 onSuccess: (runs) => Effect.succeed({ runs, unavailable: false }),
326 }),
327 )
328 ).pipe(
329 Effect.map((workflowApprovals) => ({
330 ...pullRequest,
331 author: withAvatar(pullRequest.author, new Map(), input.host),
332 checks: withWorkflowApprovals(
333 pullRequest.checks,
334 workflowApprovals.runs,
335 workflowApprovals.unavailable,
336 ),
337 ...(workflowApprovals.unavailable
338 ? {}
339 : { workflowApprovalsRequired: workflowApprovals.runs.length }),
340 })),
341 ),
342 ),
343 );
344​
345 const provider: PullRequestProviderApi = {
346 kind: SourceControlProviderKind.make("github"),
347 capabilities: CAPABILITIES,
348 unavailableRequirement: UNAVAILABLE_REQUIREMENT,
349 readsPublicHostWithoutCheckout: true,
350 mergeMessageRewrite: removeAgentCredits,
351 getRoutingIdentity: (input) =>
352 cli.getRoutingIdentity(input).pipe(Effect.mapError(fail("routeIdentity"))),
353 withVerifiedCredential: (input, use) =>
354 cli
355 .withVerifiedCredential(input, (identity) => use(identity).pipe(Effect.result))
356 .pipe(Effect.mapError(fail("routeIdentity")), Effect.flatMap(Effect.fromResult)),
357​
358 getViewer: (input) =>
359 cli
360 .getViewerLogin({ cwd: input.cwd, host: input.host ?? "github.com" })
361 .pipe(Effect.mapError(fail("getViewer"))),
362​
363 listChangeRequests: (input) =>
364 cli
365 .listPullRequests({
366 cwd: input.cwd,
367 repository: input.repository,
368 host: input.host,
369 state: input.state,
370 involvement: input.involvement,
371 viewer: input.viewer,
372 limit: input.limit,
373 query: input.query,
374 cursor: input.cursor,
375 filters: input.filters,
376 })
377 .pipe(
378 Effect.mapError(fail("listChangeRequests")),
379 Effect.flatMap((page) =>
380 cli
381 .listActorAvatars({
382 cwd: input.cwd,
383 repository: input.repository,
384 host: input.host,
385 ids: [...new Set(page.items.flatMap((item) => item.authorId ?? []))],
386 })
387 .pipe(
388 Effect.orElseSucceed(() => new Map<string, string>()),
389 Effect.map((avatarsByLogin) => ({
390 ...page,
391 items: page.items.map((item) => ({
392 ...item,
393 author: withAvatar(item.author, avatarsByLogin, input.host),
394 })),
395 })),
396 ),
397 ),
398 ),
399​
400 listChangeRequestsAcross: (input) =>
401 cli
402 .searchPullRequests({
403 cwd: input.cwd,
404 host: input.host,
405 repositories: input.repositories,
406 state: input.state,
407 involvement: input.involvement,
408 viewer: input.viewer,
409 limit: input.limit,
410 query: input.query,
411 cursor: input.cursor,
412 filters: input.filters,
413 })
414 .pipe(
415 Effect.mapError(fail("listChangeRequestsAcross")),
416 Effect.flatMap((batch) =>
417 Effect.map(unresolvedBySearch(input, batch), (unresolved) => ({
418 truncated: batch.truncated,
419 items: batch.items.map((item) => ({
420 ...item,
421 author: withAvatar(item.author, new Map<string, string>(), input.host),
422 })),
423 unresolved,
424 })),
425 ),
426 ),
427​
428 listChangeRequestStats: (input) =>
429 cli
430 .listPullRequestStats({
431 cwd: input.cwd,
432 host: input.host,
433 changeRequests: input.changeRequests,
434 })
435 .pipe(Effect.mapError(fail("listChangeRequestStats"))),
436​
437 getChangeRequestSummary: (input) =>
438 cli.getPullRequestSummary(input).pipe(
439 Effect.map((summary) => ({
440 ...summary,
441 ...(summary.author === undefined
442 ? {}
443 : { author: withAvatar(summary.author, new Map(), input.host) }),
444 })),
445 Effect.mapError(fail("getChangeRequestSummary")),
446 ),
447​
448 getChangeRequestStack: (input) =>
449 cli.getPullRequestStack(input).pipe(Effect.mapError(fail("getChangeRequestStack"))),
450​
451 getChangeRequestWatchFingerprint: (input) =>
452 cli
453 .getPullRequestWatchFingerprint(input)
454 .pipe(Effect.mapError(fail("getChangeRequestWatchFingerprint"))),
455​
456 getChangeRequestPreview: (input) =>
457 cli.getPullRequestPreview(input).pipe(Effect.mapError(fail("getChangeRequestPreview"))),
458​
459 getChangeRequestChecks: (input) =>
460 cli.revalidateChecks(input, readChecks(input)).pipe(
461 Effect.map(({ state, checks }) => ({ state, checks })),
462 Effect.mapError(fail("getChangeRequestChecks")),
463 ),
464​
465 getChangeRequest: (input) =>
466 readChecks(input).pipe(
467 Effect.map((pullRequest): ProviderChangeRequestDetail => ({
468 ...pullRequest,
469 author: withAvatar(pullRequest.author, new Map<string, string>(), input.host),
470 reviewers: [
471 ...pullRequest.reviewRequestLogins.map((login) => ({
472 login,
473 name: null,
474 avatarUrl: null,
475 })),
476 ...pullRequest.reviewRequestTeams,
477 ],
478 mergeCapabilities: pullRequest.viewerAccess.mergeCapabilities,
479 viewerPermissions: gitHubViewerPermissions({
480 ...pullRequest.viewerAccess,
481 canUpdateBranch: pullRequest.comparison?.viewerCanUpdate === true,
482 }),
483 baseComparison:
484 pullRequest.comparison === null || pullRequest.comparison.behindBy === null
485 ? "unknown"
486 : pullRequest.comparison.behindBy > 0
487 ? "behind"
488 : "up-to-date",
489 ...(pullRequest.comparison?.behindBy == null
490 ? {}
491 : { behindBy: pullRequest.comparison.behindBy }),
492 })),
493 Effect.mapError(fail("getChangeRequest")),
494 ),
495​
496 getChangeRequestActivity: (input) =>
497 Effect.all(
498 [
499 cli.getPullRequestActivity(input),
500 // Line comments live on review threads, which `gh pr view --json` cannot reach.
501 cli.listReviewThreadComments(input).pipe(
502 Effect.orElseSucceed(() => ({
503 comments: [],
504 dismissalsByReviewId: new Map<string, string>(),
505 reactions: [],
506 reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
507 editedAtById: new Map<string, string>(),
508 reviewThreads: [],
509 commentCount: 0,
510 truncated: true,
511 reviewThreadsTruncated: true,
512 reviewers: [],
513 avatarsByLogin: new Map<string, string>(),
514 botLogins: new Set<string>(),
515 commitStats: new Map<
516 string,
517 { readonly additions: number; readonly deletions: number }
518 >(),
519 commits: [],
520 viewer: { canUpdate: true, didAuthor: false },
521 })),
522 ),
523 ],
524 { concurrency: 2 },
525 ).pipe(
526 Effect.mapError(fail("getChangeRequestActivity")),
527 Effect.map(([pullRequest, reviewThreads]): ProviderChangeRequestActivity => ({
528 author: withAvatar(
529 pullRequest.author,
530 reviewThreads.avatarsByLogin,
531 input.host,
532 reviewThreads.botLogins,
533 ),
534 reviewers: reviewThreads.reviewers,
535 reactions: reviewThreads.reactions,
536 commits: (reviewThreads.commits.length > 0
537 ? reviewThreads.commits
538 : pullRequest.commits
539 ).map((commit) => ({
540 ...commit,
541 ...reviewThreads.commitStats.get(commit.oid),
542 authors: commit.authors?.map(
543 (author) =>
544 withAvatar(
545 author,
546 reviewThreads.avatarsByLogin,
547 input.host,
548 reviewThreads.botLogins,
549 ) ?? author,
550 ),
551 })),
552 comments: [...pullRequest.comments, ...reviewThreads.comments]
553 .map((comment) => ({
554 ...comment,
555 // GitHub keeps the dismissal reason on the timeline event, not on the review,
556 // so a dismissed review with nothing visible of its own reads its words from
557 // there. "Visible" and not "empty": bot reviews often carry only an HTML
558 // marker comment, which markdown renders as nothing.
559 body:
560 comment.kind === "review" &&
561 comment.reviewState?.toUpperCase() === "DISMISSED" &&
562 rendersEmpty(comment.body)
563 ? (reviewThreads.dismissalsByReviewId.get(comment.id) ?? comment.body)
564 : comment.body,
565 author: withAvatar(
566 comment.author,
567 reviewThreads.avatarsByLogin,
568 input.host,
569 reviewThreads.botLogins,
570 ),
571 // A comment out of `gh pr view --json` carries none of its own: that read
572 // reports no reaction at all, so they arrive from the GraphQL page by node id.
573 reactions: comment.reactions ?? reviewThreads.reactionsById.get(comment.id) ?? [],
574 editedAt: reviewThreads.editedAtById.get(comment.id) ?? comment.editedAt ?? null,
575 }))
576 .toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
577 // `gh pr view --json comments,reviews` follows GitHub's cursors itself, so those two
578 // are always whole and only the thread walk can stop short of the host.
579 commentCount: pullRequest.comments.length + reviewThreads.commentCount,
580 commentsTruncated: reviewThreads.truncated,
581 reviewThreadsTruncated: reviewThreads.reviewThreadsTruncated,
582 reviewThreads: reviewThreads.reviewThreads.map((thread) => ({
583 ...thread,
584 comments: thread.comments.map((comment) => ({
585 ...comment,
586 author: withAvatar(
587 comment.author,
588 reviewThreads.avatarsByLogin,
589 input.host,
590 reviewThreads.botLogins,
591 ),
592 })),
593 })),
594 })),
595 ),
596​
597 getReviewThreadComments: (input) =>
598 cli.getReviewThreadComments(input).pipe(Effect.mapError(fail("getReviewThreadComments"))),
599​
600 getViewerPermissions: (input) => {
601 const lightAccess = cli
602 .getViewerAccess({ ...input, allowReserve: true })
603 .pipe(Effect.map((access) => gitHubViewerPermissions(access)));
604 if (input.includeUpdateBranch === false) {
605 return lightAccess.pipe(Effect.mapError(fail("getViewerPermissions")));
606 }
607 return cli.getPullRequestDetail(input).pipe(
608 Effect.provideService(SourceControlRateLimit.Interactive, true),
609 Effect.map((pullRequest) =>
610 gitHubViewerPermissions({
611 ...pullRequest.viewerAccess,
612 canUpdateBranch:
613 pullRequest.state === "open" && pullRequest.comparison?.viewerCanUpdate === true,
614 }),
615 ),
616 Effect.catchIf(
617 (error) =>
618 error._tag !== "GitHubApiRateLimitError" &&
619 error._tag !== "SourceControlRateLimitPausedError",
620 () => lightAccess,
621 ),
622 Effect.mapError(fail("getViewerPermissions")),
623 );
624 },
625​
626 getDiff: (input) => cli.getPullRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
627​
628 getDiffFileContents: (input) =>
629 cli.getPullRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),
630​
631 getFilesViewed: (input) =>
632 cli.getPullRequestFilesViewed(input).pipe(Effect.mapError(fail("getFilesViewed"))),
633​
634 getFileStats: (input) =>
635 cli.getPullRequestFileStats(input).pipe(Effect.mapError(fail("getFileStats"))),
636 setFilesViewed: (input) =>
637 cli.setPullRequestFilesViewed(input).pipe(Effect.mapError(fail("setFilesViewed"))),
638​
639 listReviewerCandidates: (input) =>
640 cli.listReviewerCandidates(input).pipe(Effect.mapError(fail("listReviewerCandidates"))),
641​
642 setReviewerRequest: (input) =>
643 cli
644 .setReviewerRequest({
645 cwd: input.cwd,
646 repository: input.repository,
647 host: input.host,
648 number: input.number,
649 reviewers: input.reviewers,
650 requested: input.requested,
651 })
652 .pipe(Effect.mapError(fail("setReviewerRequest"))),
653​
654 listLabelCandidates: (input) =>
655 cli.listLabelCandidates(input).pipe(Effect.mapError(fail("listLabelCandidates"))),
656​
657 listRepositoryLabels: (input) =>
658 cli.listRepositoryLabels(input).pipe(Effect.mapError(fail("listRepositoryLabels"))),
659​
660 searchRepositoryAuthors: (input) =>
661 cli.searchRepositoryAuthors(input).pipe(Effect.mapError(fail("searchRepositoryAuthors"))),
662​
663 setLabels: (input) =>
664 cli
665 .setLabels({
666 cwd: input.cwd,
667 repository: input.repository,
668 host: input.host,
669 number: input.number,
670 labels: input.labels,
671 applied: input.applied,
672 })
673 .pipe(Effect.mapError(fail("setLabels"))),
674​
675 runAction: (input) =>
676 cli
677 .runPullRequestAction({
678 cwd: input.cwd,
679 repository: input.repository,
680 host: input.host,
681 number: input.number,
682 action: input.action,
683 ...(input.removeAgentCreditsOnMerge === true ? { removeAgentCreditsOnMerge: true } : {}),
684 ...(input.stackNumber === undefined ? {} : { stackNumber: input.stackNumber }),
685 ...(input.expectedStackHeads === undefined
686 ? {}
687 : { expectedStackHeads: input.expectedStackHeads }),
688 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
689 ...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
690 })
691 .pipe(Effect.mapError(fail("runAction"))),
692​
693 updateChangeRequest: (input) =>
694 cli
695 .updatePullRequest({
696 cwd: input.cwd,
697 repository: input.repository,
698 host: input.host,
699 number: input.number,
700 ...(input.title === undefined ? {} : { title: input.title }),
701 ...(input.body === undefined ? {} : { body: input.body }),
702 })
703 .pipe(Effect.mapError(fail("updateChangeRequest"))),
704​
705 comment: (input) => cli.commentOnPullRequest(input).pipe(Effect.mapError(fail("comment"))),
706​
707 updateComment: (input) =>
708 cli
709 .updateComment({
710 cwd: input.cwd,
711 repository: input.repository,
712 host: input.host,
713 number: input.number,
714 commentId: input.commentId,
715 kind: input.kind,
716 body: input.body,
717 })
718 .pipe(Effect.mapError(fail("updateComment"))),
719​
720 submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
721​
722 replyToThread: (input) =>
723 cli
724 .replyToReviewThread({
725 cwd: input.cwd,
726 repository: input.repository,
727 host: input.host,
728 threadId: input.threadId,
729 body: input.body,
730 })
731 .pipe(Effect.mapError(fail("replyToThread"))),
732​
733 setReaction: (input) =>
734 cli
735 .setReaction({
736 cwd: input.cwd,
737 repository: input.repository,
738 host: input.host,
739 number: input.number,
740 ...(input.subjectId === undefined ? {} : { subjectId: input.subjectId }),
741 content: input.content,
742 reacted: input.reacted,
743 })
744 .pipe(Effect.mapError(fail("setReaction"))),
745​
746 setThreadResolution: (input) =>
747 cli
748 .setReviewThreadResolution({
749 cwd: input.cwd,
750 repository: input.repository,
751 host: input.host,
752 threadId: input.threadId,
753 resolved: input.resolved,
754 })
755 .pipe(Effect.mapError(fail("setThreadResolution"))),
756 };
757​
758 return provider;
759});