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

GitHubPullRequestProvider.ts

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