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