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