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

GitHubPullRequestProvider.ts

365 lines13.4 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 (
71 error._tag === "GitHubCliAuthenticationError" ||
72 error._tag === "GitHubTokenEnvironmentUnavailableError" ||
73 error._tag === "GitHubTokenOutputEmptyError"
74 )
75 return "unauthenticated";
76 return "failed";
78​
79/**
80 * `gh pr view --json` reports no avatar for anyone, so the ones the GraphQL read collected are
81 * applied here by login. An actor already carrying one keeps it.
82 *
83 * A login GitHub did not answer for falls back to the picture every GitHub install serves at
84 * `/<login>.png`. The lookup is one more request per repository and can be refused — a rate
85 * limit, a slow host — and a face that comes and goes between two loads of the same page reads
86 * as a bug in the page rather than as a request that failed quietly.
87 */
88function withAvatar(
89 actor: PullRequestActor | null,
90 avatarsByLogin: ReadonlyMap<string, string>,
91 host: string,
92): PullRequestActor | null {
93 if (actor === null || actor.avatarUrl !== null) return actor;
94 const avatarUrl = avatarsByLogin.get(actor.login) ?? loginAvatarUrl(actor.login, host);
95 return avatarUrl === null ? actor : { ...actor, avatarUrl };
97​
98/**
99 * Null for anything that is not a plain user login: an app posts as `dependabot[bot]`, which
100 * names no page, and a guessed URL that 404s is worse than the initials it would replace.
101 */
102export function loginAvatarUrl(login: string, host: string): string | null {
103 return /^[a-z0-9][a-z0-9-]{0,38}$/iu.test(login) ? `https://${host}/${login}.png?size=80` : null;
105​
106export const make = Effect.gen(function* () {
107 const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
108​
109 const fail = (operation: string) => (error: GitHubPullRequestCli.GitHubPullRequestCliError) =>
110 new PullRequestProviderError({
111 provider: "github",
112 operation,
113 reason: reasonFor(error),
114 detail: error.detail,
115 cause: error,
116 });
117​
118 const provider: PullRequestProviderApi = {
119 kind: "github",
120 capabilities: CAPABILITIES,
121​
122 getBatchKey: (input) => cli.getBatchKey(input).pipe(Effect.mapError(fail("getBatchKey"))),
123​
124 getViewer: (input) =>
125 cli
126 .getViewerLogin({
127 cwd: input.cwd,
128 host: input.host,
129 repository: input.repository,
130 })
131 .pipe(Effect.mapError(fail("getViewer"))),
132​
133 listChangeRequests: (input) =>
134 cli
135 .listPullRequests({
136 cwd: input.cwd,
137 repository: input.repository,
138 host: input.host,
139 state: input.state,
140 involvement: input.involvement,
141 viewer: input.viewer,
142 limit: input.limit,
143 query: input.query,
144 cursor: input.cursor,
145 })
146 .pipe(
147 Effect.mapError(fail("listChangeRequests")),
148 Effect.flatMap((page) =>
149 cli
150 .listActorAvatars({
151 cwd: input.cwd,
152 repository: input.repository,
153 host: input.host,
154 ids: [...new Set(page.items.flatMap((item) => item.authorId ?? []))],
155 })
156 // A listing without faces is still a listing, so a failed lookup falls back to
157 // the initials rather than taking the rows down with it.
158 .pipe(
159 Effect.orElseSucceed(() => new Map<string, string>()),
160 Effect.map((avatarsByLogin) => ({
161 ...page,
162 items: page.items.map((item) => ({
163 ...item,
164 author: withAvatar(item.author, avatarsByLogin, input.host),
165 })),
166 })),
167 ),
168 ),
169 ),
170​
171 /**
172 * The same listing for a whole host in one search. The avatar lookup the per-repository read
173 * needs is not here: a search reports an author's picture itself, so a face costs no request
174 * of its own — `withAvatar` still stands behind it for the login GitHub answered nothing for.
175 */
176 listChangeRequestsAcross: (input) =>
177 cli
178 .searchPullRequests({
179 cwd: input.cwd,
180 host: input.host,
181 repositories: input.repositories,
182 state: input.state,
183 involvement: input.involvement,
184 viewer: input.viewer,
185 limit: input.limit,
186 query: input.query,
187 cursor: input.cursor,
188 })
189 .pipe(
190 Effect.mapError(fail("listChangeRequestsAcross")),
191 Effect.map((batch) => ({
192 truncated: batch.truncated,
193 items: batch.items.map((item) => ({
194 ...item,
195 author: withAvatar(item.author, new Map<string, string>(), input.host),
196 })),
197 })),
198 ),
199​
200 listChangeRequestStats: (input) =>
201 cli
202 .listPullRequestStats({
203 cwd: input.cwd,
204 host: input.host,
205 changeRequests: input.changeRequests,
206 })
207 .pipe(Effect.mapError(fail("listChangeRequestStats"))),
208​
209 getChangeRequest: (input) =>
210 Effect.all(
211 [
212 cli.getPullRequestDetail(input),
213 cli.getRepositoryAccess({
214 cwd: input.cwd,
215 repository: input.repository,
216 host: input.host,
217 }),
218 // A small permissions query replaces the deeply paginated review-thread walk on the
219 // core path. Writes ask again immediately before mutating, so this is presentation.
220 cli.getViewerAccess(input),
221 ],
222 { concurrency: 3 },
223 ).pipe(
224 Effect.mapError(fail("getChangeRequest")),
225 Effect.map(
226 ([pullRequest, repository, viewerAccess]): ProviderChangeRequestDetail => ({
227 ...pullRequest,
228 reviewers: pullRequest.reviewRequestLogins.map((login) => ({
229 login,
230 name: null,
231 avatarUrl: null,
232 })),
233 mergeCapabilities: repository.mergeCapabilities,
234 viewerPermissions: gitHubViewerPermissions(viewerAccess),
235 }),
236 ),
237 ),
238​
239 getChangeRequestActivity: (input) =>
240 Effect.all(
241 [
242 cli.getPullRequestActivity(input),
243 // Line comments live on review threads, which `gh pr view --json` cannot reach. A
244 // GraphQL hiccup degrades to a truncated conversation rather than blanking activity.
245 cli.listReviewThreadComments(input).pipe(
246 Effect.orElseSucceed(() => ({
247 comments: [],
248 reviewThreads: [],
249 commentCount: 0,
250 truncated: true,
251 reviewers: [],
252 avatarsByLogin: new Map<string, string>(),
253 commitStats: new Map<
254 string,
255 { readonly additions: number; readonly deletions: number }
256 >(),
257 commits: [],
258 viewer: { canUpdate: true, didAuthor: false },
259 })),
260 ),
261 ],
262 { concurrency: 2 },
263 ).pipe(
264 Effect.mapError(fail("getChangeRequestActivity")),
265 Effect.map(
266 ([pullRequest, reviewThreads]): ProviderChangeRequestActivity => ({
267 author: withAvatar(pullRequest.author, reviewThreads.avatarsByLogin, input.host),
268 reviewers: reviewThreads.reviewers,
269 commits: (reviewThreads.commits.length > 0
270 ? reviewThreads.commits
271 : pullRequest.commits
272 ).map((commit) => ({
273 ...commit,
274 ...reviewThreads.commitStats.get(commit.oid),
275 authors: commit.authors?.map(
276 (author) => withAvatar(author, reviewThreads.avatarsByLogin, input.host) ?? author,
277 ),
278 })),
279 comments: [...pullRequest.comments, ...reviewThreads.comments]
280 .map((comment) => ({
281 ...comment,
282 author: withAvatar(comment.author, reviewThreads.avatarsByLogin, input.host),
283 }))
284 .toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
285 // `gh pr view --json comments,reviews` follows GitHub's cursors itself, so those two
286 // are always whole and only the thread walk can stop short of the host.
287 commentCount: pullRequest.comments.length + reviewThreads.commentCount,
288 commentsTruncated: reviewThreads.truncated,
289 reviewThreads: reviewThreads.reviewThreads.map((thread) => ({
290 ...thread,
291 comments: thread.comments.map((comment) => ({
292 ...comment,
293 author: withAvatar(comment.author, reviewThreads.avatarsByLogin, input.host),
294 })),
295 })),
296 }),
297 ),
298 ),
299​
300 getViewerPermissions: (input) =>
301 cli
302 .getViewerAccess(input)
303 .pipe(Effect.mapError(fail("getViewerPermissions")), Effect.map(gitHubViewerPermissions)),
304​
305 getDiff: (input) => cli.getPullRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
306​
307 getDiffFileContents: (input) =>
308 cli.getPullRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),
309​
310 listReviewerCandidates: (input) =>
311 cli.listReviewerCandidates(input).pipe(Effect.mapError(fail("listReviewerCandidates"))),
312​
313 setReviewerRequest: (input) =>
314 cli
315 .setReviewerRequest({
316 cwd: input.cwd,
317 repository: input.repository,
318 host: input.host,
319 number: input.number,
320 reviewers: input.reviewers,
321 requested: input.requested,
322 })
323 .pipe(Effect.mapError(fail("setReviewerRequest"))),
324​
325 runAction: (input) =>
326 cli
327 .runPullRequestAction({
328 cwd: input.cwd,
329 repository: input.repository,
330 host: input.host,
331 number: input.number,
332 action: input.action,
333 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
334 })
335 .pipe(Effect.mapError(fail("runAction"))),
336​
337 comment: (input) => cli.commentOnPullRequest(input).pipe(Effect.mapError(fail("comment"))),
338​
339 submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
340​
341 replyToThread: (input) =>
342 cli
343 .replyToReviewThread({
344 cwd: input.cwd,
345 repository: input.repository,
346 host: input.host,
347 threadId: input.threadId,
348 body: input.body,
349 })
350 .pipe(Effect.mapError(fail("replyToThread"))),
351​
352 setThreadResolution: (input) =>
353 cli
354 .setReviewThreadResolution({
355 cwd: input.cwd,
356 repository: input.repository,
357 host: input.host,
358 threadId: input.threadId,
359 resolved: input.resolved,
360 })
361 .pipe(Effect.mapError(fail("setThreadResolution"))),
362 };
363​
364 return provider;
365});