Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Result from "effect/Result";
5import * as Schema from "effect/Schema";
6import type {
7 PullRequestAction,
8 PullRequestActor,
9 PullRequestInvolvement,
10 PullRequestListState,
11 PullRequestMergeMethod,
12 PullRequestReviewCommentDraft,
13 PullRequestReviewVerdict,
14 PullRequestReviewerCandidateList,
15 PullRequestReviewerKind,
16 PullRequestThreadComment,
17} from "@t3tools/contracts";
18
19import * as GitHubCli from "../sourceControl/GitHubCli.ts";
20import {
21 ACTOR_AVATARS_GRAPHQL_QUERY,
22 buildReviewSubmissionJson,
23 buildReviewerRequestJson,
24 decodeActorAvatarsJson,
25 decodePullRequestActivityJson,
26 decodePullRequestDetailJson,
27 decodePullRequestFilesJson,
28 decodePullRequestListJson,
29 decodePullRequestSearchJson,
30 decodePullRequestStatsJson,
31 decodeRepositoryAccessJson,
32 decodeReviewerCandidatesJson,
33 decodeReviewThreadCommentsJson,
34 decodeReviewThreadsJson,
35 buildPullRequestStatsGraphQlQuery,
36 encodeGraphQlRequestJson,
37 pullRequestSearchGraphQlQuery,
38 PULL_REQUEST_SEARCH_MAX_ROWS,
39 PULL_REQUEST_ACTIVITY_JSON_FIELDS,
40 PULL_REQUEST_DETAIL_JSON_FIELDS,
41 PULL_REQUEST_LIST_JSON_FIELDS,
42 REPOSITORY_ACCESS_JSON_FIELDS,
43 RESOLVE_REVIEW_THREAD_GRAPHQL_MUTATION,
44 REVIEWER_CANDIDATES_GRAPHQL_QUERY,
45 REVIEW_THREAD_COMMENTS_GRAPHQL_QUERY,
46 REVIEW_THREAD_REPLY_GRAPHQL_MUTATION,
47 REVIEW_THREADS_GRAPHQL_QUERY,
48 reviewThreadConversation,
49 UNRESOLVE_REVIEW_THREAD_GRAPHQL_MUTATION,
50 VIEWER_PERMISSIONS_GRAPHQL_QUERY,
51 decodeViewerPermissionsJson,
52 type GitHubPullRequestDetail,
53 type GitHubPullRequestActivity,
54 type GitHubPullRequestListItem,
55 type GitHubPullRequestSearchItem,
56 type GitHubReviewThreadComments,
57 type GitHubRepositoryAccess,
58 type GitHubReviewThreadEntry,
59 type GitHubReviewThreadPage,
60 type GitHubViewerAccess,
61} from "./gitHubPullRequestJson.ts";
62import type { ProviderListCursor } from "./PullRequestProvider.ts";
63
64/**
65 * Names the read that produced unusable output, so a failure reports the call it came from
66 * rather than borrowing another operation's message.
67 */
68export class GitHubPullRequestReadError extends Schema.TaggedErrorClass<GitHubPullRequestReadError>()(
69 "GitHubPullRequestReadError",
70 {
71 command: Schema.Literal("gh"),
72 cwd: Schema.String,
73 operation: Schema.String,
74 cause: Schema.Defect(),
75 },
76) {
77 get detail(): string {
78 return `GitHub CLI returned an unreadable ${this.operation} response.`;
79 }
80
81 override get message(): string {
82 return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
83 }
84}
85
86/** Not a decode failure: gh answered, the account it answered for just has no login. */
87export class GitHubViewerLoginUnavailableError extends Schema.TaggedErrorClass<GitHubViewerLoginUnavailableError>()(
88 "GitHubViewerLoginUnavailableError",
89 {
90 command: Schema.Literal("gh"),
91 cwd: Schema.String,
92 },
93) {
94 get detail(): string {
95 return "GitHub CLI returned no login for the authenticated account.";
96 }
97
98 override get message(): string {
99 return `GitHub CLI failed in getViewerLogin: ${this.detail}`;
100 }
101}
102
103/** Not a decode failure: the reader asked to carry on from a cursor this walk never handed out. */
104export class GitHubDiffCursorError extends Schema.TaggedErrorClass<GitHubDiffCursorError>()(
105 "GitHubDiffCursorError",
106 {
107 command: Schema.Literal("gh"),
108 cwd: Schema.String,
109 },
110) {
111 get detail(): string {
112 return "The diff cursor was not one this pull request handed out.";
113 }
114
115 override get message(): string {
116 return `GitHub CLI failed in getPullRequestDiff: ${this.detail}`;
117 }
118}
119
120/** Not a decode failure: the reader named a commit that is not a sha this repository could hold. */
121export class GitHubDiffCommitError extends Schema.TaggedErrorClass<GitHubDiffCommitError>()(
122 "GitHubDiffCommitError",
123 {
124 command: Schema.Literal("gh"),
125 cwd: Schema.String,
126 },
127) {
128 get detail(): string {
129 return "The named commit was not a commit sha.";
130 }
131
132 override get message(): string {
133 return `GitHub CLI failed in getPullRequestDiff: ${this.detail}`;
134 }
135}
136
137/** The revisions read successfully, but cannot name both sides this file needs. */
138export class GitHubDiffRevisionsUnavailableError extends Schema.TaggedErrorClass<GitHubDiffRevisionsUnavailableError>()(
139 "GitHubDiffRevisionsUnavailableError",
140 {
141 command: Schema.Literal("gh"),
142 cwd: Schema.String,
143 number: Schema.Int,
144 commit: Schema.optional(Schema.String),
145 },
146) {
147 get detail(): string {
148 return this.commit === undefined
149 ? `Pull request #${this.number} reported no usable base and head revisions.`
150 : `Commit ${this.commit} reported no usable revisions for this file.`;
151 }
152
153 override get message(): string {
154 return `GitHub CLI failed in getPullRequestDiffFileContents: ${this.detail}`;
155 }
156}
157
158/** A blob exists, but expanding it would be unsafe or would not produce text. */
159export class GitHubDiffFileContentsUnavailableError extends Schema.TaggedErrorClass<GitHubDiffFileContentsUnavailableError>()(
160 "GitHubDiffFileContentsUnavailableError",
161 {
162 command: Schema.Literal("gh"),
163 cwd: Schema.String,
164 path: Schema.String,
165 reason: Schema.Literals(["oversized", "binary"]),
166 },
167) {
168 get detail(): string {
169 return this.reason === "oversized"
170 ? `The diff file '${this.path}' exceeds the 1 MB expansion limit.`
171 : `The diff file '${this.path}' is binary.`;
172 }
173
174 override get message(): string {
175 return `GitHub CLI failed in getPullRequestDiffFileContents: ${this.detail}`;
176 }
177}
178
179/**
180 * Not a decode failure: a repository was named that cannot go into a search or into a GraphQL
181 * document as itself. Every qualifier and every alias below is composed from `owner/name`, so a
182 * name that is not one is refused here rather than escaped into something GitHub might read as a
183 * qualifier of its own.
184 */
185export class GitHubRepositorySelectorError extends Schema.TaggedErrorClass<GitHubRepositorySelectorError>()(
186 "GitHubRepositorySelectorError",
187 {
188 command: Schema.Literal("gh"),
189 cwd: Schema.String,
190 operation: Schema.String,
191 },
192) {
193 get detail(): string {
194 return "A repository was named that GitHub cannot address.";
195 }
196
197 override get message(): string {
198 return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
199 }
200}
201
202export type GitHubPullRequestCliError =
203 | GitHubCli.GitHubCliError
204 | GitHubPullRequestReadError
205 | GitHubDiffCursorError
206 | GitHubDiffCommitError
207 | GitHubDiffRevisionsUnavailableError
208 | GitHubDiffFileContentsUnavailableError
209 | GitHubRepositorySelectorError
210 | GitHubViewerLoginUnavailableError;
211
212/** A large pull request can produce a multi-megabyte patch; past this it is truncated. */
213const DIFF_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
214const DIFF_TIMEOUT_MS = 60_000;
215/** Pierre expansion is for source files, not blobs large enough to stall a review surface. */
216const DIFF_FILE_MAX_OUTPUT_BYTES = 1024 * 1024;
217
218/** A search-free fallback may scan older rows for local filters, but never the whole repository. */
219const PULL_REQUEST_FALLBACK_MAX_ROWS = 1_000;
220
221/** What the files API serves at most in one response, which is what one slice is made of. */
222const DIFF_FILES_PAGE_SIZE = 100;
223
224/**
225 * Pages of review threads to follow before the conversation is reported as truncated. GitHub
226 * serves a hundred threads a page, so this is a thousand threads — past anything a pull request
227 * a person is reading has, and short of walking a repository-sized conversation forever.
228 */
229const REVIEW_THREAD_PAGES = 10;
230
231/**
232 * And pages of one thread's own comments, for the rare thread longer than a single page. A
233 * thousand replies under one line is already a conversation nobody finishes reading.
234 */
235const REVIEW_THREAD_COMMENT_PAGES = 10;
236
237/** How many over-long threads are finished at once, so a wide conversation is not read serially. */
238const REVIEW_THREAD_CONCURRENCY = 4;
239
240export interface GitHubPullRequestListBatch {
241 readonly items: ReadonlyArray<GitHubPullRequestListItem>;
242 readonly truncated: boolean;
243 /** False for a page GitHub would not search, which came back in `gh`'s own order instead. */
244 readonly continues: boolean;
245}
246
247export interface GitHubPullRequestStat {
248 readonly repository: string;
249 readonly number: number;
250 readonly additions: number;
251 readonly deletions: number;
252}
253
254/**
255 * Aliased lookups per request, and requests at once. Measured over a hundred rows: one request
256 * carrying all hundred takes ~5.2s, four of twenty-five in parallel ~2.1s.
257 */
258const STAT_ALIASES_PER_REQUEST = 25;
259const STAT_REQUEST_CONCURRENCY = 4;
260
261export interface GitHubPullRequestSearchBatch {
262 /** Rows across every repository asked for, newest update first, each naming its own. */
263 readonly items: ReadonlyArray<GitHubPullRequestSearchItem>;
264 readonly truncated: boolean;
265}
266
267export interface GitHubPullRequestDiffSlice {
268 readonly patch: string;
269 /** Files in this slice had their hunks withheld, as opposed to there being more slices. */
270 readonly truncated: boolean;
271 /** Where the next slice starts, or null once the patch is whole. */
272 readonly nextCursor: string | null;
273}
274
275export class GitHubPullRequestCli extends Context.Service<
276 GitHubPullRequestCli,
277 {
278 readonly getViewerLogin: (input: {
279 readonly cwd: string;
280 }) => Effect.Effect<string, GitHubPullRequestCliError>;
281
282 readonly listPullRequests: (input: {
283 readonly cwd: string;
284 readonly repository: string;
285 readonly host: string;
286 readonly state: PullRequestListState;
287 readonly involvement: PullRequestInvolvement;
288 readonly viewer: string;
289 readonly limit: number;
290 /** Free text for `--search`, matched as one literal phrase. */
291 readonly query?: string | undefined;
292 /** Where to carry on from, as a `updated:` qualifier on the same search. */
293 readonly cursor?: ProviderListCursor | undefined;
294 }) => Effect.Effect<GitHubPullRequestListBatch, GitHubPullRequestCliError>;
295
296 /**
297 * The same listing for a whole host in one search. `limit` is the size of the slice across
298 * all of the repositories rather than per repository, because that is what a search answers:
299 * the newest rows of the lot, which is exactly the page.
300 */
301 readonly searchPullRequests: (input: {
302 /** Any checkout on the host; the search names its repositories itself. */
303 readonly cwd: string;
304 readonly host: string;
305 readonly repositories: ReadonlyArray<string>;
306 readonly state: PullRequestListState;
307 readonly involvement: PullRequestInvolvement;
308 readonly viewer: string;
309 readonly limit: number;
310 readonly query?: string | undefined;
311 readonly cursor?: ProviderListCursor | undefined;
312 }) => Effect.Effect<GitHubPullRequestSearchBatch, GitHubPullRequestCliError>;
313
314 /** The line counts the search leaves out, for rows already on the page. */
315 readonly listPullRequestStats: (input: {
316 readonly cwd: string;
317 readonly host: string;
318 readonly changeRequests: ReadonlyArray<{
319 readonly repository: string;
320 readonly number: number;
321 }>;
322 }) => Effect.Effect<ReadonlyArray<GitHubPullRequestStat>, GitHubPullRequestCliError>;
323
324 readonly getPullRequestDetail: (input: {
325 readonly cwd: string;
326 readonly repository: string;
327 readonly host: string;
328 readonly number: number;
329 }) => Effect.Effect<GitHubPullRequestDetail, GitHubPullRequestCliError>;
330
331 readonly getPullRequestActivity: (input: {
332 readonly cwd: string;
333 readonly repository: string;
334 readonly host: string;
335 readonly number: number;
336 }) => Effect.Effect<GitHubPullRequestActivity, GitHubPullRequestCliError>;
337
338 readonly getPullRequestDiff: (input: {
339 readonly cwd: string;
340 readonly repository: string;
341 readonly host: string;
342 readonly number: number;
343 /** Absent asks for the first slice; anything else is a cursor a slice handed back. */
344 readonly cursor?: string | undefined;
345 /** One commit's own changes, rather than everything the pull request carries. */
346 readonly commit?: string | undefined;
347 }) => Effect.Effect<GitHubPullRequestDiffSlice, GitHubPullRequestCliError>;
348
349 readonly getPullRequestDiffFileContents: (input: {
350 readonly cwd: string;
351 readonly repository: string;
352 readonly host: string;
353 readonly number: number;
354 readonly commit?: string | undefined;
355 readonly changeType: "change" | "rename-pure" | "rename-changed" | "new" | "deleted";
356 readonly oldPath: string;
357 readonly newPath: string;
358 }) => Effect.Effect<
359 { readonly oldContents: string; readonly newContents: string },
360 GitHubPullRequestCliError
361 >;
362
363 readonly listReviewThreadComments: (input: {
364 readonly cwd: string;
365 readonly repository: string;
366 readonly host: string;
367 readonly number: number;
368 }) => Effect.Effect<GitHubReviewThreadComments, GitHubPullRequestCliError>;
369
370 /** One request for a listing's authors, since no `gh` JSON field reports an avatar. */
371 readonly listActorAvatars: (input: {
372 readonly cwd: string;
373 readonly repository: string;
374 readonly host: string;
375 readonly ids: ReadonlyArray<string>;
376 }) => Effect.Effect<ReadonlyMap<string, string>, GitHubPullRequestCliError>;
377
378 /** One `gh repo view`, which answers what the repository allows and where the viewer stands. */
379 readonly getRepositoryAccess: (input: {
380 readonly cwd: string;
381 readonly repository: string;
382 readonly host: string;
383 }) => Effect.Effect<GitHubRepositoryAccess, GitHubPullRequestCliError>;
384
385 /** The viewer's standing on its own, for deciding a write without reading the whole detail. */
386 readonly getViewerAccess: (input: {
387 readonly cwd: string;
388 readonly repository: string;
389 readonly host: string;
390 readonly number: number;
391 }) => Effect.Effect<GitHubViewerAccess, GitHubPullRequestCliError>;
392
393 /** Who this pull request may be sent to, and who it has already been sent to. */
394 readonly listReviewerCandidates: (input: {
395 readonly cwd: string;
396 readonly repository: string;
397 readonly host: string;
398 readonly number: number;
399 }) => Effect.Effect<PullRequestReviewerCandidateList, GitHubPullRequestCliError>;
400
401 readonly setReviewerRequest: (input: {
402 readonly cwd: string;
403 readonly repository: string;
404 readonly host: string;
405 readonly number: number;
406 readonly reviewers: ReadonlyArray<{
407 readonly id: string;
408 readonly kind: PullRequestReviewerKind;
409 }>;
410 /** False deletes the same collection a request posts to, which takes the request back. */
411 readonly requested: boolean;
412 }) => Effect.Effect<void, GitHubPullRequestCliError>;
413
414 readonly runPullRequestAction: (input: {
415 readonly cwd: string;
416 readonly repository: string;
417 readonly host: string;
418 readonly number: number;
419 readonly action: PullRequestAction;
420 readonly mergeMethod?: PullRequestMergeMethod;
421 }) => Effect.Effect<void, GitHubPullRequestCliError>;
422
423 readonly commentOnPullRequest: (input: {
424 readonly cwd: string;
425 readonly repository: string;
426 readonly host: string;
427 readonly number: number;
428 readonly body: string;
429 }) => Effect.Effect<void, GitHubPullRequestCliError>;
430
431 readonly submitReview: (input: {
432 readonly cwd: string;
433 readonly repository: string;
434 readonly host: string;
435 readonly number: number;
436 readonly verdict: PullRequestReviewVerdict;
437 readonly body: string;
438 readonly comments: ReadonlyArray<PullRequestReviewCommentDraft>;
439 }) => Effect.Effect<void, GitHubPullRequestCliError>;
440
441 readonly replyToReviewThread: (input: {
442 readonly cwd: string;
443 readonly repository: string;
444 readonly host: string;
445 readonly threadId: string;
446 readonly body: string;
447 }) => Effect.Effect<void, GitHubPullRequestCliError>;
448
449 readonly setReviewThreadResolution: (input: {
450 readonly cwd: string;
451 readonly repository: string;
452 readonly host: string;
453 readonly threadId: string;
454 readonly resolved: boolean;
455 }) => Effect.Effect<void, GitHubPullRequestCliError>;
456 }
457>()("t3/pullRequest/GitHubPullRequestCli") {}
458
459/**
460 * The GraphQL API takes owner and name as separate arguments, so `owner/repo` is split here.
461 * The host is not read off the identity: it travels alongside it, because the identity a
462 * project records is the path below its host and never names the host itself.
463 */
464export function parseRepositorySelector(value: string): {
465 readonly owner: string;
466 readonly name: string;
467} {
468 const parts = value.trim().split("/").filter(Boolean);
469 return { name: parts.at(-1) ?? "", owner: parts.at(-2) ?? "" };
470}
471
472/**
473 * The page a diff cursor names, or null for anything this walk cannot have issued. The cursor
474 * arrives from the reader as a string and goes straight into a request path, so it is parsed
475 * rather than trusted; the length bound keeps a page number out of exponential notation.
476 */
477function diffCursorPage(cursor: string): number | null {
478 return /^[1-9][0-9]{0,6}$/.test(cursor) ? Number(cursor) : null;
479}
480
481/**
482 * A commit sha arrives from the reader and goes straight into a request path, so it is checked
483 * rather than trusted: hexadecimal only, from the shortest abbreviation a host prints up to a
484 * whole sha.
485 */
486function isCommitSha(value: string): boolean {
487 return /^[0-9a-f]{7,64}$/i.test(value);
488}
489
490/**
491 * The reader's own words as one literal phrase of a GitHub search query. Quoting is the whole
492 * defence: outside quotes GitHub reads `is:merged` as a qualifier and `label:x` as another, so
493 * text typed into a search box could widen the very listing it is meant to narrow — inside them
494 * it is only text. The two characters that could end the phrase early are therefore escaped
495 * first, which GitHub reads back as themselves; an unbalanced quote is dropped instead, which
496 * would let everything after it out of the phrase.
497 *
498 * The phrase is one argv element, so nothing in it can become a flag of its own either.
499 */
500function searchPhrase(query: string): string {
501 return `"${query.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
502}
503
504function involvementArgs(input: {
505 readonly state: PullRequestListState;
506 readonly involvement: PullRequestInvolvement;
507 readonly viewer: string;
508 readonly query?: string | undefined;
509 /** Where to carry on from, which only a search can express. */
510 readonly cursor?: ProviderListCursor | undefined;
511 /**
512 * Ask GitHub for the order the page reads its rows in. False on the fallback read, which
513 * cannot use search at all and takes whatever order `gh pr list` answers in.
514 */
515 readonly sorted: boolean;
516}): ReadonlyArray<string> {
517 // `--state closed` includes merged pull requests, so the Closed tab additionally excludes
518 // them through search; `--author` and `review-requested:` are GitHub's own filters. `gh`
519 // takes one `--search`, so the reader's text joins the qualifiers rather than replacing them.
520 const query = input.query?.trim() ?? "";
521 // The fallback read exists because this repository's search index answered nothing, so it goes
522 // nowhere near search: no order, cursor or qualifiers. Its decoded rows are narrowed by state
523 // and involvement below, since widening either would put unrelated pull requests on the page.
524 const searchTerms = !input.sorted
525 ? []
526 : [
527 ...(input.involvement === "reviewing" ? [`review-requested:${input.viewer}`] : []),
528 ...(input.state === "closed" ? ["is:unmerged"] : []),
529 ...(query.length === 0 ? [] : [searchPhrase(query)]),
530 // The instant the last slice ended on, and everything before it. Inclusive, because rows
531 // sharing one instant are ordinary and the caller drops the ones it has already sent —
532 // asking for strictly older would lose the rest of them instead.
533 ...(input.cursor === undefined ? [] : [`updated:<=${input.cursor.updatedBefore}`]),
534 // `gh pr list` answers newest-created first, which is not the order the page reads rows in
535 // and not an order a continuation can carry on from: a change request opened last year and
536 // touched this morning belongs at the top of the list and at the front of the first slice.
537 // Free text would otherwise come back in best-match order, which is worse again.
538 "sort:updated-desc",
539 ];
540 return [
541 ...(input.involvement === "authored" ? ["--author", input.viewer] : []),
542 ...(searchTerms.length > 0 ? ["--search", searchTerms.join(" ")] : []),
543 ];
544}
545
546/** The search-free fallback is wider than the request, so narrow its decoded rows locally. */
547function matchesUnsortedListing(
548 item: GitHubPullRequestListItem,
549 input: {
550 readonly state: PullRequestListState;
551 readonly involvement: PullRequestInvolvement;
552 readonly viewer: string;
553 },
554): boolean {
555 const matchesState = input.state === "all" || item.state === input.state;
556 const viewer = input.viewer.toLowerCase();
557 const matchesInvolvement =
558 input.involvement === "all" ||
559 (input.involvement === "authored"
560 ? item.author?.login.toLowerCase() === viewer
561 : item.hasTeamReviewRequest ||
562 item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer));
563 return matchesState && matchesInvolvement;
564}
565
566/** What a repository selector may hold before it goes into a search as itself. */
567const SEARCH_REPOSITORY = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
568
569/**
570 * The same listing as one GitHub search across several repositories, which is the only way to
571 * read a whole host in one request.
572 *
573 * Every narrowing `involvementArgs` hands to `gh pr list` as a flag is a qualifier here instead,
574 * because a search has no flags to borrow: `--author X` is `author:X`, `--state open` is
575 * `is:open`, and `--state closed` — which includes merged pull requests — is `is:closed
576 * is:unmerged`. The two belong together; a tab added to one wants adding to the other.
577 *
578 * Null where a repository is not `owner/name`. A name is written into the query as itself, and a
579 * name holding a space could otherwise end the `repo:` qualifier and start a qualifier of its
580 * own — so an unaddressable one refuses the whole read rather than being escaped into something
581 * GitHub might still read.
582 */
583function searchQuery(input: {
584 readonly repositories: ReadonlyArray<string>;
585 readonly state: PullRequestListState;
586 readonly involvement: PullRequestInvolvement;
587 readonly viewer: string;
588 readonly query?: string | undefined;
589 readonly cursor?: ProviderListCursor | undefined;
590}): string | null {
591 if (input.repositories.length === 0) return null;
592 const repositories = input.repositories.map((repository) => repository.trim());
593 if (!repositories.every((repository) => SEARCH_REPOSITORY.test(repository))) return null;
594 const query = input.query?.trim() ?? "";
595 return [
596 "is:pr",
597 // "all" is every state, which `is:pr` already is.
598 ...(input.state === "open" ? ["is:open"] : []),
599 ...(input.state === "closed" ? ["is:closed", "is:unmerged"] : []),
600 ...(input.state === "merged" ? ["is:merged"] : []),
601 ...(input.involvement === "authored" ? [`author:${input.viewer}`] : []),
602 ...(input.involvement === "reviewing" ? [`review-requested:${input.viewer}`] : []),
603 ...(query.length === 0 ? [] : [searchPhrase(query)]),
604 // Inclusive, and de-duplicated by the caller, for the reason the per-repository read gives.
605 ...(input.cursor === undefined ? [] : [`updated:<=${input.cursor.updatedBefore}`]),
606 // The order the page reads its rows in, and the only order a continuation can carry on from.
607 "sort:updated-desc",
608 ...repositories.map((repository) => `repo:${repository}`),
609 ].join(" ");
610}
611
612/**
613 * The `after` a paged read carries. gh sends a JSON null only through a typed field, and an
614 * untyped `cursor=` would send the empty string, which GitHub refuses as a cursor rather than
615 * reading as "start at the beginning".
616 */
617function cursorVariable(cursor: string | null): readonly [string, string] {
618 return cursor === null ? ["-F", "cursor=null"] : ["-f", `cursor=${cursor}`];
619}
620
621function actionArgs(
622 action: PullRequestAction,
623 mergeMethod: PullRequestMergeMethod | undefined,
624): ReadonlyArray<string> {
625 switch (action) {
626 case "merge":
627 return ["merge", `--${mergeMethod ?? "merge"}`];
628 case "ready":
629 return ["ready"];
630 case "draft":
631 return ["ready", "--undo"];
632 case "close":
633 return ["close"];
634 case "reopen":
635 return ["reopen"];
636 }
637}
638
639export const make = Effect.gen(function* () {
640 const github = yield* GitHubCli.GitHubCli;
641
642 // `gh` resolves a bare `owner/repo` against whichever host it defaults to, which is
643 // github.com. Naming the host makes a GitHub Enterprise repository resolve to its own
644 // install rather than to a same-named repository on github.com.
645 const repositoryArgs = (input: { readonly host: string; readonly repository: string }) => [
646 "--repo",
647 `${input.host}/${input.repository}`,
648 ];
649
650 /**
651 * A GraphQL mutation whose answer is not read back. `gh` exits non-zero on a GraphQL error,
652 * so a failed mutation is already a failed command rather than a body to inspect.
653 *
654 * The query and its variables travel over stdin as one document: a variable can carry a
655 * body the reader wrote, and argv is visible in process listings and echoed back inside
656 * process-runner failure messages.
657 */
658 const graphql = (input: {
659 readonly cwd: string;
660 readonly host: string;
661 readonly query: string;
662 readonly variables: Readonly<Record<string, string>>;
663 }) =>
664 github
665 .execute({
666 cwd: input.cwd,
667 args: ["api", "graphql", "--hostname", input.host, "--input", "-"],
668 stdin: encodeGraphQlRequestJson({ query: input.query, variables: input.variables }),
669 })
670 .pipe(Effect.asVoid);
671
672 /** A GraphQL read whose answer is decoded, reporting a failure against the read that made it. */
673 const graphqlRead = <A>(input: {
674 readonly cwd: string;
675 readonly host: string;
676 readonly operation: string;
677 /** Variables as `-f` flags, for values this module composed itself. */
678 readonly variables?: ReadonlyArray<readonly [string, string]>;
679 /**
680 * Variables carrying words the reader typed. Document and variables travel over stdin
681 * together, because argv is visible in process listings and is echoed back inside a
682 * process-runner failure message.
683 */
684 readonly privateVariables?: Readonly<Record<string, string>>;
685 readonly query: string;
686 readonly decode: (raw: string) => Result.Result<A, unknown>;
687 }): Effect.Effect<A, GitHubPullRequestCliError> =>
688 github
689 .execute(
690 input.privateVariables === undefined
691 ? {
692 cwd: input.cwd,
693 args: [
694 "api",
695 "graphql",
696 "--hostname",
697 input.host,
698 ...(input.variables ?? []).flat(),
699 "-f",
700 `query=${input.query}`,
701 ],
702 }
703 : {
704 cwd: input.cwd,
705 args: ["api", "graphql", "--hostname", input.host, "--input", "-"],
706 stdin: encodeGraphQlRequestJson({
707 query: input.query,
708 variables: input.privateVariables,
709 }),
710 },
711 )
712 .pipe(
713 Effect.flatMap((result) => {
714 const decoded = input.decode(result.stdout.trim());
715 return Result.isSuccess(decoded)
716 ? Effect.succeed(decoded.success)
717 : Effect.fail(
718 new GitHubPullRequestReadError({
719 command: "gh",
720 cwd: input.cwd,
721 operation: input.operation,
722 cause: decoded.failure,
723 }),
724 );
725 }),
726 );
727
728 /**
729 * One page of the patch, read from the files API. GitHub refuses `pr diff` outright past 300
730 * changed files, and still serves those files' hunks here.
731 *
732 * A page is a whole number of files, so each one parses on its own; the caller carries on from
733 * `nextCursor` for as long as GitHub keeps handing pages back.
734 *
735 * A named commit is read from the commit endpoint, which lists the same file entries and pages
736 * them the same way — only wrapped in an object, which jq unwraps before they are decoded.
737 */
738 const diffFilesPage = (input: {
739 readonly cwd: string;
740 readonly repository: string;
741 readonly host: string;
742 readonly number: number;
743 readonly page: number;
744 readonly commit?: string | undefined;
745 }): Effect.Effect<GitHubPullRequestDiffSlice, GitHubPullRequestCliError> => {
746 const { owner, name } = parseRepositorySelector(input.repository);
747 const paging = `per_page=${DIFF_FILES_PAGE_SIZE}&page=${input.page}`;
748 return github
749 .execute({
750 cwd: input.cwd,
751 args: [
752 "api",
753 "--hostname",
754 input.host,
755 input.commit === undefined
756 ? `repos/${owner}/${name}/pulls/${input.number}/files?${paging}`
757 : `repos/${owner}/${name}/commits/${input.commit}?${paging}`,
758 // An empty commit carries no `files` at all, which is a commit with nothing in it
759 // rather than an answer that could not be read.
760 ...(input.commit === undefined ? [] : ["--jq", ".files // []"]),
761 ],
762 maxOutputBytes: DIFF_MAX_OUTPUT_BYTES,
763 timeoutMs: DIFF_TIMEOUT_MS,
764 })
765 .pipe(
766 Effect.flatMap((result) => {
767 // Checked before decoding: a byte-truncated response is a JSON prefix, which would
768 // fail to parse. Nothing of this page can be shown, and an empty patch would render
769 // as a change with no files rather than as the failure it is; slices already handed
770 // over stay with the reader either way.
771 if (result.stdoutTruncated) {
772 return Effect.fail(
773 new GitHubPullRequestReadError({
774 command: "gh",
775 cwd: input.cwd,
776 operation: "getPullRequestDiff",
777 cause: new Error(`Page ${input.page} of the changed files was too large to read.`),
778 }),
779 );
780 }
781 const decoded = decodePullRequestFilesJson(result.stdout.trim());
782 if (!Result.isSuccess(decoded)) {
783 return Effect.fail(
784 new GitHubPullRequestReadError({
785 command: "gh",
786 cwd: input.cwd,
787 operation: "getPullRequestDiff",
788 cause: decoded.failure,
789 }),
790 );
791 }
792 // Counted before decoding, so a page whose files all failed to decode still moves on
793 // rather than pointing the reader back at the page it just read.
794 const morePages = decoded.success.rawCount >= DIFF_FILES_PAGE_SIZE;
795 return Effect.succeed({
796 patch: decoded.success.patch,
797 truncated: decoded.success.truncated,
798 nextCursor: morePages ? String(input.page + 1) : null,
799 });
800 }),
801 );
802 };
803
804 const getPullRequestDiffFileContents: GitHubPullRequestCli["Service"]["getPullRequestDiffFileContents"] =
805 (input) =>
806 Effect.gen(function* () {
807 if (input.commit !== undefined && !isCommitSha(input.commit)) {
808 return yield* new GitHubDiffCommitError({ command: "gh", cwd: input.cwd });
809 }
810 const { owner, name } = parseRepositorySelector(input.repository);
811 const refsResult = yield* github.execute({
812 cwd: input.cwd,
813 args: [
814 "api",
815 "--hostname",
816 input.host,
817 input.commit === undefined
818 ? `repos/${owner}/${name}/pulls/${input.number}`
819 : `repos/${owner}/${name}/commits/${input.commit}`,
820 "--jq",
821 input.commit === undefined
822 ? "[.base.sha, .head.sha] | @tsv"
823 : "[.parents[0].sha, .sha] | @tsv",
824 ],
825 maxOutputBytes: 1024,
826 timeoutMs: DIFF_TIMEOUT_MS,
827 });
828 // Keep a leading tab: a root commit has no parent, and jq represents that absent old
829 // revision as the empty field before the tab. Every file in it is new, so that is a
830 // usable answer whenever the caller does not need the old side.
831 const [baseRef, headRef, ...extraRefs] = refsResult.stdout.trimEnd().split("\t");
832 const rootCommitNewFile =
833 input.commit !== undefined && input.changeType === "new" && baseRef === "";
834 if (
835 refsResult.stdoutTruncated ||
836 !headRef ||
837 extraRefs.length > 0 ||
838 (!rootCommitNewFile && (baseRef === undefined || !isCommitSha(baseRef))) ||
839 !isCommitSha(headRef)
840 ) {
841 return yield* new GitHubDiffRevisionsUnavailableError({
842 command: "gh",
843 cwd: input.cwd,
844 number: input.number,
845 ...(input.commit === undefined ? {} : { commit: input.commit }),
846 });
847 }
848
849 const readFile = (revision: string, filePath: string) =>
850 github
851 .execute({
852 cwd: input.cwd,
853 args: [
854 "api",
855 "--hostname",
856 input.host,
857 "--header",
858 "Accept: application/vnd.github.raw+json",
859 `repos/${owner}/${name}/contents/${filePath
860 .split("/")
861 .map(encodeURIComponent)
862 .join("/")}?ref=${encodeURIComponent(revision)}`,
863 ],
864 maxOutputBytes: DIFF_FILE_MAX_OUTPUT_BYTES,
865 timeoutMs: DIFF_TIMEOUT_MS,
866 })
867 .pipe(
868 Effect.flatMap((result) =>
869 result.stdoutTruncated ||
870 result.stdout.includes("\0") ||
871 result.stdoutInvalidUtf8 === true
872 ? Effect.fail(
873 new GitHubDiffFileContentsUnavailableError({
874 command: "gh",
875 cwd: input.cwd,
876 path: filePath,
877 reason: result.stdoutTruncated ? "oversized" : "binary",
878 }),
879 )
880 : Effect.succeed(result.stdout),
881 ),
882 );
883
884 const [oldContents, newContents] = yield* Effect.all(
885 [
886 input.changeType === "new" ? Effect.succeed("") : readFile(baseRef, input.oldPath),
887 input.changeType === "deleted" ? Effect.succeed("") : readFile(headRef, input.newPath),
888 ],
889 { concurrency: 2 },
890 );
891 return { oldContents, newContents };
892 });
893
894 return GitHubPullRequestCli.of({
895 getViewerLogin: (input) =>
896 github.execute({ cwd: input.cwd, args: ["api", "user", "--jq", ".login"] }).pipe(
897 Effect.flatMap((result) => {
898 const login = result.stdout.trim();
899 return login.length > 0
900 ? Effect.succeed(login)
901 : Effect.fail(new GitHubViewerLoginUnavailableError({ command: "gh", cwd: input.cwd }));
902 }),
903 ),
904
905 listPullRequests: (input) => {
906 const fallbackMaxRows = Math.max(input.limit + 1, PULL_REQUEST_FALLBACK_MAX_ROWS);
907 const read = (
908 continues: boolean,
909 requestedRows = input.limit + 1,
910 ): Effect.Effect<GitHubPullRequestListBatch, GitHubPullRequestCliError> =>
911 github
912 .execute({
913 cwd: input.cwd,
914 args: [
915 "pr",
916 "list",
917 ...repositoryArgs(input),
918 ...involvementArgs({ ...input, sorted: continues }),
919 "--state",
920 input.state,
921 "--limit",
922 // One extra row reveals that the repository has more than the page shows.
923 String(requestedRows),
924 "--json",
925 PULL_REQUEST_LIST_JSON_FIELDS,
926 ],
927 })
928 .pipe(
929 Effect.flatMap((result) => {
930 const raw = result.stdout.trim();
931 if (raw.length === 0) {
932 return Effect.succeed({ items: [], truncated: false, continues });
933 }
934 const decoded = decodePullRequestListJson(raw);
935 if (Result.isSuccess(decoded)) {
936 const items = continues
937 ? decoded.success.items
938 : decoded.success.items.filter((item) => matchesUnsortedListing(item, input));
939 if (
940 !continues &&
941 items.length < input.limit &&
942 decoded.success.rawCount >= requestedRows &&
943 requestedRows < fallbackMaxRows
944 ) {
945 const nextRows = Math.min(requestedRows * 2, fallbackMaxRows);
946 if (nextRows > requestedRows) return read(false, nextRows);
947 }
948 return Effect.succeed({
949 items: items.slice(0, input.limit),
950 // One row over the page size is the probe for a next page, and it is
951 // counted before decoding: a skipped malformed row must not end paging.
952 truncated: continues
953 ? decoded.success.rawCount > input.limit
954 : items.length > input.limit || decoded.success.rawCount >= requestedRows,
955 continues,
956 });
957 }
958 return Effect.fail(
959 new GitHubPullRequestReadError({
960 command: "gh",
961 cwd: input.cwd,
962 operation: "listPullRequests",
963 cause: decoded.failure,
964 }),
965 );
966 }),
967 );
968 // GitHub does not index every repository for search, and one it will not search answers
969 // with no rows rather than with an error — so an empty listing is read again the way `gh`
970 // lists without one. Those rows come back newest-created first, an order no `updated:`
971 // qualifier can carry on from, so that page says it cannot be continued and the reader
972 // reaches the rest of it by asking for a larger page, as every listing used to.
973 //
974 // Only ever the first slice: a repository that answered the search once will answer it
975 // again, so an empty slice under a cursor is a repository that has run out.
976 // A text search that finds nothing has found nothing: falling back would answer it with the
977 // repository's whole list, which is every row the reader did not search for. The fallback
978 // is for a repository the index does not cover, and a listing with no text to match is the
979 // only place an empty answer can mean that.
980 const searched = (input.query?.trim().length ?? 0) > 0;
981 return read(true).pipe(
982 Effect.flatMap((batch) =>
983 batch.items.length === 0 && input.cursor === undefined && !searched
984 ? read(false)
985 : Effect.succeed(batch),
986 ),
987 );
988 },
989
990 searchPullRequests: (input) => {
991 const query = searchQuery(input);
992 if (query === null) {
993 return Effect.fail(
994 new GitHubRepositorySelectorError({
995 command: "gh",
996 cwd: input.cwd,
997 operation: "searchPullRequests",
998 }),
999 );
1000 }
1001 // One extra row reveals that the host has more than the slice shows, the way the
1002 // per-repository read does — up to GitHub's own ceiling on a search page, past which
1003 // `hasNextPage` is what says there is more.
1004 const rows = Math.min(input.limit + 1, PULL_REQUEST_SEARCH_MAX_ROWS);
1005 return graphqlRead({
1006 cwd: input.cwd,
1007 host: input.host,
1008 operation: "searchPullRequests",
1009 // The reader's own words are in the query, so it travels over stdin rather than in argv.
1010 privateVariables: { q: query },
1011 query: pullRequestSearchGraphQlQuery(rows),
1012 decode: decodePullRequestSearchJson,
1013 }).pipe(
1014 Effect.map((batch) => ({
1015 items: batch.items.slice(0, input.limit),
1016 truncated: batch.rawCount > input.limit || batch.hasNextPage,
1017 })),
1018 );
1019 },
1020
1021 listPullRequestStats: (input) => {
1022 const chunks: Array<ReadonlyArray<{ readonly repository: string; readonly number: number }>> =
1023 [];
1024 for (let start = 0; start < input.changeRequests.length; start += STAT_ALIASES_PER_REQUEST) {
1025 chunks.push(input.changeRequests.slice(start, start + STAT_ALIASES_PER_REQUEST));
1026 }
1027 return Effect.forEach(
1028 chunks,
1029 (chunk) => {
1030 const query = buildPullRequestStatsGraphQlQuery(chunk);
1031 if (query === null) {
1032 return Effect.fail(
1033 new GitHubRepositorySelectorError({
1034 command: "gh",
1035 cwd: input.cwd,
1036 operation: "listPullRequestStats",
1037 }),
1038 );
1039 }
1040 return graphqlRead({
1041 cwd: input.cwd,
1042 host: input.host,
1043 operation: "listPullRequestStats",
1044 query,
1045 decode: decodePullRequestStatsJson,
1046 }).pipe(
1047 Effect.map((stats) =>
1048 chunk.flatMap((changeRequest, index) => {
1049 const stat = stats.get(index);
1050 return stat === undefined ? [] : [{ ...changeRequest, ...stat }];
1051 }),
1052 ),
1053 );
1054 },
1055 { concurrency: STAT_REQUEST_CONCURRENCY },
1056 ).pipe(Effect.map((results) => results.flat()));
1057 },
1058
1059 getPullRequestDetail: (input) =>
1060 github
1061 .execute({
1062 cwd: input.cwd,
1063 args: [
1064 "pr",
1065 "view",
1066 String(input.number),
1067 ...repositoryArgs(input),
1068 "--json",
1069 PULL_REQUEST_DETAIL_JSON_FIELDS,
1070 ],
1071 })
1072 .pipe(
1073 Effect.flatMap((result) => {
1074 const decoded = decodePullRequestDetailJson(result.stdout.trim());
1075 return Result.isSuccess(decoded)
1076 ? Effect.succeed(decoded.success)
1077 : Effect.fail(
1078 new GitHubPullRequestReadError({
1079 command: "gh",
1080 cwd: input.cwd,
1081 operation: "getPullRequestDetail",
1082 cause: decoded.failure,
1083 }),
1084 );
1085 }),
1086 ),
1087
1088 getPullRequestActivity: (input) =>
1089 github
1090 .execute({
1091 cwd: input.cwd,
1092 args: [
1093 "pr",
1094 "view",
1095 String(input.number),
1096 ...repositoryArgs(input),
1097 "--json",
1098 PULL_REQUEST_ACTIVITY_JSON_FIELDS,
1099 ],
1100 })
1101 .pipe(
1102 Effect.flatMap((result) => {
1103 const decoded = decodePullRequestActivityJson(result.stdout.trim());
1104 return Result.isSuccess(decoded)
1105 ? Effect.succeed(decoded.success)
1106 : Effect.fail(
1107 new GitHubPullRequestReadError({
1108 command: "gh",
1109 cwd: input.cwd,
1110 operation: "getPullRequestActivity",
1111 cause: decoded.failure,
1112 }),
1113 );
1114 }),
1115 ),
1116
1117 getPullRequestDiff: (input) => {
1118 const filesPage = (page: number) =>
1119 diffFilesPage({
1120 cwd: input.cwd,
1121 repository: input.repository,
1122 host: input.host,
1123 number: input.number,
1124 page,
1125 ...(input.commit === undefined ? {} : { commit: input.commit }),
1126 });
1127 if (input.commit !== undefined && !isCommitSha(input.commit)) {
1128 return Effect.fail(new GitHubDiffCommitError({ command: "gh", cwd: input.cwd }));
1129 }
1130 // A cursor only ever comes from the files walk, so a reader carrying one is already past
1131 // the point where `gh pr diff` had anything to say.
1132 if (input.cursor !== undefined) {
1133 const page = diffCursorPage(input.cursor);
1134 return page === null
1135 ? Effect.fail(new GitHubDiffCursorError({ command: "gh", cwd: input.cwd }))
1136 : filesPage(page);
1137 }
1138 // `gh pr diff` speaks for the whole pull request and has no way to name one commit of it.
1139 if (input.commit !== undefined) {
1140 return filesPage(1);
1141 }
1142 return github
1143 .execute({
1144 cwd: input.cwd,
1145 args: ["pr", "diff", String(input.number), ...repositoryArgs(input), "--color", "never"],
1146 maxOutputBytes: DIFF_MAX_OUTPUT_BYTES,
1147 timeoutMs: DIFF_TIMEOUT_MS,
1148 })
1149 .pipe(
1150 Effect.flatMap((result) =>
1151 // A patch cut at a byte boundary ends mid-file, which is neither a whole slice nor
1152 // something the reader can carry on from. The files API can serve the same change a
1153 // whole number of files at a time, so an oversized patch takes that road as well.
1154 result.stdoutTruncated
1155 ? filesPage(1)
1156 : // One read served the whole patch, so there is no next slice to ask for.
1157 Effect.succeed({ patch: result.stdout, truncated: false, nextCursor: null }),
1158 ),
1159 // GitHub answers 406 rather than a diff past 300 changed files, so the patch is read
1160 // from the files API instead, a page per call. Only once the direct read has failed: a
1161 // pull request GitHub will serve a diff for must not pay for a second request. A
1162 // fallback that fails too reports the original refusal, which is the one that explains
1163 // the page. Narrowed to a command that ran and was refused: a missing `gh` or a
1164 // signed-out one fails the same way for every request.
1165 Effect.catchTags({
1166 GitHubCliCommandError: (error) =>
1167 filesPage(1).pipe(Effect.catch(() => Effect.fail(error))),
1168 }),
1169 );
1170 },
1171
1172 getPullRequestDiffFileContents,
1173
1174 listReviewThreadComments: (input) =>
1175 Effect.gen(function* () {
1176 const { owner, name } = parseRepositorySelector(input.repository);
1177 const threadPage = (
1178 cursor: string | null,
1179 ): Effect.Effect<GitHubReviewThreadPage, GitHubPullRequestCliError> =>
1180 graphqlRead({
1181 cwd: input.cwd,
1182 host: input.host,
1183 operation: "listReviewThreadComments",
1184 variables: [
1185 ["-f", `owner=${owner}`],
1186 ["-f", `name=${name}`],
1187 ["-F", `number=${input.number}`],
1188 cursorVariable(cursor),
1189 ],
1190 query: REVIEW_THREADS_GRAPHQL_QUERY,
1191 decode: decodeReviewThreadsJson,
1192 });
1193 const commentPage = (
1194 threadId: string,
1195 cursor: string,
1196 ): Effect.Effect<
1197 {
1198 readonly comments: ReadonlyArray<PullRequestThreadComment>;
1199 readonly nextCursor: string | null;
1200 },
1201 GitHubPullRequestCliError
1202 > =>
1203 graphqlRead({
1204 cwd: input.cwd,
1205 host: input.host,
1206 operation: "listReviewThreadComments",
1207 variables: [["-f", `threadId=${threadId}`], cursorVariable(cursor)],
1208 query: REVIEW_THREAD_COMMENTS_GRAPHQL_QUERY,
1209 decode: decodeReviewThreadCommentsJson,
1210 });
1211
1212 const entries: GitHubReviewThreadEntry[] = [];
1213 const avatarsByLogin = new Map<string, string>();
1214 const commitStats = new Map<
1215 string,
1216 { readonly additions: number; readonly deletions: number }
1217 >();
1218 let reviewers: ReadonlyArray<PullRequestActor> = [];
1219 let commits: GitHubReviewThreadPage["commits"] = [];
1220 let viewer: GitHubReviewThreadPage["viewer"] = { canUpdate: true, didAuthor: false };
1221 let cursor: string | null = null;
1222 let page = 0;
1223 do {
1224 const read: GitHubReviewThreadPage = yield* threadPage(cursor);
1225 entries.push(...read.threads);
1226 for (const [login, avatarUrl] of read.avatarsByLogin)
1227 avatarsByLogin.set(login, avatarUrl);
1228 // The roster, the commits and the viewer's standing travel with every page, and the
1229 // first one already carries all of them.
1230 if (page === 0) {
1231 reviewers = read.reviewers;
1232 commits = read.commits;
1233 viewer = read.viewer;
1234 for (const [oid, stat] of read.commitStats) commitStats.set(oid, stat);
1235 }
1236 cursor = read.nextCursor;
1237 page += 1;
1238 } while (cursor !== null && page < REVIEW_THREAD_PAGES);
1239
1240 // Only the threads GitHub said were unfinished cost a request; the rest arrived whole
1241 // with the page they were listed on.
1242 const finished = yield* Effect.forEach(
1243 entries,
1244 (entry) =>
1245 Effect.gen(function* () {
1246 const comments = [...entry.thread.comments];
1247 let commentCursor = entry.nextCommentCursor;
1248 let commentPageCount = 0;
1249 while (commentCursor !== null && commentPageCount < REVIEW_THREAD_COMMENT_PAGES) {
1250 const read = yield* commentPage(entry.thread.id, commentCursor);
1251 comments.push(...read.comments);
1252 commentCursor = read.nextCursor;
1253 commentPageCount += 1;
1254 }
1255 return {
1256 thread: { ...entry.thread, comments },
1257 commentCount: entry.commentCount,
1258 truncated: commentCursor !== null,
1259 };
1260 }),
1261 { concurrency: REVIEW_THREAD_CONCURRENCY },
1262 );
1263
1264 const reviewThreads = finished.map((entry) => entry.thread);
1265 return {
1266 comments: reviewThreadConversation(reviewThreads),
1267 reviewThreads,
1268 // GitHub's own count of each thread, so the number the page shows is the host's even
1269 // where a bound kept some of the words on GitHub.
1270 commentCount: finished.reduce((total, entry) => total + entry.commentCount, 0),
1271 truncated: cursor !== null || finished.some((entry) => entry.truncated),
1272 reviewers,
1273 avatarsByLogin,
1274 commitStats,
1275 commits,
1276 viewer,
1277 };
1278 }),
1279
1280 listActorAvatars: (input) => {
1281 if (input.ids.length === 0) {
1282 return Effect.succeed(new Map<string, string>());
1283 }
1284 return github
1285 .execute({
1286 cwd: input.cwd,
1287 args: [
1288 "api",
1289 "graphql",
1290 "--hostname",
1291 input.host,
1292 ...input.ids.flatMap((id) => ["-f", `ids[]=${id}`]),
1293 "-f",
1294 `query=${ACTOR_AVATARS_GRAPHQL_QUERY}`,
1295 ],
1296 })
1297 .pipe(
1298 Effect.flatMap((result) => {
1299 const decoded = decodeActorAvatarsJson(result.stdout.trim());
1300 return Result.isSuccess(decoded)
1301 ? Effect.succeed(decoded.success)
1302 : Effect.fail(
1303 new GitHubPullRequestReadError({
1304 command: "gh",
1305 cwd: input.cwd,
1306 operation: "listActorAvatars",
1307 cause: decoded.failure,
1308 }),
1309 );
1310 }),
1311 );
1312 },
1313
1314 getRepositoryAccess: (input) =>
1315 github
1316 .execute({
1317 cwd: input.cwd,
1318 args: [
1319 "repo",
1320 "view",
1321 `${input.host}/${input.repository}`,
1322 "--json",
1323 REPOSITORY_ACCESS_JSON_FIELDS,
1324 ],
1325 })
1326 .pipe(
1327 Effect.flatMap((result) => {
1328 const decoded = decodeRepositoryAccessJson(result.stdout.trim());
1329 return Result.isSuccess(decoded)
1330 ? Effect.succeed(decoded.success)
1331 : Effect.fail(
1332 new GitHubPullRequestReadError({
1333 command: "gh",
1334 cwd: input.cwd,
1335 operation: "getRepositoryAccess",
1336 cause: decoded.failure,
1337 }),
1338 );
1339 }),
1340 ),
1341
1342 getViewerAccess: (input) => {
1343 const { owner, name } = parseRepositorySelector(input.repository);
1344 return graphqlRead({
1345 cwd: input.cwd,
1346 host: input.host,
1347 operation: "getViewerAccess",
1348 variables: [
1349 ["-f", `owner=${owner}`],
1350 ["-f", `name=${name}`],
1351 ["-F", `number=${input.number}`],
1352 ],
1353 query: VIEWER_PERMISSIONS_GRAPHQL_QUERY,
1354 decode: decodeViewerPermissionsJson,
1355 });
1356 },
1357
1358 listReviewerCandidates: (input) => {
1359 const { owner, name } = parseRepositorySelector(input.repository);
1360 return graphqlRead({
1361 cwd: input.cwd,
1362 host: input.host,
1363 operation: "listReviewerCandidates",
1364 variables: [
1365 ["-f", `owner=${owner}`],
1366 ["-f", `name=${name}`],
1367 ["-F", `number=${input.number}`],
1368 ],
1369 query: REVIEWER_CANDIDATES_GRAPHQL_QUERY,
1370 decode: decodeReviewerCandidatesJson,
1371 });
1372 },
1373
1374 setReviewerRequest: (input) => {
1375 const { owner, name } = parseRepositorySelector(input.repository);
1376 return github
1377 .execute({
1378 cwd: input.cwd,
1379 // Posting to a login GitHub has already been asked about is what a re-request is, so
1380 // there is nothing to say here about somebody who has reviewed once already. The body
1381 // travels over stdin for the reason every other one does: argv is visible in process
1382 // listings and echoed back inside process-runner failure messages.
1383 args: [
1384 "api",
1385 "--method",
1386 input.requested ? "POST" : "DELETE",
1387 "--hostname",
1388 input.host,
1389 `repos/${owner}/${name}/pulls/${input.number}/requested_reviewers`,
1390 "--input",
1391 "-",
1392 ],
1393 stdin: buildReviewerRequestJson(input.reviewers),
1394 })
1395 .pipe(Effect.asVoid);
1396 },
1397
1398 runPullRequestAction: (input) => {
1399 const [subcommand, ...flags] = actionArgs(input.action, input.mergeMethod);
1400 return github
1401 .execute({
1402 cwd: input.cwd,
1403 args: ["pr", subcommand!, String(input.number), ...repositoryArgs(input), ...flags],
1404 })
1405 .pipe(Effect.asVoid);
1406 },
1407
1408 commentOnPullRequest: (input) =>
1409 github
1410 .execute({
1411 cwd: input.cwd,
1412 // The body travels over stdin: argv is visible in process listings and is echoed
1413 // back inside process-runner failure messages.
1414 args: [
1415 "pr",
1416 "comment",
1417 String(input.number),
1418 ...repositoryArgs(input),
1419 "--body-file",
1420 "-",
1421 ],
1422 stdin: input.body,
1423 })
1424 .pipe(Effect.asVoid),
1425
1426 submitReview: (input) => {
1427 const { owner, name } = parseRepositorySelector(input.repository);
1428 return github
1429 .execute({
1430 cwd: input.cwd,
1431 // The whole review is one request, so nothing is visible to anyone else until the
1432 // verdict is sent. The payload travels over stdin for the same reason a comment
1433 // body does: argv is visible in process listings and echoed back in failures.
1434 args: [
1435 "api",
1436 "--method",
1437 "POST",
1438 "--hostname",
1439 input.host,
1440 `repos/${owner}/${name}/pulls/${input.number}/reviews`,
1441 "--input",
1442 "-",
1443 ],
1444 stdin: buildReviewSubmissionJson({
1445 verdict: input.verdict,
1446 body: input.body,
1447 comments: input.comments,
1448 }),
1449 })
1450 .pipe(Effect.asVoid);
1451 },
1452
1453 replyToReviewThread: (input) =>
1454 graphql({
1455 cwd: input.cwd,
1456 host: input.host,
1457 query: REVIEW_THREAD_REPLY_GRAPHQL_MUTATION,
1458 variables: { threadId: input.threadId, body: input.body },
1459 }),
1460
1461 setReviewThreadResolution: (input) =>
1462 graphql({
1463 cwd: input.cwd,
1464 host: input.host,
1465 query: input.resolved
1466 ? RESOLVE_REVIEW_THREAD_GRAPHQL_MUTATION
1467 : UNRESOLVE_REVIEW_THREAD_GRAPHQL_MUTATION,
1468 variables: { threadId: input.threadId },
1469 }),
1470 });
1471});
1472
1473export const layer = Layer.effect(GitHubPullRequestCli, make);