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

GitHubPullRequestProvider.test.ts

450 lines14.3 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import type { PullRequestReaction } from "@t3tools/contracts";
5​
6import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";
7import { gitHubViewerPermissions, loginAvatarUrl, make } from "./GitHubPullRequestProvider.ts";
8import type { GitHubReviewThreadComments } from "./gitHubPullRequestJson.ts";
9​
10describe("gitHubViewerPermissions", () => {
11 it("offers everything to a viewer who can write to the repository", () => {
12 expect(gitHubViewerPermissions({ canWrite: true, canUpdate: true, didAuthor: false })).toEqual({
13 // Arming a merge for later is the merge, so it travels with it.
14 actions: [
15 "merge",
16 "enable-auto-merge",
17 "disable-auto-merge",
18 "ready",
19 "draft",
20 "close",
21 "reopen",
22 ],
23 comment: true,
24 resolve: true,
25 verdicts: ["comment", "approve", "request-changes"],
26 requestReviewers: true,
27 });
28 });
29​
30 it("leaves a passer-by on a repository they can only read nothing but the review", () => {
31 // Every open-source pull request somebody else opened: GitHub says no to all five actions
32 // and to resolving, and yes to commenting and to every verdict.
33 expect(
34 gitHubViewerPermissions({ canWrite: false, canUpdate: false, didAuthor: false }),
35 ).toEqual({
36 actions: [],
37 comment: true,
38 resolve: false,
39 verdicts: ["comment", "approve", "request-changes"],
40 // Asking somebody else to review is the one thing read access never stretches to.
41 requestReviewers: false,
42 });
43 });
44​
45 it("keeps an author's own pull request theirs to close, with read access and no more", () => {
46 expect(gitHubViewerPermissions({ canWrite: false, canUpdate: true, didAuthor: true })).toEqual({
47 // Merging is the one thing writing is needed for, now or later; the rest an author may do.
48 actions: ["ready", "draft", "close", "reopen"],
49 comment: true,
50 resolve: true,
51 // GitHub refuses an author's approval of their own change, so the page does not offer one.
52 verdicts: ["comment"],
53 requestReviewers: false,
54 });
55 });
56​
57 it.effect("uses the small viewer-access read for core permissions", () =>
58 Effect.gen(function* () {
59 const provider = yield* make;
60 const detail = yield* provider.getChangeRequest({
61 cwd: "/w",
62 repository: "acme/web",
63 host: "github.com",
64 number: 7,
65 });
66​
67 expect(detail.viewerPermissions).toEqual({
68 actions: ["ready", "draft", "close", "reopen"],
69 comment: true,
70 resolve: false,
71 verdicts: ["comment", "approve", "request-changes"],
72 requestReviewers: false,
73 });
74 }).pipe(
75 Effect.provide(
76 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
77 getPullRequestDetail: () =>
78 Effect.succeed({
79 authorId: null,
80 number: 7,
81 title: "Pull request 7",
82 url: "https://github.com/acme/web/pull/7",
83 author: null,
84 headRepositoryOwner: null,
85 headBranch: "feat/page",
86 baseBranch: "main",
87 state: "open",
88 isDraft: false,
89 mergeability: "mergeable",
90 reviewDecision: null,
91 additions: 1,
92 deletions: 1,
93 createdAt: "2026-07-01T00:00:00Z",
94 updatedAt: "2026-07-02T00:00:00Z",
95 reviewRequestLogins: [],
96 hasTeamReviewRequest: false,
97 checksState: null,
98 labels: [],
99 body: "",
100 changedFiles: 1,
101 mergedAt: null,
102 closedAt: null,
103 checks: [],
104 comments: [],
105 commits: [],
106 }),
107 getRepositoryAccess: () =>
108 Effect.succeed({
109 canWrite: false,
110 mergeCapabilities: { merge: true, squash: true, rebase: true },
111 }),
112 getViewerAccess: () =>
113 Effect.succeed({ canWrite: false, canUpdate: true, didAuthor: false }),
114 }),
115 ),
116 ),
117 );
118});
119​
120describe("getViewerPermissions", () => {
121 const openDetail = {
122 authorId: null,
123 number: 7,
124 title: "Pull request 7",
125 url: "https://github.com/acme/web/pull/7",
126 author: null,
127 headRepositoryOwner: "acme",
128 headBranch: "feat/page",
129 baseBranch: "main",
130 state: "open" as const,
131 isDraft: false,
132 mergeability: "mergeable" as const,
133 reviewDecision: null,
134 additions: 1,
135 deletions: 1,
136 createdAt: "2026-07-01T00:00:00Z",
137 updatedAt: "2026-07-02T00:00:00Z",
138 reviewRequestLogins: [],
139 hasTeamReviewRequest: false,
140 checksState: null,
141 labels: [],
142 body: "",
143 changedFiles: 1,
144 mergedAt: null,
145 closedAt: null,
146 checks: [],
147 comments: [],
148 commits: [],
149 };
150​
151 const layerWithComparison = (
152 comparison: Effect.Effect<{
153 readonly behindBy: number | null;
154 readonly viewerCanUpdate: boolean;
155 }>,
156 ) =>
157 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
158 getPullRequestDetail: () => Effect.succeed(openDetail),
159 getPullRequestBaseComparison: () => comparison,
160 getViewerAccess: () => Effect.succeed({ canWrite: true, canUpdate: true, didAuthor: false }),
161 });
162​
163 it.effect("offers update-branch when the comparison grants it", () =>
164 Effect.gen(function* () {
165 const provider = yield* make;
166 const permissions = yield* provider.getViewerPermissions({
167 cwd: "/w",
168 repository: "acme/web",
169 host: "github.com",
170 number: 7,
171 });
172​
173 expect(permissions.actions).toContain("update-branch");
174 expect(permissions.updateMethods).toEqual(["merge", "rebase"]);
175 }).pipe(
176 Effect.provide(layerWithComparison(Effect.succeed({ behindBy: 3, viewerCanUpdate: true }))),
177 ),
178 );
179​
180 it.effect("withholds update-branch when the comparison cannot be read", () =>
181 Effect.gen(function* () {
182 const provider = yield* make;
183 const permissions = yield* provider.getViewerPermissions({
184 cwd: "/w",
185 repository: "acme/web",
186 host: "github.com",
187 number: 7,
188 });
189​
190 expect(permissions.actions).not.toContain("update-branch");
191 expect(permissions.updateMethods).toBeUndefined();
192 // The rest of the answer survives a comparison nobody could make.
193 expect(permissions.actions).toContain("merge");
194 }).pipe(
195 Effect.provide(
196 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
197 getPullRequestDetail: () => Effect.succeed(openDetail),
198 getPullRequestBaseComparison: () =>
199 Effect.fail(
200 new GitHubPullRequestCli.GitHubPullRequestReadError({
201 command: "gh",
202 cwd: "/w",
203 operation: "getPullRequestBaseComparison",
204 cause: new Error("unreadable"),
205 }),
206 ),
207 getViewerAccess: () =>
208 Effect.succeed({ canWrite: true, canUpdate: true, didAuthor: false }),
209 }),
210 ),
211 ),
212 );
213});
214​
215describe("getChangeRequest commits", () => {
216 const baseDetail = {
217 authorId: null,
218 number: 7,
219 title: "Pull request 7",
220 url: "https://github.com/acme/web/pull/7",
221 author: null,
222 headBranch: "feat/page",
223 baseBranch: "main",
224 state: "open" as const,
225 isDraft: false,
226 mergeability: "mergeable" as const,
227 additions: 1,
228 deletions: 1,
229 createdAt: "2026-07-01T00:00:00Z",
230 updatedAt: "2026-07-02T00:00:00Z",
231 reviewRequestLogins: [],
232 hasTeamReviewRequest: false,
233 checksState: null,
234 labels: [],
235 body: "",
236 changedFiles: 1,
237 mergedAt: null,
238 closedAt: null,
239 checks: [],
240 comments: [],
241 };
242​
243 const baseThreadComments = {
244 comments: [],
245 dismissalsByReviewId: new Map<string, string>(),
246 reviewThreads: [],
247 commentCount: 0,
248 truncated: false,
249 reactions: [],
250 reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
251 reviewers: [],
252 avatarsByLogin: new Map<string, string>(),
253 commitStats: new Map<string, { readonly additions: number; readonly deletions: number }>(),
254 viewer: { canUpdate: true, didAuthor: false },
255 };
256​
257 const layerWith = (commits: GitHubReviewThreadComments["commits"]) =>
258 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
259 getPullRequestActivity: () =>
260 Effect.succeed({
261 author: baseDetail.author,
262 comments: baseDetail.comments,
263 commits: [
264 {
265 oid: "view-oldest",
266 messageHeadline: "gh pr view's oldest commit",
267 committedDate: "2026-01-01T00:00:00Z",
268 authors: [],
269 },
270 ],
271 }),
272 listReviewThreadComments: () => Effect.succeed({ ...baseThreadComments, commits }),
273 });
274​
275 it.effect("prefers the GraphQL commits, which are the newest, over the gh view list", () =>
276 Effect.gen(function* () {
277 const provider = yield* make;
278 const detail = yield* provider.getChangeRequestActivity({
279 cwd: "/w",
280 repository: "acme/web",
281 host: "github.com",
282 number: 7,
283 });
284​
285 expect(detail.commits.map((commit) => commit.oid)).toEqual(["graphql-newest"]);
286 }).pipe(
287 Effect.provide(
288 layerWith([
289 {
290 oid: "graphql-newest",
291 messageHeadline: "the newest commit gh pr view drops",
292 committedDate: "2026-07-06T00:00:00Z",
293 authors: [],
294 },
295 ]),
296 ),
297 ),
298 );
299​
300 it.effect("falls back to the gh view list when the GraphQL read has no commits", () =>
301 Effect.gen(function* () {
302 const provider = yield* make;
303 const detail = yield* provider.getChangeRequestActivity({
304 cwd: "/w",
305 repository: "acme/web",
306 host: "github.com",
307 number: 7,
308 });
309​
310 expect(detail.commits.map((commit) => commit.oid)).toEqual(["view-oldest"]);
311 }).pipe(Effect.provide(layerWith([]))),
312 );
313});
314​
315describe("getChangeRequestActivity dismissed reviews", () => {
316 const dismissedReview = (body: string) => ({
317 id: "PRR_1",
318 kind: "review" as const,
319 author: null,
320 body,
321 createdAt: "2026-07-03T00:00:00Z",
322 url: null,
323 path: null,
324 reviewState: "DISMISSED",
325 });
326 const threadComments: GitHubReviewThreadComments = {
327 comments: [],
328 dismissalsByReviewId: new Map([["PRR_1", "Dismissing prior approval to re-evaluate 9b66581"]]),
329 reviewThreads: [],
330 commentCount: 0,
331 truncated: false,
332 reactions: [],
333 reactionsById: new Map(),
334 reviewers: [],
335 avatarsByLogin: new Map(),
336 commitStats: new Map(),
337 commits: [],
338 viewer: { canUpdate: true, didAuthor: false },
339 };
340 const layerFor = (body: string) =>
341 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
342 getPullRequestActivity: () =>
343 Effect.succeed({ author: null, comments: [dismissedReview(body)], commits: [] }),
344 listReviewThreadComments: () => Effect.succeed(threadComments),
345 });
346 const readActivity = Effect.gen(function* () {
347 const provider = yield* make;
348 return yield* provider.getChangeRequestActivity({
349 cwd: "/w",
350 repository: "acme/web",
351 host: "github.com",
352 number: 7,
353 });
354 });
355​
356 it.effect("fills a marker-only dismissed review with the timeline's reason", () =>
357 // Macroscope's approvals carry only an HTML comment, which markdown renders as nothing —
358 // an empty-string check misses them and the card opens onto nothing.
359 readActivity.pipe(
360 Effect.map((activity) => {
361 expect(activity.comments[0]?.body).toBe("Dismissing prior approval to re-evaluate 9b66581");
362 }),
363 Effect.provide(layerFor("<!-- Macroscope (Approvability) review body marker -->")),
364 ),
365 );
366​
367 it.effect("keeps the words of a dismissed review that has its own", () =>
368 readActivity.pipe(
369 Effect.map((activity) => {
370 expect(activity.comments[0]?.body).toBe("These findings still stand.");
371 }),
372 Effect.provide(layerFor("These findings still stand.")),
373 ),
374 );
375});
376​
377describe("editing", () => {
378 const rewrites: Array<unknown> = [];
379​
380 it.effect("hands a rewrite to the CLI as the request named it", () =>
381 Effect.gen(function* () {
382 const provider = yield* make;
383​
384 expect(provider.capabilities.edit).toEqual({ changeRequest: true, comment: true });
385 yield* provider.updateChangeRequest!({
386 cwd: "/w",
387 repository: "acme/web",
388 host: "github.com",
389 number: 7,
390 title: "A better title",
391 });
392 yield* provider.updateComment!({
393 cwd: "/w",
394 repository: "acme/web",
395 host: "github.com",
396 number: 7,
397 commentId: "IC_1",
398 kind: "review-comment",
399 body: "Reworded.",
400 });
401​
402 expect(rewrites).toEqual([
403 {
404 cwd: "/w",
405 repository: "acme/web",
406 host: "github.com",
407 number: 7,
408 title: "A better title",
409 },
410 {
411 cwd: "/w",
412 repository: "acme/web",
413 host: "github.com",
414 number: 7,
415 commentId: "IC_1",
416 kind: "review-comment",
417 body: "Reworded.",
418 },
419 ]);
420 }).pipe(
421 Effect.provide(
422 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
423 updatePullRequest: (input) => Effect.sync(() => void rewrites.push(input)),
424 updateComment: (input) => Effect.sync(() => void rewrites.push(input)),
425 }),
426 ),
427 ),
428 );
429});
430​
431describe("loginAvatarUrl", () => {
432 it("serves a user's picture from the host they belong to", () => {
433 expect(loginAvatarUrl("octocat", "github.com")).toBe("https://github.com/octocat.png?size=80");
434 expect(loginAvatarUrl("octocat", "ghe.example.com")).toBe(
435 "https://ghe.example.com/octocat.png?size=80",
436 );
437 });
438​
439 it("has nothing for an app, which names no page", () => {
440 // `dependabot[bot]` has a picture, but not at `/dependabot[bot].png` — a guess that 404s is
441 // worse than the initials it would replace.
442 expect(loginAvatarUrl("dependabot[bot]", "github.com")).toBeNull();
443 });
444​
445 it("refuses anything that is not a login, rather than building a URL out of it", () => {
446 for (const login of ["../../etc", "a b", "-leading", "x".repeat(40), ""]) {
447 expect(loginAvatarUrl(login, "github.com")).toBeNull();
448 }
449 });
450});