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