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 getChangeRequestPreview: (input) =>
457 cli.getPullRequestPreview(input).pipe(Effect.mapError(fail("getChangeRequestPreview"))),
458
459 getChangeRequestChecks: (input) =>
460 cli.revalidateChecks(input, readChecks(input)).pipe(
461 Effect.map(({ state, checks }) => ({ state, checks })),
462 Effect.mapError(fail("getChangeRequestChecks")),
463 ),
464
465 getChangeRequest: (input) =>
466 readChecks(input).pipe(
467 Effect.map((pullRequest): ProviderChangeRequestDetail => ({
468 ...pullRequest,
469 author: withAvatar(pullRequest.author, new Map<string, string>(), input.host),
470 reviewers: [
471 ...pullRequest.reviewRequestLogins.map((login) => ({
472 login,
473 name: null,
474 avatarUrl: null,
475 })),
476 ...pullRequest.reviewRequestTeams,
477 ],
478 mergeCapabilities: pullRequest.viewerAccess.mergeCapabilities,
479 viewerPermissions: {
480 ...gitHubViewerPermissions({
481 ...pullRequest.viewerAccess,
482 canUpdateBranch: pullRequest.comparison?.viewerCanUpdate === true,
483 }),
484 maintainerEdits: pullRequest.canEditMaintainerEdits,
485 },
486 baseComparison:
487 pullRequest.comparison === null || pullRequest.comparison.behindBy === null
488 ? "unknown"
489 : pullRequest.comparison.behindBy > 0
490 ? "behind"
491 : "up-to-date",
492 ...(pullRequest.comparison?.behindBy == null
493 ? {}
494 : { behindBy: pullRequest.comparison.behindBy }),
495 })),
496 Effect.mapError(fail("getChangeRequest")),
497 ),
498
499 getChangeRequestActivity: (input) =>
500 Effect.all(
501 [
502 cli.getPullRequestActivity(input),
503 cli.listReviewThreadComments(input).pipe(
504 Effect.orElseSucceed(() => ({
505 comments: [],
506 dismissalsByReviewId: new Map<string, string>(),
507 reactions: [],
508 reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
509 editedAtById: new Map<string, string>(),
510 reviewThreads: [],
511 commentCount: 0,
512 truncated: true,
513 reviewThreadsTruncated: true,
514 reviewers: [],
515 avatarsByLogin: new Map<string, string>(),
516 botLogins: new Set<string>(),
517 commits: [],
518 viewer: { canUpdate: true, didAuthor: false },
519 })),
520 ),
521 ],
522 { concurrency: 2 },
523 ).pipe(
524 Effect.mapError(fail("getChangeRequestActivity")),
525 Effect.map(([pullRequest, reviewThreads]): ProviderChangeRequestActivity => {
526 const commitStats = new Map(
527 pullRequest.commits.map(({ oid, additions, deletions }) => [
528 oid,
529 additions === undefined ? {} : { additions, deletions },
530 ]),
531 );
532 return {
533 author: withAvatar(
534 pullRequest.author,
535 reviewThreads.avatarsByLogin,
536 input.host,
537 reviewThreads.botLogins,
538 ),
539 reviewers: reviewThreads.reviewers,
540 reactions: reviewThreads.reactions,
541 commits: (reviewThreads.commits.length > 0
542 ? reviewThreads.commits
543 : pullRequest.commits
544 ).map((commit) => ({
545 ...commit,
546 ...commitStats.get(commit.oid),
547 authors: commit.authors?.map(
548 (author) =>
549 withAvatar(
550 author,
551 reviewThreads.avatarsByLogin,
552 input.host,
553 reviewThreads.botLogins,
554 ) ?? author,
555 ),
556 })),
557 comments: [...pullRequest.comments, ...reviewThreads.comments]
558 .map((comment) => ({
559 ...comment,
560 // Dismissal reasons live on timeline events; HTML-only bot reviews need that fallback too.
561 body:
562 comment.kind === "review" &&
563 comment.reviewState?.toUpperCase() === "DISMISSED" &&
564 rendersEmpty(comment.body)
565 ? (reviewThreads.dismissalsByReviewId.get(comment.id) ?? comment.body)
566 : comment.body,
567 author: withAvatar(
568 comment.author,
569 reviewThreads.avatarsByLogin,
570 input.host,
571 reviewThreads.botLogins,
572 ),
573 reactions: comment.reactions ?? reviewThreads.reactionsById.get(comment.id) ?? [],
574 editedAt: reviewThreads.editedAtById.get(comment.id) ?? comment.editedAt ?? null,
575 }))
576 .toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
577 commentCount: pullRequest.comments.length + reviewThreads.commentCount,
578 commentsTruncated: reviewThreads.truncated,
579 reviewThreadsTruncated: reviewThreads.reviewThreadsTruncated,
580 reviewThreads: reviewThreads.reviewThreads.map((thread) => ({
581 ...thread,
582 comments: thread.comments.map((comment) => ({
583 ...comment,
584 author: withAvatar(
585 comment.author,
586 reviewThreads.avatarsByLogin,
587 input.host,
588 reviewThreads.botLogins,
589 ),
590 })),
591 })),
592 };
593 }),
594 ),
595
596 getReviewThreadComments: (input) =>
597 cli.getReviewThreadComments(input).pipe(Effect.mapError(fail("getReviewThreadComments"))),
598
599 getViewerPermissions: (input) => {
600 const lightAccess = cli
601 .getViewerAccess({ ...input, allowReserve: true })
602 .pipe(Effect.map((access) => gitHubViewerPermissions(access)));
603 if (input.includeUpdateBranch === false) {
604 return lightAccess.pipe(Effect.mapError(fail("getViewerPermissions")));
605 }
606 return cli.getPullRequestDetail(input).pipe(
607 Effect.provideService(SourceControlRateLimit.Interactive, true),
608 Effect.map((pullRequest) =>
609 gitHubViewerPermissions({
610 ...pullRequest.viewerAccess,
611 canUpdateBranch:
612 pullRequest.state === "open" && pullRequest.comparison?.viewerCanUpdate === true,
613 }),
614 ),
615 Effect.catchIf(
616 (error) =>
617 error._tag !== "GitHubApiRateLimitError" &&
618 error._tag !== "SourceControlRateLimitPausedError",
619 () => lightAccess,
620 ),
621 Effect.mapError(fail("getViewerPermissions")),
622 );
623 },
624
625 getDiff: (input) => cli.getPullRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
626
627 getDiffFileContents: (input) =>
628 cli.getPullRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),
629
630 getFilesViewed: (input) =>
631 cli.getPullRequestFilesViewed(input).pipe(Effect.mapError(fail("getFilesViewed"))),
632
633 getFileStats: (input) =>
634 cli.getPullRequestFileStats(input).pipe(Effect.mapError(fail("getFileStats"))),
635 setFilesViewed: (input) =>
636 cli.setPullRequestFilesViewed(input).pipe(Effect.mapError(fail("setFilesViewed"))),
637
638 listReviewerCandidates: (input) =>
639 cli.listReviewerCandidates(input).pipe(Effect.mapError(fail("listReviewerCandidates"))),
640
641 setReviewerRequest: (input) =>
642 cli
643 .setReviewerRequest({
644 cwd: input.cwd,
645 repository: input.repository,
646 host: input.host,
647 number: input.number,
648 reviewers: input.reviewers,
649 requested: input.requested,
650 })
651 .pipe(Effect.mapError(fail("setReviewerRequest"))),
652
653 listLabelCandidates: (input) =>
654 cli.listLabelCandidates(input).pipe(Effect.mapError(fail("listLabelCandidates"))),
655
656 listRepositoryLabels: (input) =>
657 cli.listRepositoryLabels(input).pipe(Effect.mapError(fail("listRepositoryLabels"))),
658
659 searchRepositoryAuthors: (input) =>
660 cli.searchRepositoryAuthors(input).pipe(Effect.mapError(fail("searchRepositoryAuthors"))),
661
662 searchRepositoryReferences: (input) =>
663 cli
664 .searchRepositoryReferences(input)
665 .pipe(Effect.mapError(fail("searchRepositoryReferences"))),
666
667 setLabels: (input) =>
668 cli
669 .setLabels({
670 cwd: input.cwd,
671 repository: input.repository,
672 host: input.host,
673 number: input.number,
674 labels: input.labels,
675 applied: input.applied,
676 })
677 .pipe(Effect.mapError(fail("setLabels"))),
678
679 runAction: (input) =>
680 cli
681 .runPullRequestAction({
682 cwd: input.cwd,
683 repository: input.repository,
684 host: input.host,
685 number: input.number,
686 action: input.action,
687 ...(input.removeAgentCreditsOnMerge === true ? { removeAgentCreditsOnMerge: true } : {}),
688 ...(input.stackNumber === undefined ? {} : { stackNumber: input.stackNumber }),
689 ...(input.expectedStackHeads === undefined
690 ? {}
691 : { expectedStackHeads: input.expectedStackHeads }),
692 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
693 ...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
694 })
695 .pipe(Effect.mapError(fail("runAction"))),
696
697 updateChangeRequest: (input) =>
698 cli
699 .updatePullRequest({
700 ...(input.maintainerCanModify === undefined
701 ? {}
702 : { maintainerCanModify: input.maintainerCanModify }),
703 cwd: input.cwd,
704 repository: input.repository,
705 host: input.host,
706 number: input.number,
707 ...(input.title === undefined ? {} : { title: input.title }),
708 ...(input.body === undefined ? {} : { body: input.body }),
709 })
710 .pipe(Effect.mapError(fail("updateChangeRequest"))),
711
712 comment: (input) => cli.commentOnPullRequest(input).pipe(Effect.mapError(fail("comment"))),
713
714 updateComment: (input) =>
715 cli
716 .updateComment({
717 cwd: input.cwd,
718 repository: input.repository,
719 host: input.host,
720 number: input.number,
721 commentId: input.commentId,
722 kind: input.kind,
723 body: input.body,
724 })
725 .pipe(Effect.mapError(fail("updateComment"))),
726
727 submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
728
729 replyToThread: (input) =>
730 cli
731 .replyToReviewThread({
732 cwd: input.cwd,
733 repository: input.repository,
734 host: input.host,
735 threadId: input.threadId,
736 body: input.body,
737 })
738 .pipe(Effect.mapError(fail("replyToThread"))),
739
740 setReaction: (input) =>
741 cli
742 .setReaction({
743 cwd: input.cwd,
744 repository: input.repository,
745 host: input.host,
746 number: input.number,
747 ...(input.subjectId === undefined ? {} : { subjectId: input.subjectId }),
748 content: input.content,
749 reacted: input.reacted,
750 })
751 .pipe(Effect.mapError(fail("setReaction"))),
752
753 setThreadResolution: (input) =>
754 cli
755 .setReviewThreadResolution({
756 cwd: input.cwd,
757 repository: input.repository,
758 host: input.host,
759 threadId: input.threadId,
760 resolved: input.resolved,
761 })
762 .pipe(Effect.mapError(fail("setThreadResolution"))),
763 };
764
765 return provider;
766});