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