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

GitHubPullRequestProvider.ts

808 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 mergeMessageRewrite: removeAgentCredits,
403 getRoutingIdentity: (input) =>
404 cli.getRoutingIdentity(input).pipe(Effect.mapError(fail("routeIdentity"))),
405 withVerifiedCredential: (input, use) =>
406 cli
407 .withVerifiedCredential(input, (identity) => use(identity).pipe(Effect.result))
408 .pipe(Effect.mapError(fail("routeIdentity")), Effect.flatMap(Effect.fromResult)),
409​
410 getViewer: (input) =>
411 cli
412 .getViewerLogin({ cwd: input.cwd, host: input.host ?? "github.com" })
413 .pipe(Effect.mapError(fail("getViewer"))),
414​
415 listChangeRequests: (input) =>
416 cli
417 .listPullRequests({
418 cwd: input.cwd,
419 repository: input.repository,
420 host: input.host,
421 state: input.state,
422 involvement: input.involvement,
423 viewer: input.viewer,
424 limit: input.limit,
425 query: input.query,
426 cursor: input.cursor,
427 filters: input.filters,
428 })
429 .pipe(
430 Effect.mapError(fail("listChangeRequests")),
431 Effect.map((page) => ({
432 ...page,
433 items: page.items.map((item) => ({
434 ...item,
435 author: withAvatar(item.author, new Map<string, string>(), input.host),
436 })),
437 })),
438 ),
439​
440 listChangeRequestsAcross: (input) =>
441 cli
442 .searchPullRequests({
443 cwd: input.cwd,
444 host: input.host,
445 repositories: input.repositories,
446 state: input.state,
447 involvement: input.involvement,
448 viewer: input.viewer,
449 limit: input.limit,
450 query: input.query,
451 cursor: input.cursor,
452 filters: input.filters,
453 })
454 .pipe(
455 Effect.mapError(fail("listChangeRequestsAcross")),
456 Effect.flatMap((batch) =>
457 Effect.map(unresolvedBySearch(input, batch), (unresolved) => ({
458 truncated: batch.truncated,
459 items: batch.items.map((item) => ({
460 ...item,
461 author: withAvatar(item.author, new Map<string, string>(), input.host),
462 })),
463 unresolved,
464 })),
465 ),
466 ),
467​
468 listChangeRequestStats: (input) =>
469 cli
470 .listPullRequestStats({
471 cwd: input.cwd,
472 host: input.host,
473 changeRequests: input.changeRequests,
474 })
475 .pipe(Effect.mapError(fail("listChangeRequestStats"))),
476​
477 getChangeRequestSummary: (input) =>
478 cli.getPullRequestSummary(input).pipe(
479 Effect.map((summary) => ({
480 ...summary,
481 ...(summary.author === undefined
482 ? {}
483 : { author: withAvatar(summary.author, new Map(), input.host) }),
484 })),
485 Effect.mapError(fail("getChangeRequestSummary")),
486 ),
487​
488 getChangeRequestStack: (input) =>
489 cli.getPullRequestStack(input).pipe(Effect.mapError(fail("getChangeRequestStack"))),
490​
491 getChangeRequestWatchFingerprint: (input) =>
492 cli
493 .getPullRequestWatchFingerprint(input)
494 .pipe(Effect.mapError(fail("getChangeRequestWatchFingerprint"))),
495​
496 changeRequestEvents: (input) => cli.pullRequestEvents(input),
497​
498 getChangeRequestPreview: (input) =>
499 cli.getPullRequestPreview(input).pipe(Effect.mapError(fail("getChangeRequestPreview"))),
500​
501 getChangeRequestChecks: (input) =>
502 cli.revalidateChecks(input, readChecks(input)).pipe(
503 Effect.map(({ state, checks }) => ({ state, checks })),
504 Effect.mapError(fail("getChangeRequestChecks")),
505 ),
506​
507 getChangeRequest: (input) =>
508 readChecks(input).pipe(
509 Effect.map((pullRequest): ProviderChangeRequestDetail => ({
510 ...pullRequest,
511 author: withAvatar(pullRequest.author, new Map<string, string>(), input.host),
512 reviewers: [
513 ...pullRequest.reviewRequestLogins.map((login) => ({
514 login,
515 name: null,
516 avatarUrl: null,
517 })),
518 ...pullRequest.reviewRequestTeams,
519 ],
520 mergeCapabilities: pullRequest.viewerAccess.mergeCapabilities,
521 viewerPermissions: {
522 ...gitHubViewerPermissions({
523 ...pullRequest.viewerAccess,
524 canUpdateBranch: pullRequest.comparison?.viewerCanUpdate === true,
525 }),
526 maintainerEdits: pullRequest.canEditMaintainerEdits,
527 },
528 baseComparison:
529 pullRequest.comparison === null || pullRequest.comparison.behindBy === null
530 ? "unknown"
531 : pullRequest.comparison.behindBy > 0
532 ? "behind"
533 : "up-to-date",
534 ...(pullRequest.comparison?.behindBy == null
535 ? {}
536 : { behindBy: pullRequest.comparison.behindBy }),
537 })),
538 Effect.mapError(fail("getChangeRequest")),
539 ),
540​
541 getChangeRequestActivity: (input) =>
542 Effect.all(
543 [
544 cli.getPullRequestActivity(input),
545 cli.listReviewThreadComments(input).pipe(
546 Effect.orElseSucceed(() => ({
547 comments: [],
548 dismissalsByReviewId: new Map<string, string>(),
549 reactions: [],
550 reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
551 editedAtById: new Map<string, string>(),
552 reviewThreads: [],
553 commentCount: 0,
554 truncated: true,
555 reviewThreadsTruncated: true,
556 reviewers: [],
557 avatarsByLogin: new Map<string, string>(),
558 botLogins: new Set<string>(),
559 commits: [],
560 viewer: { canUpdate: true, didAuthor: false },
561 })),
562 ),
563 ],
564 { concurrency: 2 },
565 ).pipe(
566 Effect.mapError(fail("getChangeRequestActivity")),
567 Effect.map(([pullRequest, reviewThreads]): ProviderChangeRequestActivity => {
568 const commitStats = new Map(
569 pullRequest.commits.map(({ oid, additions, deletions }) => [
570 oid,
571 additions === undefined ? {} : { additions, deletions },
572 ]),
573 );
574 return {
575 author: withAvatar(
576 pullRequest.author,
577 reviewThreads.avatarsByLogin,
578 input.host,
579 reviewThreads.botLogins,
580 ),
581 reviewers: reviewThreads.reviewers,
582 reactions: reviewThreads.reactions,
583 commits: (reviewThreads.commits.length > 0
584 ? reviewThreads.commits
585 : pullRequest.commits
586 ).map((commit) => ({
587 ...commit,
588 ...commitStats.get(commit.oid),
589 authors: commit.authors?.map(
590 (author) =>
591 withAvatar(
592 author,
593 reviewThreads.avatarsByLogin,
594 input.host,
595 reviewThreads.botLogins,
596 ) ?? author,
597 ),
598 })),
599 comments: [...pullRequest.comments, ...reviewThreads.comments]
600 .map((comment) => ({
601 ...comment,
602 // Dismissal reasons live on timeline events; HTML-only bot reviews need that fallback too.
603 body:
604 comment.kind === "review" &&
605 comment.reviewState?.toUpperCase() === "DISMISSED" &&
606 rendersEmpty(comment.body)
607 ? (reviewThreads.dismissalsByReviewId.get(comment.id) ?? comment.body)
608 : comment.body,
609 author: withAvatar(
610 comment.author,
611 reviewThreads.avatarsByLogin,
612 input.host,
613 reviewThreads.botLogins,
614 ),
615 reactions: comment.reactions ?? reviewThreads.reactionsById.get(comment.id) ?? [],
616 editedAt: reviewThreads.editedAtById.get(comment.id) ?? comment.editedAt ?? null,
617 }))
618 .toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
619 commentCount: pullRequest.comments.length + reviewThreads.commentCount,
620 commentsTruncated: reviewThreads.truncated,
621 reviewThreadsTruncated: reviewThreads.reviewThreadsTruncated,
622 reviewThreads: reviewThreads.reviewThreads.map((thread) => ({
623 ...thread,
624 comments: thread.comments.map((comment) => ({
625 ...comment,
626 author: withAvatar(
627 comment.author,
628 reviewThreads.avatarsByLogin,
629 input.host,
630 reviewThreads.botLogins,
631 ),
632 })),
633 })),
634 };
635 }),
636 ),
637​
638 getReviewThreadComments: (input) =>
639 cli.getReviewThreadComments(input).pipe(Effect.mapError(fail("getReviewThreadComments"))),
640​
641 getViewerPermissions: (input) => {
642 const lightAccess = cli
643 .getViewerAccess({ ...input, allowReserve: true })
644 .pipe(Effect.map((access) => gitHubViewerPermissions(access)));
645 if (input.includeUpdateBranch === false) {
646 return lightAccess.pipe(Effect.mapError(fail("getViewerPermissions")));
647 }
648 return cli.getPullRequestDetail(input).pipe(
649 Effect.provideService(SourceControlRateLimit.Interactive, true),
650 Effect.map((pullRequest) =>
651 gitHubViewerPermissions({
652 ...pullRequest.viewerAccess,
653 canUpdateBranch:
654 pullRequest.state === "open" && pullRequest.comparison?.viewerCanUpdate === true,
655 }),
656 ),
657 Effect.catchIf(
658 (error) =>
659 error._tag !== "GitHubApiRateLimitError" &&
660 error._tag !== "SourceControlRateLimitPausedError",
661 () => lightAccess,
662 ),
663 Effect.mapError(fail("getViewerPermissions")),
664 );
665 },
666​
667 getDiff: (input) => cli.getPullRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
668​
669 getDiffFileContents: (input) =>
670 cli.getPullRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),
671​
672 getFilesViewed: (input) =>
673 cli.getPullRequestFilesViewed(input).pipe(Effect.mapError(fail("getFilesViewed"))),
674​
675 getFileStats: (input) =>
676 cli.getPullRequestFileStats(input).pipe(Effect.mapError(fail("getFileStats"))),
677 setFilesViewed: (input) =>
678 cli.setPullRequestFilesViewed(input).pipe(Effect.mapError(fail("setFilesViewed"))),
679​
680 listReviewerCandidates: (input) =>
681 cli.listReviewerCandidates(input).pipe(Effect.mapError(fail("listReviewerCandidates"))),
682​
683 setReviewerRequest: (input) =>
684 cli
685 .setReviewerRequest({
686 cwd: input.cwd,
687 repository: input.repository,
688 host: input.host,
689 number: input.number,
690 reviewers: input.reviewers,
691 requested: input.requested,
692 })
693 .pipe(Effect.mapError(fail("setReviewerRequest"))),
694​
695 listLabelCandidates: (input) =>
696 cli.listLabelCandidates(input).pipe(Effect.mapError(fail("listLabelCandidates"))),
697​
698 listRepositoryLabels: (input) =>
699 cli.listRepositoryLabels(input).pipe(Effect.mapError(fail("listRepositoryLabels"))),
700​
701 searchRepositoryAuthors: (input) =>
702 cli.searchRepositoryAuthors(input).pipe(Effect.mapError(fail("searchRepositoryAuthors"))),
703​
704 searchRepositoryReferences: (input) =>
705 cli
706 .searchRepositoryReferences(input)
707 .pipe(Effect.mapError(fail("searchRepositoryReferences"))),
708​
709 setLabels: (input) =>
710 cli
711 .setLabels({
712 cwd: input.cwd,
713 repository: input.repository,
714 host: input.host,
715 number: input.number,
716 labels: input.labels,
717 applied: input.applied,
718 })
719 .pipe(Effect.mapError(fail("setLabels"))),
720​
721 runAction: (input) =>
722 cli
723 .runPullRequestAction({
724 cwd: input.cwd,
725 repository: input.repository,
726 host: input.host,
727 number: input.number,
728 action: input.action,
729 ...(input.removeAgentCreditsOnMerge === true ? { removeAgentCreditsOnMerge: true } : {}),
730 ...(input.stackNumber === undefined ? {} : { stackNumber: input.stackNumber }),
731 ...(input.expectedStackHeads === undefined
732 ? {}
733 : { expectedStackHeads: input.expectedStackHeads }),
734 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
735 ...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
736 })
737 .pipe(Effect.mapError(fail("runAction"))),
738​
739 updateChangeRequest: (input) =>
740 cli
741 .updatePullRequest({
742 ...(input.maintainerCanModify === undefined
743 ? {}
744 : { maintainerCanModify: input.maintainerCanModify }),
745 cwd: input.cwd,
746 repository: input.repository,
747 host: input.host,
748 number: input.number,
749 ...(input.title === undefined ? {} : { title: input.title }),
750 ...(input.body === undefined ? {} : { body: input.body }),
751 })
752 .pipe(Effect.mapError(fail("updateChangeRequest"))),
753​
754 comment: (input) => cli.commentOnPullRequest(input).pipe(Effect.mapError(fail("comment"))),
755​
756 updateComment: (input) =>
757 cli
758 .updateComment({
759 cwd: input.cwd,
760 repository: input.repository,
761 host: input.host,
762 number: input.number,
763 commentId: input.commentId,
764 kind: input.kind,
765 body: input.body,
766 })
767 .pipe(Effect.mapError(fail("updateComment"))),
768​
769 submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
770​
771 replyToThread: (input) =>
772 cli
773 .replyToReviewThread({
774 cwd: input.cwd,
775 repository: input.repository,
776 host: input.host,
777 threadId: input.threadId,
778 body: input.body,
779 })
780 .pipe(Effect.mapError(fail("replyToThread"))),
781​
782 setReaction: (input) =>
783 cli
784 .setReaction({
785 cwd: input.cwd,
786 repository: input.repository,
787 host: input.host,
788 number: input.number,
789 ...(input.subjectId === undefined ? {} : { subjectId: input.subjectId }),
790 content: input.content,
791 reacted: input.reacted,
792 })
793 .pipe(Effect.mapError(fail("setReaction"))),
794​
795 setThreadResolution: (input) =>
796 cli
797 .setReviewThreadResolution({
798 cwd: input.cwd,
799 repository: input.repository,
800 host: input.host,
801 threadId: input.threadId,
802 resolved: input.resolved,
803 })
804 .pipe(Effect.mapError(fail("setThreadResolution"))),
805 };
806​
807 return provider;
808});