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.flatMap((page) =>
369 cli
370 .listActorAvatars({
371 cwd: input.cwd,
372 repository: input.repository,
373 host: input.host,
374 ids: [...new Set(page.items.flatMap((item) => item.authorId ?? []))],
375 })
376 .pipe(
377 Effect.orElseSucceed(() => new Map<string, string>()),
378 Effect.map((avatarsByLogin) => ({
379 ...page,
380 items: page.items.map((item) => ({
381 ...item,
382 author: withAvatar(item.author, avatarsByLogin, input.host),
383 })),
384 })),
385 ),
386 ),
387 ),
388
389 listChangeRequestsAcross: (input) =>
390 cli
391 .searchPullRequests({
392 cwd: input.cwd,
393 host: input.host,
394 repositories: input.repositories,
395 state: input.state,
396 involvement: input.involvement,
397 viewer: input.viewer,
398 limit: input.limit,
399 query: input.query,
400 cursor: input.cursor,
401 filters: input.filters,
402 })
403 .pipe(
404 Effect.mapError(fail("listChangeRequestsAcross")),
405 Effect.flatMap((batch) =>
406 Effect.map(unresolvedBySearch(input, batch), (unresolved) => ({
407 truncated: batch.truncated,
408 items: batch.items.map((item) => ({
409 ...item,
410 author: withAvatar(item.author, new Map<string, string>(), input.host),
411 })),
412 unresolved,
413 })),
414 ),
415 ),
416
417 listChangeRequestStats: (input) =>
418 cli
419 .listPullRequestStats({
420 cwd: input.cwd,
421 host: input.host,
422 changeRequests: input.changeRequests,
423 })
424 .pipe(Effect.mapError(fail("listChangeRequestStats"))),
425
426 getChangeRequestSummary: (input) =>
427 cli.getPullRequestSummary(input).pipe(
428 Effect.map((summary) => ({
429 ...summary,
430 ...(summary.author === undefined
431 ? {}
432 : { author: withAvatar(summary.author, new Map(), input.host) }),
433 })),
434 Effect.mapError(fail("getChangeRequestSummary")),
435 ),
436
437 getChangeRequestStack: (input) =>
438 cli.getPullRequestStack(input).pipe(Effect.mapError(fail("getChangeRequestStack"))),
439
440 getChangeRequestWatchFingerprint: (input) =>
441 cli
442 .getPullRequestWatchFingerprint(input)
443 .pipe(Effect.mapError(fail("getChangeRequestWatchFingerprint"))),
444
445 getChangeRequestPreview: (input) =>
446 cli.getPullRequestPreview(input).pipe(Effect.mapError(fail("getChangeRequestPreview"))),
447
448 getChangeRequestChecks: (input) =>
449 cli.revalidateChecks(input, readChecks(input)).pipe(
450 Effect.map(({ state, checks }) => ({ state, checks })),
451 Effect.mapError(fail("getChangeRequestChecks")),
452 ),
453
454 getChangeRequest: (input) =>
455 readChecks(input).pipe(
456 Effect.map((pullRequest): ProviderChangeRequestDetail => ({
457 ...pullRequest,
458 author: withAvatar(pullRequest.author, new Map<string, string>(), input.host),
459 reviewers: [
460 ...pullRequest.reviewRequestLogins.map((login) => ({
461 login,
462 name: null,
463 avatarUrl: null,
464 })),
465 ...pullRequest.reviewRequestTeams,
466 ],
467 mergeCapabilities: pullRequest.viewerAccess.mergeCapabilities,
468 viewerPermissions: gitHubViewerPermissions({
469 ...pullRequest.viewerAccess,
470 canUpdateBranch: pullRequest.comparison?.viewerCanUpdate === true,
471 }),
472 baseComparison:
473 pullRequest.comparison === null || pullRequest.comparison.behindBy === null
474 ? "unknown"
475 : pullRequest.comparison.behindBy > 0
476 ? "behind"
477 : "up-to-date",
478 ...(pullRequest.comparison?.behindBy == null
479 ? {}
480 : { behindBy: pullRequest.comparison.behindBy }),
481 })),
482 Effect.mapError(fail("getChangeRequest")),
483 ),
484
485 getChangeRequestActivity: (input) =>
486 Effect.all(
487 [
488 cli.getPullRequestActivity(input),
489 cli.listReviewThreadComments(input).pipe(
490 Effect.orElseSucceed(() => ({
491 comments: [],
492 dismissalsByReviewId: new Map<string, string>(),
493 reactions: [],
494 reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
495 editedAtById: new Map<string, string>(),
496 reviewThreads: [],
497 commentCount: 0,
498 truncated: true,
499 reviewThreadsTruncated: true,
500 reviewers: [],
501 avatarsByLogin: new Map<string, string>(),
502 botLogins: new Set<string>(),
503 commitStats: new Map<
504 string,
505 { readonly additions: number; readonly deletions: number }
506 >(),
507 commits: [],
508 viewer: { canUpdate: true, didAuthor: false },
509 })),
510 ),
511 ],
512 { concurrency: 2 },
513 ).pipe(
514 Effect.mapError(fail("getChangeRequestActivity")),
515 Effect.map(([pullRequest, reviewThreads]): ProviderChangeRequestActivity => ({
516 author: withAvatar(
517 pullRequest.author,
518 reviewThreads.avatarsByLogin,
519 input.host,
520 reviewThreads.botLogins,
521 ),
522 reviewers: reviewThreads.reviewers,
523 reactions: reviewThreads.reactions,
524 commits: (reviewThreads.commits.length > 0
525 ? reviewThreads.commits
526 : pullRequest.commits
527 ).map((commit) => ({
528 ...commit,
529 ...reviewThreads.commitStats.get(commit.oid),
530 authors: commit.authors?.map(
531 (author) =>
532 withAvatar(
533 author,
534 reviewThreads.avatarsByLogin,
535 input.host,
536 reviewThreads.botLogins,
537 ) ?? author,
538 ),
539 })),
540 comments: [...pullRequest.comments, ...reviewThreads.comments]
541 .map((comment) => ({
542 ...comment,
543 // Dismissal reasons live on timeline events; HTML-only bot reviews need that fallback too.
544 body:
545 comment.kind === "review" &&
546 comment.reviewState?.toUpperCase() === "DISMISSED" &&
547 rendersEmpty(comment.body)
548 ? (reviewThreads.dismissalsByReviewId.get(comment.id) ?? comment.body)
549 : comment.body,
550 author: withAvatar(
551 comment.author,
552 reviewThreads.avatarsByLogin,
553 input.host,
554 reviewThreads.botLogins,
555 ),
556 reactions: comment.reactions ?? reviewThreads.reactionsById.get(comment.id) ?? [],
557 editedAt: reviewThreads.editedAtById.get(comment.id) ?? comment.editedAt ?? null,
558 }))
559 .toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
560 commentCount: pullRequest.comments.length + reviewThreads.commentCount,
561 commentsTruncated: reviewThreads.truncated,
562 reviewThreadsTruncated: reviewThreads.reviewThreadsTruncated,
563 reviewThreads: reviewThreads.reviewThreads.map((thread) => ({
564 ...thread,
565 comments: thread.comments.map((comment) => ({
566 ...comment,
567 author: withAvatar(
568 comment.author,
569 reviewThreads.avatarsByLogin,
570 input.host,
571 reviewThreads.botLogins,
572 ),
573 })),
574 })),
575 })),
576 ),
577
578 getReviewThreadComments: (input) =>
579 cli.getReviewThreadComments(input).pipe(Effect.mapError(fail("getReviewThreadComments"))),
580
581 getViewerPermissions: (input) => {
582 const lightAccess = cli
583 .getViewerAccess({ ...input, allowReserve: true })
584 .pipe(Effect.map((access) => gitHubViewerPermissions(access)));
585 if (input.includeUpdateBranch === false) {
586 return lightAccess.pipe(Effect.mapError(fail("getViewerPermissions")));
587 }
588 return cli.getPullRequestDetail(input).pipe(
589 Effect.provideService(SourceControlRateLimit.Interactive, true),
590 Effect.map((pullRequest) =>
591 gitHubViewerPermissions({
592 ...pullRequest.viewerAccess,
593 canUpdateBranch:
594 pullRequest.state === "open" && pullRequest.comparison?.viewerCanUpdate === true,
595 }),
596 ),
597 Effect.catchIf(
598 (error) =>
599 error._tag !== "GitHubApiRateLimitError" &&
600 error._tag !== "SourceControlRateLimitPausedError",
601 () => lightAccess,
602 ),
603 Effect.mapError(fail("getViewerPermissions")),
604 );
605 },
606
607 getDiff: (input) => cli.getPullRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
608
609 getDiffFileContents: (input) =>
610 cli.getPullRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),
611
612 getFilesViewed: (input) =>
613 cli.getPullRequestFilesViewed(input).pipe(Effect.mapError(fail("getFilesViewed"))),
614
615 getFileStats: (input) =>
616 cli.getPullRequestFileStats(input).pipe(Effect.mapError(fail("getFileStats"))),
617 setFilesViewed: (input) =>
618 cli.setPullRequestFilesViewed(input).pipe(Effect.mapError(fail("setFilesViewed"))),
619
620 listReviewerCandidates: (input) =>
621 cli.listReviewerCandidates(input).pipe(Effect.mapError(fail("listReviewerCandidates"))),
622
623 setReviewerRequest: (input) =>
624 cli
625 .setReviewerRequest({
626 cwd: input.cwd,
627 repository: input.repository,
628 host: input.host,
629 number: input.number,
630 reviewers: input.reviewers,
631 requested: input.requested,
632 })
633 .pipe(Effect.mapError(fail("setReviewerRequest"))),
634
635 listLabelCandidates: (input) =>
636 cli.listLabelCandidates(input).pipe(Effect.mapError(fail("listLabelCandidates"))),
637
638 listRepositoryLabels: (input) =>
639 cli.listRepositoryLabels(input).pipe(Effect.mapError(fail("listRepositoryLabels"))),
640
641 searchRepositoryAuthors: (input) =>
642 cli.searchRepositoryAuthors(input).pipe(Effect.mapError(fail("searchRepositoryAuthors"))),
643
644 setLabels: (input) =>
645 cli
646 .setLabels({
647 cwd: input.cwd,
648 repository: input.repository,
649 host: input.host,
650 number: input.number,
651 labels: input.labels,
652 applied: input.applied,
653 })
654 .pipe(Effect.mapError(fail("setLabels"))),
655
656 runAction: (input) =>
657 cli
658 .runPullRequestAction({
659 cwd: input.cwd,
660 repository: input.repository,
661 host: input.host,
662 number: input.number,
663 action: input.action,
664 ...(input.removeAgentCreditsOnMerge === true ? { removeAgentCreditsOnMerge: true } : {}),
665 ...(input.stackNumber === undefined ? {} : { stackNumber: input.stackNumber }),
666 ...(input.expectedStackHeads === undefined
667 ? {}
668 : { expectedStackHeads: input.expectedStackHeads }),
669 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
670 ...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
671 })
672 .pipe(Effect.mapError(fail("runAction"))),
673
674 updateChangeRequest: (input) =>
675 cli
676 .updatePullRequest({
677 cwd: input.cwd,
678 repository: input.repository,
679 host: input.host,
680 number: input.number,
681 ...(input.title === undefined ? {} : { title: input.title }),
682 ...(input.body === undefined ? {} : { body: input.body }),
683 })
684 .pipe(Effect.mapError(fail("updateChangeRequest"))),
685
686 comment: (input) => cli.commentOnPullRequest(input).pipe(Effect.mapError(fail("comment"))),
687
688 updateComment: (input) =>
689 cli
690 .updateComment({
691 cwd: input.cwd,
692 repository: input.repository,
693 host: input.host,
694 number: input.number,
695 commentId: input.commentId,
696 kind: input.kind,
697 body: input.body,
698 })
699 .pipe(Effect.mapError(fail("updateComment"))),
700
701 submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
702
703 replyToThread: (input) =>
704 cli
705 .replyToReviewThread({
706 cwd: input.cwd,
707 repository: input.repository,
708 host: input.host,
709 threadId: input.threadId,
710 body: input.body,
711 })
712 .pipe(Effect.mapError(fail("replyToThread"))),
713
714 setReaction: (input) =>
715 cli
716 .setReaction({
717 cwd: input.cwd,
718 repository: input.repository,
719 host: input.host,
720 number: input.number,
721 ...(input.subjectId === undefined ? {} : { subjectId: input.subjectId }),
722 content: input.content,
723 reacted: input.reacted,
724 })
725 .pipe(Effect.mapError(fail("setReaction"))),
726
727 setThreadResolution: (input) =>
728 cli
729 .setReviewThreadResolution({
730 cwd: input.cwd,
731 repository: input.repository,
732 host: input.host,
733 threadId: input.threadId,
734 resolved: input.resolved,
735 })
736 .pipe(Effect.mapError(fail("setThreadResolution"))),
737 };
738
739 return provider;
740});