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