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
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 };
108}
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 }
144}
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 };
164}
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 ];
203}
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 ];
227}
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;
232}
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 }
262}
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" || pullRequest.isCrossRepository !== true
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: 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 }) => ({ state, checks })),
507 Effect.mapError(fail("getChangeRequestChecks")),
508 ),
509
510 getChangeRequest: (input) =>
511 readChecks(input).pipe(
512 Effect.map((pullRequest): ProviderChangeRequestDetail => ({
513 ...pullRequest,
514 author: withAvatar(pullRequest.author, new Map<string, string>(), input.host),
515 reviewers: [
516 ...pullRequest.reviewRequestLogins.map((login) => ({
517 login,
518 name: null,
519 avatarUrl: null,
520 })),
521 ...pullRequest.reviewRequestTeams,
522 ],
523 mergeCapabilities: pullRequest.viewerAccess.mergeCapabilities,
524 viewerPermissions: {
525 ...gitHubViewerPermissions({
526 ...pullRequest.viewerAccess,
527 canUpdateBranch: pullRequest.comparison?.viewerCanUpdate === true,
528 }),
529 maintainerEdits: pullRequest.canEditMaintainerEdits,
530 },
531 baseComparison:
532 pullRequest.comparison === null || pullRequest.comparison.behindBy === null
533 ? "unknown"
534 : pullRequest.comparison.behindBy > 0
535 ? "behind"
536 : "up-to-date",
537 ...(pullRequest.comparison?.behindBy == null
538 ? {}
539 : { behindBy: pullRequest.comparison.behindBy }),
540 })),
541 Effect.mapError(fail("getChangeRequest")),
542 ),
543
544 getChangeRequestActivity: (input) => {
545 const threadRead = cli.listReviewThreadComments(input).pipe(
546 Effect.catchIf(
547 (error) =>
548 error._tag !== "GitHubApiRateLimitError" &&
549 error._tag !== "SourceControlRateLimitPausedError",
550 () =>
551 Effect.succeed({
552 comments: [],
553 dismissalsByReviewId: new Map<string, string>(),
554 reactions: [],
555 reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
556 editedAtById: new Map<string, string>(),
557 reviewThreads: [],
558 commentCount: 0,
559 truncated: true,
560 reviewThreadsTruncated: true,
561 reviewers: [],
562 avatarsByLogin: new Map<string, string>(),
563 botLogins: new Set<string>(),
564 commits: [],
565 viewer: { canUpdate: true, didAuthor: false },
566 }),
567 ),
568 );
569 return Effect.all([cli.getPullRequestActivity(input), threadRead], {
570 concurrency: 2,
571 }).pipe(
572 Effect.mapError(fail("getChangeRequestActivity")),
573 Effect.map(([pullRequest, reviewThreads]): ProviderChangeRequestActivity => {
574 const commitStats = new Map(
575 pullRequest.commits.map(({ oid, additions, deletions }) => [
576 oid,
577 additions === undefined ? {} : { additions, deletions },
578 ]),
579 );
580 return {
581 author: withAvatar(
582 pullRequest.author,
583 reviewThreads.avatarsByLogin,
584 input.host,
585 reviewThreads.botLogins,
586 ),
587 reviewers: reviewThreads.reviewers,
588 reactions: reviewThreads.reactions,
589 commits: (reviewThreads.commits.length > 0
590 ? reviewThreads.commits
591 : pullRequest.commits
592 ).map((commit) => ({
593 ...commit,
594 ...commitStats.get(commit.oid),
595 authors: commit.authors?.map(
596 (author) =>
597 withAvatar(
598 author,
599 reviewThreads.avatarsByLogin,
600 input.host,
601 reviewThreads.botLogins,
602 ) ?? author,
603 ),
604 })),
605 comments: [...pullRequest.comments, ...reviewThreads.comments]
606 .map((comment) => ({
607 ...comment,
608 // Dismissal reasons live on timeline events; HTML-only bot reviews need that fallback too.
609 body:
610 comment.kind === "review" &&
611 comment.reviewState?.toUpperCase() === "DISMISSED" &&
612 rendersEmpty(comment.body)
613 ? (reviewThreads.dismissalsByReviewId.get(comment.id) ?? comment.body)
614 : comment.body,
615 author: withAvatar(
616 comment.author,
617 reviewThreads.avatarsByLogin,
618 input.host,
619 reviewThreads.botLogins,
620 ),
621 reactions: comment.reactions ?? reviewThreads.reactionsById.get(comment.id) ?? [],
622 editedAt: reviewThreads.editedAtById.get(comment.id) ?? comment.editedAt ?? null,
623 }))
624 .toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
625 commentCount: pullRequest.comments.length + reviewThreads.commentCount,
626 commentsTruncated: pullRequest.truncated || reviewThreads.truncated,
627 reviewThreadsTruncated: reviewThreads.reviewThreadsTruncated,
628 reviewThreads: reviewThreads.reviewThreads.map((thread) => ({
629 ...thread,
630 comments: thread.comments.map((comment) => ({
631 ...comment,
632 author: withAvatar(
633 comment.author,
634 reviewThreads.avatarsByLogin,
635 input.host,
636 reviewThreads.botLogins,
637 ),
638 })),
639 })),
640 };
641 }),
642 );
643 },
644
645 getReviewThreadComments: (input) =>
646 cli.getReviewThreadComments(input).pipe(Effect.mapError(fail("getReviewThreadComments"))),
647
648 getViewerPermissions: (input) => {
649 const lightAccess = cli
650 .getViewerAccess({ ...input, allowReserve: true })
651 .pipe(Effect.map((access) => gitHubViewerPermissions(access)));
652 if (input.includeUpdateBranch === false) {
653 return lightAccess.pipe(Effect.mapError(fail("getViewerPermissions")));
654 }
655 return cli.getPullRequestDetail(input).pipe(
656 Effect.provideService(SourceControlRateLimit.Interactive, true),
657 Effect.map((pullRequest) =>
658 gitHubViewerPermissions({
659 ...pullRequest.viewerAccess,
660 canUpdateBranch:
661 pullRequest.state === "open" && pullRequest.comparison?.viewerCanUpdate === true,
662 }),
663 ),
664 Effect.catchIf(
665 (error) =>
666 error._tag !== "GitHubApiRateLimitError" &&
667 error._tag !== "SourceControlRateLimitPausedError",
668 () => lightAccess,
669 ),
670 Effect.mapError(fail("getViewerPermissions")),
671 );
672 },
673
674 getDiff: (input) => cli.getPullRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
675
676 getDiffFileContents: (input) =>
677 cli.getPullRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),
678
679 getFilesViewed: (input) =>
680 cli.getPullRequestFilesViewed(input).pipe(Effect.mapError(fail("getFilesViewed"))),
681
682 getFileStats: (input) =>
683 cli.getPullRequestFileStats(input).pipe(Effect.mapError(fail("getFileStats"))),
684 setFilesViewed: (input) =>
685 cli.setPullRequestFilesViewed(input).pipe(Effect.mapError(fail("setFilesViewed"))),
686
687 listReviewerCandidates: (input) =>
688 cli.listReviewerCandidates(input).pipe(Effect.mapError(fail("listReviewerCandidates"))),
689
690 setReviewerRequest: (input) =>
691 cli
692 .setReviewerRequest({
693 cwd: input.cwd,
694 repository: input.repository,
695 host: input.host,
696 number: input.number,
697 reviewers: input.reviewers,
698 requested: input.requested,
699 })
700 .pipe(Effect.mapError(fail("setReviewerRequest"))),
701
702 listLabelCandidates: (input) =>
703 cli.listLabelCandidates(input).pipe(Effect.mapError(fail("listLabelCandidates"))),
704
705 listRepositoryLabels: (input) =>
706 cli.listRepositoryLabels(input).pipe(Effect.mapError(fail("listRepositoryLabels"))),
707
708 searchRepositoryAuthors: (input) =>
709 cli.searchRepositoryAuthors(input).pipe(Effect.mapError(fail("searchRepositoryAuthors"))),
710
711 searchRepositoryReferences: (input) =>
712 cli
713 .searchRepositoryReferences(input)
714 .pipe(Effect.mapError(fail("searchRepositoryReferences"))),
715
716 setLabels: (input) =>
717 cli
718 .setLabels({
719 cwd: input.cwd,
720 repository: input.repository,
721 host: input.host,
722 number: input.number,
723 labels: input.labels,
724 applied: input.applied,
725 })
726 .pipe(Effect.mapError(fail("setLabels"))),
727
728 runAction: (input) =>
729 cli
730 .runPullRequestAction({
731 cwd: input.cwd,
732 repository: input.repository,
733 host: input.host,
734 number: input.number,
735 action: input.action,
736 ...(input.removeAgentCreditsOnMerge === true ? { removeAgentCreditsOnMerge: true } : {}),
737 ...(input.stackNumber === undefined ? {} : { stackNumber: input.stackNumber }),
738 ...(input.expectedStackHeads === undefined
739 ? {}
740 : { expectedStackHeads: input.expectedStackHeads }),
741 ...(input.expectedHeadSha === undefined
742 ? {}
743 : { expectedHeadSha: input.expectedHeadSha }),
744 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
745 ...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
746 })
747 .pipe(Effect.mapError(fail("runAction"))),
748
749 getCheckLogs: (input) => cli.readCheckLogs(input).pipe(Effect.mapError(fail("getCheckLogs"))),
750 rerunChecks: (input) => cli.rerunChecks(input).pipe(Effect.mapError(fail("rerunChecks"))),
751
752 updateChangeRequest: (input) =>
753 cli
754 .updatePullRequest({
755 ...(input.maintainerCanModify === undefined
756 ? {}
757 : { maintainerCanModify: input.maintainerCanModify }),
758 cwd: input.cwd,
759 repository: input.repository,
760 host: input.host,
761 number: input.number,
762 ...(input.title === undefined ? {} : { title: input.title }),
763 ...(input.body === undefined ? {} : { body: input.body }),
764 })
765 .pipe(Effect.mapError(fail("updateChangeRequest"))),
766
767 comment: (input) => cli.commentOnPullRequest(input).pipe(Effect.mapError(fail("comment"))),
768
769 updateComment: (input) =>
770 cli
771 .updateComment({
772 cwd: input.cwd,
773 repository: input.repository,
774 host: input.host,
775 number: input.number,
776 commentId: input.commentId,
777 kind: input.kind,
778 body: input.body,
779 })
780 .pipe(Effect.mapError(fail("updateComment"))),
781
782 submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
783
784 replyToThread: (input) =>
785 cli
786 .replyToReviewThread({
787 cwd: input.cwd,
788 repository: input.repository,
789 host: input.host,
790 number: input.number,
791 threadId: input.threadId,
792 body: input.body,
793 })
794 .pipe(Effect.mapError(fail("replyToThread"))),
795
796 setReaction: (input) =>
797 cli
798 .setReaction({
799 cwd: input.cwd,
800 repository: input.repository,
801 host: input.host,
802 number: input.number,
803 ...(input.subjectId === undefined ? {} : { subjectId: input.subjectId }),
804 content: input.content,
805 reacted: input.reacted,
806 })
807 .pipe(Effect.mapError(fail("setReaction"))),
808
809 setThreadResolution: (input) =>
810 cli
811 .setReviewThreadResolution({
812 cwd: input.cwd,
813 repository: input.repository,
814 host: input.host,
815 number: input.number,
816 threadId: input.threadId,
817 resolved: input.resolved,
818 })
819 .pipe(Effect.mapError(fail("setThreadResolution"))),
820 };
821
822 return provider;
823});