Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitHubPullRequestProvider.ts

352 lines13.0 KB

1import * as Effect from "effect/Effect";
2import type {
3 PullRequestActor,
4 PullRequestCapabilities,
5 PullRequestViewerPermissions,
6} from "@t3tools/contracts";
7​
8import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";
9import {
10 PullRequestProviderError,
11 type ProviderChangeRequestActivity,
12 type ProviderChangeRequestDetail,
13 type PullRequestProviderApi,
14} from "./PullRequestProvider.ts";
15import type { GitHubViewerAccess } from "./gitHubPullRequestJson.ts";
16​
17const CAPABILITIES: PullRequestCapabilities = {
18 diff: true,
19 comment: true,
20 actions: ["merge", "ready", "draft", "close", "reopen"],
21 mergeMethods: ["merge", "squash", "rebase"],
22 search: true,
23 review: {
24 inlineComment: true,
25 reply: true,
26 resolve: true,
27 verdicts: ["comment", "approve", "request-changes"],
28 },
29 reviewers: { request: true, listCandidates: true },
30};
31​
32/**
33 * What the signed-in account may do here, from the three things GitHub says about it.
34 *
35 * Merging needs a role that can push, which is the one thing a stranger on an open-source
36 * repository never has. The other four actions go by `viewerCanUpdate`, because the author of a
37 * pull request may close it, reopen it and move it in and out of draft with no more than read
38 * access on the repository it was opened against.
39 *
40 * Commenting and reviewing are not gated at all: read access is enough to say something and
41 * enough to approve or ask for changes, which is what open-source review consists of. Resolving a
42 * conversation is the exception — GitHub allows it to whoever can write, and to the author of the
43 * pull request the conversation is on.
44 *
45 * Asking somebody else for a review needs write access, which is the one thing here an author
46 * cannot do on their own pull request: GitHub shows an outside contributor the reviewer control
47 * and refuses the request behind it.
48 */
49export function gitHubViewerPermissions(access: GitHubViewerAccess): PullRequestViewerPermissions {
50 return {
51 actions: [
52 ...(access.canWrite ? (["merge"] as const) : []),
53 ...(access.canUpdate ? (["ready", "draft", "close", "reopen"] as const) : []),
54 ],
55 comment: true,
56 resolve: access.canWrite || access.didAuthor,
57 // Anyone may review a pull request they can see, except their own: GitHub refuses an author's
58 // approval and their request for changes ("Can not approve your own pull request"), and
59 // leaves them commenting, which is what an author has to say about their own change anyway.
60 verdicts: access.didAuthor ? (["comment"] as const) : CAPABILITIES.review.verdicts,
61 requestReviewers: access.canWrite,
62 };
64​
65/** The CLI tags that mean the tool itself is unusable, rather than one request failing. */
66function reasonFor(
67 error: GitHubPullRequestCli.GitHubPullRequestCliError,
68): PullRequestProviderError["reason"] {
69 if (error._tag === "GitHubCliUnavailableError") return "missing-tool";
70 if (error._tag === "GitHubCliAuthenticationError") return "unauthenticated";
71 return "failed";
73​
74/**
75 * `gh pr view --json` reports no avatar for anyone, so the ones the GraphQL read collected are
76 * applied here by login. An actor already carrying one keeps it.
77 *
78 * A login GitHub did not answer for falls back to the picture every GitHub install serves at
79 * `/<login>.png`. The lookup is one more request per repository and can be refused — a rate
80 * limit, a slow host — and a face that comes and goes between two loads of the same page reads
81 * as a bug in the page rather than as a request that failed quietly.
82 */
83function withAvatar(
84 actor: PullRequestActor | null,
85 avatarsByLogin: ReadonlyMap<string, string>,
86 host: string,
87): PullRequestActor | null {
88 if (actor === null || actor.avatarUrl !== null) return actor;
89 const avatarUrl = avatarsByLogin.get(actor.login) ?? loginAvatarUrl(actor.login, host);
90 return avatarUrl === null ? actor : { ...actor, avatarUrl };
92​
93/**
94 * Null for anything that is not a plain user login: an app posts as `dependabot[bot]`, which
95 * names no page, and a guessed URL that 404s is worse than the initials it would replace.
96 */
97export function loginAvatarUrl(login: string, host: string): string | null {
98 return /^[a-z0-9][a-z0-9-]{0,38}$/iu.test(login) ? `https://${host}/${login}.png?size=80` : null;
100​
101export const make = Effect.gen(function* () {
102 const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
103​
104 const fail = (operation: string) => (error: GitHubPullRequestCli.GitHubPullRequestCliError) =>
105 new PullRequestProviderError({
106 provider: "github",
107 operation,
108 reason: reasonFor(error),
109 detail: error.detail,
110 cause: error,
111 });
112​
113 const provider: PullRequestProviderApi = {
114 kind: "github",
115 capabilities: CAPABILITIES,
116​
117 getViewer: (input) =>
118 cli.getViewerLogin({ cwd: input.cwd }).pipe(Effect.mapError(fail("getViewer"))),
119​
120 listChangeRequests: (input) =>
121 cli
122 .listPullRequests({
123 cwd: input.cwd,
124 repository: input.repository,
125 host: input.host,
126 state: input.state,
127 involvement: input.involvement,
128 viewer: input.viewer,
129 limit: input.limit,
130 query: input.query,
131 cursor: input.cursor,
132 })
133 .pipe(
134 Effect.mapError(fail("listChangeRequests")),
135 Effect.flatMap((page) =>
136 cli
137 .listActorAvatars({
138 cwd: input.cwd,
139 repository: input.repository,
140 host: input.host,
141 ids: [...new Set(page.items.flatMap((item) => item.authorId ?? []))],
142 })
143 // A listing without faces is still a listing, so a failed lookup falls back to
144 // the initials rather than taking the rows down with it.
145 .pipe(
146 Effect.orElseSucceed(() => new Map<string, string>()),
147 Effect.map((avatarsByLogin) => ({
148 ...page,
149 items: page.items.map((item) => ({
150 ...item,
151 author: withAvatar(item.author, avatarsByLogin, input.host),
152 })),
153 })),
154 ),
155 ),
156 ),
157​
158 /**
159 * The same listing for a whole host in one search. The avatar lookup the per-repository read
160 * needs is not here: a search reports an author's picture itself, so a face costs no request
161 * of its own — `withAvatar` still stands behind it for the login GitHub answered nothing for.
162 */
163 listChangeRequestsAcross: (input) =>
164 cli
165 .searchPullRequests({
166 cwd: input.cwd,
167 host: input.host,
168 repositories: input.repositories,
169 state: input.state,
170 involvement: input.involvement,
171 viewer: input.viewer,
172 limit: input.limit,
173 query: input.query,
174 cursor: input.cursor,
175 })
176 .pipe(
177 Effect.mapError(fail("listChangeRequestsAcross")),
178 Effect.map((batch) => ({
179 truncated: batch.truncated,
180 items: batch.items.map((item) => ({
181 ...item,
182 author: withAvatar(item.author, new Map<string, string>(), input.host),
183 })),
184 })),
185 ),
186​
187 listChangeRequestStats: (input) =>
188 cli
189 .listPullRequestStats({
190 cwd: input.cwd,
191 host: input.host,
192 changeRequests: input.changeRequests,
193 })
194 .pipe(Effect.mapError(fail("listChangeRequestStats"))),
195​
196 getChangeRequest: (input) =>
197 Effect.all(
198 [
199 cli.getPullRequestDetail(input),
200 cli.getRepositoryAccess({
201 cwd: input.cwd,
202 repository: input.repository,
203 host: input.host,
204 }),
205 // A small permissions query replaces the deeply paginated review-thread walk on the
206 // core path. Writes ask again immediately before mutating, so this is presentation.
207 cli.getViewerAccess(input),
208 ],
209 { concurrency: 3 },
210 ).pipe(
211 Effect.mapError(fail("getChangeRequest")),
212 Effect.map(
213 ([pullRequest, repository, viewerAccess]): ProviderChangeRequestDetail => ({
214 ...pullRequest,
215 reviewers: pullRequest.reviewRequestLogins.map((login) => ({
216 login,
217 name: null,
218 avatarUrl: null,
219 })),
220 mergeCapabilities: repository.mergeCapabilities,
221 viewerPermissions: gitHubViewerPermissions(viewerAccess),
222 }),
223 ),
224 ),
225​
226 getChangeRequestActivity: (input) =>
227 Effect.all(
228 [
229 cli.getPullRequestActivity(input),
230 // Line comments live on review threads, which `gh pr view --json` cannot reach. A
231 // GraphQL hiccup degrades to a truncated conversation rather than blanking activity.
232 cli.listReviewThreadComments(input).pipe(
233 Effect.orElseSucceed(() => ({
234 comments: [],
235 reviewThreads: [],
236 commentCount: 0,
237 truncated: true,
238 reviewers: [],
239 avatarsByLogin: new Map<string, string>(),
240 commitStats: new Map<
241 string,
242 { readonly additions: number; readonly deletions: number }
243 >(),
244 commits: [],
245 viewer: { canUpdate: true, didAuthor: false },
246 })),
247 ),
248 ],
249 { concurrency: 2 },
250 ).pipe(
251 Effect.mapError(fail("getChangeRequestActivity")),
252 Effect.map(
253 ([pullRequest, reviewThreads]): ProviderChangeRequestActivity => ({
254 author: withAvatar(pullRequest.author, reviewThreads.avatarsByLogin, input.host),
255 reviewers: reviewThreads.reviewers,
256 commits: (reviewThreads.commits.length > 0
257 ? reviewThreads.commits
258 : pullRequest.commits
259 ).map((commit) => ({
260 ...commit,
261 ...reviewThreads.commitStats.get(commit.oid),
262 authors: commit.authors?.map(
263 (author) => withAvatar(author, reviewThreads.avatarsByLogin, input.host) ?? author,
264 ),
265 })),
266 comments: [...pullRequest.comments, ...reviewThreads.comments]
267 .map((comment) => ({
268 ...comment,
269 author: withAvatar(comment.author, reviewThreads.avatarsByLogin, input.host),
270 }))
271 .toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
272 // `gh pr view --json comments,reviews` follows GitHub's cursors itself, so those two
273 // are always whole and only the thread walk can stop short of the host.
274 commentCount: pullRequest.comments.length + reviewThreads.commentCount,
275 commentsTruncated: reviewThreads.truncated,
276 reviewThreads: reviewThreads.reviewThreads.map((thread) => ({
277 ...thread,
278 comments: thread.comments.map((comment) => ({
279 ...comment,
280 author: withAvatar(comment.author, reviewThreads.avatarsByLogin, input.host),
281 })),
282 })),
283 }),
284 ),
285 ),
286​
287 getViewerPermissions: (input) =>
288 cli
289 .getViewerAccess(input)
290 .pipe(Effect.mapError(fail("getViewerPermissions")), Effect.map(gitHubViewerPermissions)),
291​
292 getDiff: (input) => cli.getPullRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
293​
294 getDiffFileContents: (input) =>
295 cli.getPullRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),
296​
297 listReviewerCandidates: (input) =>
298 cli.listReviewerCandidates(input).pipe(Effect.mapError(fail("listReviewerCandidates"))),
299​
300 setReviewerRequest: (input) =>
301 cli
302 .setReviewerRequest({
303 cwd: input.cwd,
304 repository: input.repository,
305 host: input.host,
306 number: input.number,
307 reviewers: input.reviewers,
308 requested: input.requested,
309 })
310 .pipe(Effect.mapError(fail("setReviewerRequest"))),
311​
312 runAction: (input) =>
313 cli
314 .runPullRequestAction({
315 cwd: input.cwd,
316 repository: input.repository,
317 host: input.host,
318 number: input.number,
319 action: input.action,
320 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
321 })
322 .pipe(Effect.mapError(fail("runAction"))),
323​
324 comment: (input) => cli.commentOnPullRequest(input).pipe(Effect.mapError(fail("comment"))),
325​
326 submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
327​
328 replyToThread: (input) =>
329 cli
330 .replyToReviewThread({
331 cwd: input.cwd,
332 repository: input.repository,
333 host: input.host,
334 threadId: input.threadId,
335 body: input.body,
336 })
337 .pipe(Effect.mapError(fail("replyToThread"))),
338​
339 setThreadResolution: (input) =>
340 cli
341 .setReviewThreadResolution({
342 cwd: input.cwd,
343 repository: input.repository,
344 host: input.host,
345 threadId: input.threadId,
346 resolved: input.resolved,
347 })
348 .pipe(Effect.mapError(fail("setThreadResolution"))),
349 };
350​
351 return provider;
352});