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

GitHubPullRequestProvider.ts

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