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

GitHubPullRequestProvider.ts

809 lines29.6 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​
164const workflowRunIdOf = (url: string | null) =>
165 url?.match(/\/actions\/runs\/(\d+)(?:\/|$)/)?.[1] ?? null;
166​
167function withWorkflowApprovals(
168 checks: ReadonlyArray<PullRequestCheck>,
169 runs: ReadonlyArray<GitHubWorkflowRunApproval>,
170 unavailable: boolean,
171): ReadonlyArray<PullRequestCheck> {
172 const representedRunIds = new Set<number>();
173 for (const check of checks) {
174 if (check.status !== "action-required" || check.url === null) continue;
175 const id = workflowRunIdOf(check.url);
176 if (id !== null) representedRunIds.add(Number(id));
177 }
178 const approvalChecks = runs
179 .filter((run) => !representedRunIds.has(run.id))
180 .map((run): PullRequestCheck => ({
181 name: run.name,
182 status: "action-required",
183 description: "A maintainer must approve this workflow before it can run.",
184 url: run.url,
185 }));
186 return [
187 ...checks,
188 ...approvalChecks,
189 ...(unavailable
190 ? [
191 {
192 name: "Workflow approval status",
193 status: "action-required" as const,
194 description: "GitHub could not determine whether workflows are awaiting approval.",
195 url: null,
196 placeholder: true,
197 },
198 ]
199 : []),
200 ];
202​
203// GitHub adds a run's check runs only as its jobs start, so a queued run can have none yet.
204function withUnfinishedWorkflowRuns(
205 checks: ReadonlyArray<PullRequestCheck>,
206 runs: ReadonlyArray<GitHubWorkflowRunApproval>,
207): ReadonlyArray<PullRequestCheck> {
208 const runningRunIds = new Set<number>();
209 for (const check of checks) {
210 if (check.status !== "pending" && check.status !== "action-required") continue;
211 const id = workflowRunIdOf(check.url);
212 if (id !== null) runningRunIds.add(Number(id));
213 }
214 return [
215 ...checks,
216 ...runs
217 .filter((run) => !runningRunIds.has(run.id))
218 .map((run): PullRequestCheck => ({
219 name: run.name,
220 status: "pending",
221 description: "This workflow run has not finished.",
222 url: run.url,
223 })),
224 ];
226​
227/** App logins have no profile page; guessed avatar URLs 404. */
228export function loginAvatarUrl(login: string, host: string): string | null {
229 return /^[a-z0-9][a-z0-9-]{0,38}$/iu.test(login) ? `https://${host}/${login}.png?size=80` : null;
231​
232// Whether search covers a repository changes only when the repository is renamed or moved.
233const SEARCH_COVERAGE_TTL = Duration.hours(1);
234const SEARCH_COVERAGE_CAPACITY = 4096;
235const SEARCH_COVERAGE_CONCURRENCY = 4;
236​
237/**
238 * Whether GitHub search covers a repository. `cwd` only says where to ask, so equality ignores
239 * it and `lookup`, and every checkout of a repository shares one answer.
240 */
241class SearchCoverage {
242 readonly key: string;
243 readonly lookup: Effect.Effect<boolean, GitHubPullRequestApi.GitHubPullRequestApiError>;
244​
245 constructor(
246 host: string,
247 repository: string,
248 lookup: Effect.Effect<boolean, GitHubPullRequestApi.GitHubPullRequestApiError>,
249 ) {
250 this.key = `${host.toLowerCase()}\n${repository.trim().toLowerCase()}`;
251 this.lookup = lookup;
252 }
253​
254 [Equal.symbol](that: unknown): boolean {
255 return that instanceof SearchCoverage && that.key === this.key;
256 }
257 [Hash.symbol](): number {
258 return Hash.string(this.key);
259 }
261​
262const rendersEmpty = (body: string): boolean =>
263 body.replace(/<!--[\s\S]*?-->/g, "").trim().length === 0;
264​
265export const make = Effect.gen(function* () {
266 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
267​
268 // GitHub does not index every repository for search: a renamed one answers for its old name
269 // with silence rather than with an error. Where search has any pull request for a repository it
270 // covers it, so its silence on a page is a real empty answer; any other the caller reads on its
271 // own. A failed check is not kept.
272 const searchCoverage = yield* Cache.makeWith((request: SearchCoverage) => request.lookup, {
273 capacity: SEARCH_COVERAGE_CAPACITY,
274 timeToLive: (exit) => (Exit.isSuccess(exit) ? SEARCH_COVERAGE_TTL : Duration.zero),
275 });
276 const coverageOf = (
277 input: Parameters<NonNullable<PullRequestProviderApi["listChangeRequestsAcross"]>>[0],
278 repository: string,
279 ) =>
280 new SearchCoverage(
281 input.host,
282 repository,
283 Effect.suspend(() =>
284 cli.searchPullRequests({
285 cwd: input.cwd,
286 host: input.host,
287 repositories: [repository],
288 state: "all",
289 involvement: "all",
290 viewer: input.viewer,
291 limit: 1,
292 }),
293 ).pipe(Effect.map((batch) => batch.items.length > 0)),
294 );
295 const unresolvedBySearch = Effect.fn("GitHubPullRequestProvider.unresolvedBySearch")(function* (
296 input: Parameters<NonNullable<PullRequestProviderApi["listChangeRequestsAcross"]>>[0],
297 batch: GitHubPullRequestApi.GitHubPullRequestSearchBatch,
298 ) {
299 // A repository a page has rows for is covered without asking.
300 yield* Effect.forEach(
301 batch.items,
302 (item) => Cache.set(searchCoverage, coverageOf(input, item.repository), true),
303 { discard: true },
304 );
305 const answered = new Set(batch.items.map((item) => item.repository.trim().toLowerCase()));
306 const silent = input.repositories.filter(
307 (repository) => !answered.has(repository.trim().toLowerCase()),
308 );
309 // A truncated first slice can be silent about a covered repository whose rows are just
310 // older than the cut, so it vouches for none. Past the first slice silence from a covered
311 // repository means its rows are older rather than absent.
312 if (input.cursor === undefined && batch.truncated) return silent;
313 return yield* Effect.filter(
314 silent,
315 (repository) =>
316 Cache.get(searchCoverage, coverageOf(input, repository)).pipe(
317 Effect.map((covered) => !covered),
318 Effect.orElseSucceed(() => true),
319 ),
320 { concurrency: SEARCH_COVERAGE_CONCURRENCY },
321 );
322 });
323​
324 const fail = (operation: string) => (error: GitHubPullRequestApi.GitHubPullRequestApiError) =>
325 new PullRequestProviderError({
326 provider: SourceControlProviderKind.make("github"),
327 operation,
328 ...gitHubProviderFailure(error),
329 detail: error.message,
330 cause: error,
331 });
332​
333 const readChecks = (input: ProviderRepositoryRef & { readonly number: number }) =>
334 cli.getPullRequestDetail(input).pipe(
335 Effect.flatMap((pullRequest) =>
336 (pullRequest.state !== "open" || pullRequest.isCrossRepository !== true
337 ? Effect.succeed({
338 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
339 unavailable: false,
340 })
341 : pullRequest.headSha == null || pullRequest.headRepositoryOwner == null
342 ? Effect.succeed({
343 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
344 unavailable: true,
345 })
346 : cli
347 .listWorkflowRunsRequiringApproval({
348 ...input,
349 headSha: pullRequest.headSha,
350 headBranch: pullRequest.headBranch,
351 headRepositoryOwner: pullRequest.headRepositoryOwner,
352 isCrossRepository: true,
353 })
354 .pipe(
355 Effect.matchEffect({
356 onFailure: (error) =>
357 error._tag === "GitHubApiRateLimitError" ||
358 error._tag === "SourceControlRateLimitPausedError"
359 ? Effect.fail(error)
360 : Effect.succeed({
361 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
362 unavailable: true,
363 }),
364 onSuccess: (runs) => Effect.succeed({ runs, unavailable: false }),
365 }),
366 )
367 ).pipe(
368 Effect.zip(
369 pullRequest.state !== "open" || pullRequest.headSha == null
370 ? Effect.succeed([] as ReadonlyArray<GitHubWorkflowRunApproval>)
371 : cli.listUnfinishedWorkflowRuns({ ...input, headSha: pullRequest.headSha }).pipe(
372 Effect.catchIf(
373 (error) =>
374 error._tag !== "GitHubApiRateLimitError" &&
375 error._tag !== "SourceControlRateLimitPausedError",
376 () => Effect.succeed([] as ReadonlyArray<GitHubWorkflowRunApproval>),
377 ),
378 ),
379 { concurrent: true },
380 ),
381 Effect.map(([workflowApprovals, unfinishedRuns]) => ({
382 ...pullRequest,
383 author: withAvatar(pullRequest.author, new Map(), input.host),
384 checks: withWorkflowApprovals(
385 withUnfinishedWorkflowRuns(pullRequest.checks, unfinishedRuns),
386 workflowApprovals.runs,
387 workflowApprovals.unavailable,
388 ),
389 ...(workflowApprovals.unavailable
390 ? {}
391 : { workflowApprovalsRequired: workflowApprovals.runs.length }),
392 })),
393 ),
394 ),
395 );
396​
397 const provider: PullRequestProviderApi = {
398 kind: SourceControlProviderKind.make("github"),
399 capabilities: CAPABILITIES,
400 unavailableRequirement: UNAVAILABLE_REQUIREMENT,
401 readsPublicHostWithoutCheckout: true,
402 batchesReads: true,
403 mergeMessageRewrite: removeAgentCredits,
404 getRoutingIdentity: (input) =>
405 cli.getRoutingIdentity(input).pipe(Effect.mapError(fail("routeIdentity"))),
406 withVerifiedCredential: (input, use) =>
407 cli
408 .withVerifiedCredential(input, (identity) => use(identity).pipe(Effect.result))
409 .pipe(Effect.mapError(fail("routeIdentity")), Effect.flatMap(Effect.fromResult)),
410​
411 getViewer: (input) =>
412 cli
413 .getViewerLogin({ cwd: input.cwd, host: input.host ?? "github.com" })
414 .pipe(Effect.mapError(fail("getViewer"))),
415​
416 listChangeRequests: (input) =>
417 cli
418 .listPullRequests({
419 cwd: input.cwd,
420 repository: input.repository,
421 host: input.host,
422 state: input.state,
423 involvement: input.involvement,
424 viewer: input.viewer,
425 limit: input.limit,
426 query: input.query,
427 cursor: input.cursor,
428 filters: input.filters,
429 })
430 .pipe(
431 Effect.mapError(fail("listChangeRequests")),
432 Effect.map((page) => ({
433 ...page,
434 items: page.items.map((item) => ({
435 ...item,
436 author: withAvatar(item.author, new Map<string, string>(), input.host),
437 })),
438 })),
439 ),
440​
441 listChangeRequestsAcross: (input) =>
442 cli
443 .searchPullRequests({
444 cwd: input.cwd,
445 host: input.host,
446 repositories: input.repositories,
447 state: input.state,
448 involvement: input.involvement,
449 viewer: input.viewer,
450 limit: input.limit,
451 query: input.query,
452 cursor: input.cursor,
453 filters: input.filters,
454 })
455 .pipe(
456 Effect.mapError(fail("listChangeRequestsAcross")),
457 Effect.flatMap((batch) =>
458 Effect.map(unresolvedBySearch(input, batch), (unresolved) => ({
459 truncated: batch.truncated,
460 items: batch.items.map((item) => ({
461 ...item,
462 author: withAvatar(item.author, new Map<string, string>(), input.host),
463 })),
464 unresolved,
465 })),
466 ),
467 ),
468​
469 listChangeRequestStats: (input) =>
470 cli
471 .listPullRequestStats({
472 cwd: input.cwd,
473 host: input.host,
474 changeRequests: input.changeRequests,
475 })
476 .pipe(Effect.mapError(fail("listChangeRequestStats"))),
477​
478 getChangeRequestSummary: (input) =>
479 cli.getPullRequestSummary(input).pipe(
480 Effect.map((summary) => ({
481 ...summary,
482 ...(summary.author === undefined
483 ? {}
484 : { author: withAvatar(summary.author, new Map(), input.host) }),
485 })),
486 Effect.mapError(fail("getChangeRequestSummary")),
487 ),
488​
489 getChangeRequestStack: (input) =>
490 cli.getPullRequestStack(input).pipe(Effect.mapError(fail("getChangeRequestStack"))),
491​
492 getChangeRequestWatchFingerprint: (input) =>
493 cli
494 .getPullRequestWatchFingerprint(input)
495 .pipe(Effect.mapError(fail("getChangeRequestWatchFingerprint"))),
496​
497 changeRequestEvents: (input) => cli.pullRequestEvents(input),
498​
499 getChangeRequestPreview: (input) =>
500 cli.getPullRequestPreview(input).pipe(Effect.mapError(fail("getChangeRequestPreview"))),
501​
502 getChangeRequestChecks: (input) =>
503 cli.revalidateChecks(input, readChecks(input)).pipe(
504 Effect.map(({ state, checks }) => ({ state, checks })),
505 Effect.mapError(fail("getChangeRequestChecks")),
506 ),
507​
508 getChangeRequest: (input) =>
509 readChecks(input).pipe(
510 Effect.map((pullRequest): ProviderChangeRequestDetail => ({
511 ...pullRequest,
512 author: withAvatar(pullRequest.author, new Map<string, string>(), input.host),
513 reviewers: [
514 ...pullRequest.reviewRequestLogins.map((login) => ({
515 login,
516 name: null,
517 avatarUrl: null,
518 })),
519 ...pullRequest.reviewRequestTeams,
520 ],
521 mergeCapabilities: pullRequest.viewerAccess.mergeCapabilities,
522 viewerPermissions: {
523 ...gitHubViewerPermissions({
524 ...pullRequest.viewerAccess,
525 canUpdateBranch: pullRequest.comparison?.viewerCanUpdate === true,
526 }),
527 maintainerEdits: pullRequest.canEditMaintainerEdits,
528 },
529 baseComparison:
530 pullRequest.comparison === null || pullRequest.comparison.behindBy === null
531 ? "unknown"
532 : pullRequest.comparison.behindBy > 0
533 ? "behind"
534 : "up-to-date",
535 ...(pullRequest.comparison?.behindBy == null
536 ? {}
537 : { behindBy: pullRequest.comparison.behindBy }),
538 })),
539 Effect.mapError(fail("getChangeRequest")),
540 ),
541​
542 getChangeRequestActivity: (input) =>
543 Effect.all(
544 [
545 cli.getPullRequestActivity(input),
546 cli.listReviewThreadComments(input).pipe(
547 Effect.orElseSucceed(() => ({
548 comments: [],
549 dismissalsByReviewId: new Map<string, string>(),
550 reactions: [],
551 reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
552 editedAtById: new Map<string, string>(),
553 reviewThreads: [],
554 commentCount: 0,
555 truncated: true,
556 reviewThreadsTruncated: true,
557 reviewers: [],
558 avatarsByLogin: new Map<string, string>(),
559 botLogins: new Set<string>(),
560 commits: [],
561 viewer: { canUpdate: true, didAuthor: false },
562 })),
563 ),
564 ],
565 { concurrency: 2 },
566 ).pipe(
567 Effect.mapError(fail("getChangeRequestActivity")),
568 Effect.map(([pullRequest, reviewThreads]): ProviderChangeRequestActivity => {
569 const commitStats = new Map(
570 pullRequest.commits.map(({ oid, additions, deletions }) => [
571 oid,
572 additions === undefined ? {} : { additions, deletions },
573 ]),
574 );
575 return {
576 author: withAvatar(
577 pullRequest.author,
578 reviewThreads.avatarsByLogin,
579 input.host,
580 reviewThreads.botLogins,
581 ),
582 reviewers: reviewThreads.reviewers,
583 reactions: reviewThreads.reactions,
584 commits: (reviewThreads.commits.length > 0
585 ? reviewThreads.commits
586 : pullRequest.commits
587 ).map((commit) => ({
588 ...commit,
589 ...commitStats.get(commit.oid),
590 authors: commit.authors?.map(
591 (author) =>
592 withAvatar(
593 author,
594 reviewThreads.avatarsByLogin,
595 input.host,
596 reviewThreads.botLogins,
597 ) ?? author,
598 ),
599 })),
600 comments: [...pullRequest.comments, ...reviewThreads.comments]
601 .map((comment) => ({
602 ...comment,
603 // Dismissal reasons live on timeline events; HTML-only bot reviews need that fallback too.
604 body:
605 comment.kind === "review" &&
606 comment.reviewState?.toUpperCase() === "DISMISSED" &&
607 rendersEmpty(comment.body)
608 ? (reviewThreads.dismissalsByReviewId.get(comment.id) ?? comment.body)
609 : comment.body,
610 author: withAvatar(
611 comment.author,
612 reviewThreads.avatarsByLogin,
613 input.host,
614 reviewThreads.botLogins,
615 ),
616 reactions: comment.reactions ?? reviewThreads.reactionsById.get(comment.id) ?? [],
617 editedAt: reviewThreads.editedAtById.get(comment.id) ?? comment.editedAt ?? null,
618 }))
619 .toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
620 commentCount: pullRequest.comments.length + reviewThreads.commentCount,
621 commentsTruncated: reviewThreads.truncated,
622 reviewThreadsTruncated: reviewThreads.reviewThreadsTruncated,
623 reviewThreads: reviewThreads.reviewThreads.map((thread) => ({
624 ...thread,
625 comments: thread.comments.map((comment) => ({
626 ...comment,
627 author: withAvatar(
628 comment.author,
629 reviewThreads.avatarsByLogin,
630 input.host,
631 reviewThreads.botLogins,
632 ),
633 })),
634 })),
635 };
636 }),
637 ),
638​
639 getReviewThreadComments: (input) =>
640 cli.getReviewThreadComments(input).pipe(Effect.mapError(fail("getReviewThreadComments"))),
641​
642 getViewerPermissions: (input) => {
643 const lightAccess = cli
644 .getViewerAccess({ ...input, allowReserve: true })
645 .pipe(Effect.map((access) => gitHubViewerPermissions(access)));
646 if (input.includeUpdateBranch === false) {
647 return lightAccess.pipe(Effect.mapError(fail("getViewerPermissions")));
648 }
649 return cli.getPullRequestDetail(input).pipe(
650 Effect.provideService(SourceControlRateLimit.Interactive, true),
651 Effect.map((pullRequest) =>
652 gitHubViewerPermissions({
653 ...pullRequest.viewerAccess,
654 canUpdateBranch:
655 pullRequest.state === "open" && pullRequest.comparison?.viewerCanUpdate === true,
656 }),
657 ),
658 Effect.catchIf(
659 (error) =>
660 error._tag !== "GitHubApiRateLimitError" &&
661 error._tag !== "SourceControlRateLimitPausedError",
662 () => lightAccess,
663 ),
664 Effect.mapError(fail("getViewerPermissions")),
665 );
666 },
667​
668 getDiff: (input) => cli.getPullRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
669​
670 getDiffFileContents: (input) =>
671 cli.getPullRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),
672​
673 getFilesViewed: (input) =>
674 cli.getPullRequestFilesViewed(input).pipe(Effect.mapError(fail("getFilesViewed"))),
675​
676 getFileStats: (input) =>
677 cli.getPullRequestFileStats(input).pipe(Effect.mapError(fail("getFileStats"))),
678 setFilesViewed: (input) =>
679 cli.setPullRequestFilesViewed(input).pipe(Effect.mapError(fail("setFilesViewed"))),
680​
681 listReviewerCandidates: (input) =>
682 cli.listReviewerCandidates(input).pipe(Effect.mapError(fail("listReviewerCandidates"))),
683​
684 setReviewerRequest: (input) =>
685 cli
686 .setReviewerRequest({
687 cwd: input.cwd,
688 repository: input.repository,
689 host: input.host,
690 number: input.number,
691 reviewers: input.reviewers,
692 requested: input.requested,
693 })
694 .pipe(Effect.mapError(fail("setReviewerRequest"))),
695​
696 listLabelCandidates: (input) =>
697 cli.listLabelCandidates(input).pipe(Effect.mapError(fail("listLabelCandidates"))),
698​
699 listRepositoryLabels: (input) =>
700 cli.listRepositoryLabels(input).pipe(Effect.mapError(fail("listRepositoryLabels"))),
701​
702 searchRepositoryAuthors: (input) =>
703 cli.searchRepositoryAuthors(input).pipe(Effect.mapError(fail("searchRepositoryAuthors"))),
704​
705 searchRepositoryReferences: (input) =>
706 cli
707 .searchRepositoryReferences(input)
708 .pipe(Effect.mapError(fail("searchRepositoryReferences"))),
709​
710 setLabels: (input) =>
711 cli
712 .setLabels({
713 cwd: input.cwd,
714 repository: input.repository,
715 host: input.host,
716 number: input.number,
717 labels: input.labels,
718 applied: input.applied,
719 })
720 .pipe(Effect.mapError(fail("setLabels"))),
721​
722 runAction: (input) =>
723 cli
724 .runPullRequestAction({
725 cwd: input.cwd,
726 repository: input.repository,
727 host: input.host,
728 number: input.number,
729 action: input.action,
730 ...(input.removeAgentCreditsOnMerge === true ? { removeAgentCreditsOnMerge: true } : {}),
731 ...(input.stackNumber === undefined ? {} : { stackNumber: input.stackNumber }),
732 ...(input.expectedStackHeads === undefined
733 ? {}
734 : { expectedStackHeads: input.expectedStackHeads }),
735 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
736 ...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
737 })
738 .pipe(Effect.mapError(fail("runAction"))),
739​
740 updateChangeRequest: (input) =>
741 cli
742 .updatePullRequest({
743 ...(input.maintainerCanModify === undefined
744 ? {}
745 : { maintainerCanModify: input.maintainerCanModify }),
746 cwd: input.cwd,
747 repository: input.repository,
748 host: input.host,
749 number: input.number,
750 ...(input.title === undefined ? {} : { title: input.title }),
751 ...(input.body === undefined ? {} : { body: input.body }),
752 })
753 .pipe(Effect.mapError(fail("updateChangeRequest"))),
754​
755 comment: (input) => cli.commentOnPullRequest(input).pipe(Effect.mapError(fail("comment"))),
756​
757 updateComment: (input) =>
758 cli
759 .updateComment({
760 cwd: input.cwd,
761 repository: input.repository,
762 host: input.host,
763 number: input.number,
764 commentId: input.commentId,
765 kind: input.kind,
766 body: input.body,
767 })
768 .pipe(Effect.mapError(fail("updateComment"))),
769​
770 submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
771​
772 replyToThread: (input) =>
773 cli
774 .replyToReviewThread({
775 cwd: input.cwd,
776 repository: input.repository,
777 host: input.host,
778 threadId: input.threadId,
779 body: input.body,
780 })
781 .pipe(Effect.mapError(fail("replyToThread"))),
782​
783 setReaction: (input) =>
784 cli
785 .setReaction({
786 cwd: input.cwd,
787 repository: input.repository,
788 host: input.host,
789 number: input.number,
790 ...(input.subjectId === undefined ? {} : { subjectId: input.subjectId }),
791 content: input.content,
792 reacted: input.reacted,
793 })
794 .pipe(Effect.mapError(fail("setReaction"))),
795​
796 setThreadResolution: (input) =>
797 cli
798 .setReviewThreadResolution({
799 cwd: input.cwd,
800 repository: input.repository,
801 host: input.host,
802 threadId: input.threadId,
803 resolved: input.resolved,
804 })
805 .pipe(Effect.mapError(fail("setThreadResolution"))),
806 };
807​
808 return provider;
809});