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

GitHubPullRequestProvider.ts

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