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

GitHubCli.test.ts

638 lines22.1 KB

1import { assert, it, describe } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as TestClock from "effect/testing/TestClock";
4import * as Effect from "effect/Effect";
5import * as Fiber from "effect/Fiber";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Schema from "effect/Schema";
9import { ChildProcessSpawner } from "effect/process";
10​
11import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
12import * as VcsProcess from "../vcs/VcsProcess.ts";
13import * as GitHubApi from "./GitHubApi.ts";
14import * as GitHubCli from "./GitHubCli.ts";
15import * as GitHubCredentials from "./GitHubCredentials.ts";
16​
17const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
18​
19const processOutput = (stdout: string, exitCode = 0): VcsProcess.VcsProcessOutput => ({
20 exitCode: ChildProcessSpawner.ExitCode(exitCode),
21 stdout,
22 stderr: "",
23 stdoutTruncated: false,
24 stderrTruncated: false,
25});
26​
27const remotesOutput = (...entries: ReadonlyArray<readonly [string, string]>) =>
28 entries
29 .flatMap(([name, url]) => [`${name}\t${url} (fetch)`, `${name}\t${url} (push)`])
30 .join("\n");
31​
32const restResponse = (body: unknown, status = 200): GitHubApi.GitHubRestResponse => ({
33 status,
34 headers: {},
35 body: body === undefined ? "" : encodeJson(body),
36 truncated: false,
37 invalidUtf8: false,
38});
39​
40const node = (number: number, headRefName: string, owner = "acme") => ({
41 number,
42 title: `PR ${number}`,
43 url: `https://github.com/acme/web/pull/${number}`,
44 baseRefName: "main",
45 headRefName,
46 state: "OPEN",
47 isCrossRepository: owner !== "acme",
48 updatedAt: "2026-01-02T00:00:00Z",
49 headRepository: { name: "web", nameWithOwner: `${owner}/web` },
50 headRepositoryOwner: { login: owner },
51});
52​
53/**
54 * A GitHubCli over a mocked GitHubApi, git driver and process. `remotes` is what
55 * `git remote -v` prints; `git` records every driver call.
56 */
57function harness(input: {
58 readonly remotes: string;
59 readonly api: Partial<GitHubApi.GitHubApi["Service"]>;
60 readonly localBranches?: ReadonlyArray<string>;
61}) {
62 const git: Array<readonly [string, unknown]> = [];
63 const record =
64 <A>(name: string, value: A) =>
65 (args: unknown) =>
66 Effect.sync(() => {
67 git.push([name, args]);
68 return value;
69 });
70 const driver = Layer.mock(GitVcsDriver.GitVcsDriver)({
71 execute: (args) =>
72 Effect.sync(() => {
73 git.push(["execute", args.args]);
74 return processOutput("");
75 }),
76 resolvePrimaryRemoteName: () => Effect.succeed("origin"),
77 readConfigValue: () => Effect.succeed("git@github.com:acme/web.git"),
78 ensureRemote: (args) =>
79 Effect.sync(() => {
80 git.push(["ensureRemote", args]);
81 return args.preferredName;
82 }),
83 fetchRemoteTrackingBranch: (args) => record("fetchRemoteTrackingBranch", undefined)(args),
84 setBranchUpstream: (args) => record("setBranchUpstream", undefined)(args),
85 switchRef: (args) => record("switchRef", { refName: args.refName })(args) as never,
86 listLocalBranchNames: () => Effect.succeed([...(input.localBranches ?? [])]),
87 resolveCommit: () => Effect.succeed({ commitSha: "abc123" }),
88 });
89 const process = Layer.mock(VcsProcess.VcsProcess)({
90 run: (args) =>
91 Effect.succeed(
92 args.args[0] === "remote" ? processOutput(input.remotes) : processOutput("", 1),
93 ),
94 });
95 const layer = Layer.effect(GitHubCli.GitHubCli, GitHubCli.make).pipe(
96 Layer.provide(
97 Layer.mergeAll(
98 driver,
99 process,
100 Layer.mock(GitHubApi.GitHubApi)(input.api),
101 NodeServices.layer,
102 ),
103 ),
104 );
105 return { layer, git };
107​
108describe("selectGitHubBaseRepository", () => {
109 const remotes = (...entries: ReadonlyArray<readonly [string, string]>) =>
110 entries
111 .flatMap(([name, url]) => [`${name}\t${url} (fetch)`, `${name}\t${url} (push)`])
112 .join("\n");
113 const select = (input: { remotes: string; resolved?: string }) =>
114 GitHubCli.selectGitHubBaseRepository({ resolved: "", host: "github.com", ...input });
115​
116 it("picks the repository gh reads without a prompt", () => {
117 assert.deepStrictEqual(select({ remotes: remotes(["fork", "git@github.com:me/web.git"]) }), {
118 owner: "me",
119 name: "web",
120 });
121 const fork = remotes(
122 ["origin", "git@github.com:me/web.git"],
123 ["upstream", "https://github.com/Acme/Web.git"],
124 );
125 assert.deepStrictEqual(select({ remotes: fork }), { owner: "acme", name: "web" });
126 assert.deepStrictEqual(select({ remotes: fork, resolved: "remote.origin.gh-resolved base" }), {
127 owner: "me",
128 name: "web",
129 });
130 assert.deepStrictEqual(
131 select({ remotes: fork, resolved: "remote.origin.gh-resolved acme/other" }),
132 { owner: "acme", name: "other" },
133 );
134 // gh ranks remote names in any case.
135 assert.deepStrictEqual(
136 select({
137 remotes: remotes(
138 ["origin", "git@github.com:me/web.git"],
139 ["Upstream", "git@github.com:acme/web.git"],
140 ),
141 }),
142 { owner: "acme", name: "web" },
143 );
144 });
145​
146 it("leaves gh to choose when it might weigh the remotes differently", () => {
147 for (const input of [
148 { remotes: "" },
149 {
150 remotes: remotes(["a", "git@github.com:me/web.git"], ["b", "git@github.com:acme/web.git"]),
151 },
152 {
153 remotes: remotes(
154 ["origin", "git@github.com:me/web.git"],
155 ["mirror", "git@gitlab.com:me/web.git"],
156 ),
157 },
158 { remotes: remotes(["origin", "git@github-work:me/web.git"]) },
159 {
160 remotes: remotes(
161 ["origin", "git@github.com:me/web.git"],
162 ["Origin", "git@github.com:acme/web.git"],
163 ),
164 },
165 {
166 remotes: remotes(
167 ["origin", "git@github.com:me/web.git"],
168 ["upstream", "git@github.com:acme/web.git"],
169 ),
170 resolved: "remote.origin.gh-resolved base\nremote.upstream.gh-resolved base",
171 },
172 ]) {
173 assert.strictEqual(select(input), null);
174 }
175 });
176});
177​
178describe("GitHubCli repository resolution", () => {
179 it.effect("reads the repository gh would pick from the remotes", () => {
180 const paths: string[] = [];
181 const { layer } = harness({
182 remotes: remotesOutput(
183 ["origin", "git@github.com:me/web.git"],
184 ["upstream", "https://github.com/acme/web.git"],
185 ),
186 api: {
187 rest: (input) =>
188 Effect.sync(() => {
189 paths.push(`${input.host} ${input.path}`);
190 return restResponse({
191 full_name: "acme/web",
192 html_url: "https://github.com/acme/web",
193 ssh_url: "git@github.com:acme/web.git",
194 default_branch: "trunk",
195 });
196 }),
197 },
198 });
199 return Effect.gen(function* () {
200 const gh = yield* GitHubCli.GitHubCli;
201 assert.strictEqual(yield* gh.getDefaultBranch({ cwd: "/repo" }), "trunk");
202 assert.deepStrictEqual(paths, ["github.com repos/acme/web"]);
203 }).pipe(Effect.provide(layer));
204 });
205​
206 it.effect("reads an SSH alias remote through github.com", () => {
207 const hosts: string[] = [];
208 const { layer } = harness({
209 remotes: remotesOutput(["origin", "git@github:acme/web.git"]),
210 api: {
211 rest: (input) =>
212 Effect.sync(() => {
213 hosts.push(`${input.host} ${input.path}`);
214 return restResponse({
215 full_name: "acme/web",
216 html_url: "https://github.com/acme/web",
217 ssh_url: "git@github.com:acme/web.git",
218 default_branch: "main",
219 });
220 }),
221 },
222 });
223 return Effect.gen(function* () {
224 const gh = yield* GitHubCli.GitHubCli;
225 yield* gh.getDefaultBranch({ cwd: "/repo" });
226 // A provider's host hint for the same alias (`github` here) resolves the same way.
227 yield* gh.getDefaultBranch({ cwd: "/repo", rateLimitHost: "github" });
228 assert.deepStrictEqual(hosts, ["github.com repos/acme/web", "github.com repos/acme/web"]);
229 assert.strictEqual(
230 GitHubCli.gitHubApiHostForRemote("git@github.example.com:a/b.git"),
231 "github.example.com",
232 );
233 assert.strictEqual(GitHubCli.gitHubApiHostForRemote("git@gitlab.com:a/b.git"), null);
234 }).pipe(Effect.provide(layer));
235 });
236​
237 it.effect("fails clearly when no remote is on GitHub", () => {
238 const { layer } = harness({
239 remotes: remotesOutput(["origin", "git@gitlab.com:a/b.git"]),
240 api: {},
241 });
242 return Effect.gen(function* () {
243 const gh = yield* GitHubCli.GitHubCli;
244 const error = yield* gh.getDefaultBranch({ cwd: "/repo" }).pipe(Effect.flip);
245 assert.strictEqual(error._tag, "GitHubCliCommandError");
246 assert.include(String((error.cause as Error).message), "No GitHub repository");
247 }).pipe(Effect.provide(layer));
248 });
249});
250​
251describe("GitHubCli.listPullRequestsByHead", () => {
252 const remotes = remotesOutput(["origin", "git@github.com:acme/web.git"]);
253​
254 it.effect("reads a background sweep's staggered heads in one GraphQL document", () => {
255 const documents: Array<GitHubApi.GitHubGraphQlInput> = [];
256 const { layer } = harness({
257 remotes,
258 api: {
259 graphql: (input) =>
260 Effect.sync(() => {
261 documents.push(input);
262 return encodeJson({
263 data: { repository: { h0: { nodes: [node(7, "feature/a")] }, h1: { nodes: [] } } },
264 });
265 }),
266 },
267 });
268 return Effect.gen(function* () {
269 const gh = yield* GitHubCli.GitHubCli;
270 const lookup = (headSelector: string) =>
271 gh
272 .listPullRequestsByHead({
273 cwd: "/repo",
274 headSelector,
275 state: "all",
276 limit: 100,
277 rateLimitHost: "github.com",
278 })
279 .pipe(Effect.forkChild);
280 // Each branch's own git reads come first, so a sweep's lookups arrive spread out.
281 const firstLookup = yield* lookup("feature/a");
282 yield* TestClock.adjust("200 millis");
283 const secondLookup = yield* lookup("feature/b");
284 yield* TestClock.adjust("300 millis");
285 const first = yield* Fiber.join(firstLookup);
286 const second = yield* Fiber.join(secondLookup);
287 assert.deepStrictEqual(
288 first?.map((pr) => pr.number),
289 [7],
290 );
291 assert.deepStrictEqual(second, []);
292 assert.strictEqual(documents.length, 1);
293 assert.deepStrictEqual(documents[0]!.variables, {
294 owner: "acme",
295 name: "web",
296 h0: "feature/a",
297 s0: ["OPEN", "CLOSED", "MERGED"],
298 h1: "feature/b",
299 s1: ["OPEN", "CLOSED", "MERGED"],
300 });
301 }).pipe(Effect.provide(layer));
302 });
303​
304 it.effect("caps a background document at twenty-five heads", () => {
305 const headCounts: Array<number> = [];
306 const { layer } = harness({
307 remotes,
308 api: {
309 graphql: (input) =>
310 Effect.sync(() => {
311 const heads = Object.keys(input.variables ?? {}).filter((key) => /^h\d+$/.test(key));
312 headCounts.push(heads.length);
313 return encodeJson({
314 data: { repository: Object.fromEntries(heads.map((key) => [key, { nodes: [] }])) },
315 });
316 }),
317 },
318 });
319 return Effect.gen(function* () {
320 const gh = yield* GitHubCli.GitHubCli;
321 const lookups = yield* Effect.all(
322 Array.from({ length: 26 }, (_, index) =>
323 gh.listPullRequestsByHead({
324 cwd: "/repo",
325 headSelector: `feature/${index}`,
326 state: "all",
327 limit: 100,
328 rateLimitHost: "github.com",
329 }),
330 ),
331 { concurrency: "unbounded" },
332 ).pipe(Effect.forkChild);
333 yield* TestClock.adjust("500 millis");
334 yield* Fiber.join(lookups);
335 assert.deepStrictEqual(
336 headCounts.toSorted((a, b) => a - b),
337 [1, 25],
338 );
339 }).pipe(Effect.provide(layer));
340 });
341​
342 it.effect("matches an owner:branch selector on the head owner", () => {
343 const { layer } = harness({
344 remotes,
345 api: {
346 graphql: (input) =>
347 Effect.succeed(
348 encodeJson({
349 data: {
350 repository: {
351 h0: {
352 nodes:
353 input.variables?.h0 === "main"
354 ? [node(9, "main", "someone"), node(8, "main", "me"), node(7, "main", "me")]
355 : [],
356 },
357 },
358 },
359 }),
360 ),
361 },
362 });
363 return Effect.gen(function* () {
364 const gh = yield* GitHubCli.GitHubCli;
365 const open = yield* gh
366 .listOpenPullRequests({ cwd: "/repo", headSelector: "me:main", limit: 1 })
367 .pipe(Effect.forkChild);
368 yield* TestClock.adjust("50 millis");
369 assert.deepStrictEqual(
370 (yield* Fiber.join(open)).map((pr) => pr.number),
371 [8],
372 );
373 }).pipe(Effect.provide(layer));
374 });
375​
376 it.effect("maps API failures onto the errors callers handle", () => {
377 const { layer } = harness({
378 remotes,
379 api: {
380 graphql: (input) =>
381 Effect.fail(
382 input.variables?.h0 === "missing"
383 ? new GitHubCredentials.GitHubCliMissingError({ host: "github.com" })
384 : new GitHubApi.GitHubApiRateLimitError({
385 host: "github.com",
386 operation: "x",
387 retryAt: 123,
388 }),
389 ),
390 },
391 });
392 return Effect.gen(function* () {
393 const gh = yield* GitHubCli.GitHubCli;
394 const read = (headSelector: string) =>
395 gh
396 .listPullRequestsByHead({ cwd: "/repo", headSelector, state: "open", limit: 1 })
397 .pipe(Effect.flip, Effect.forkChild);
398 const missing = yield* read("missing");
399 yield* TestClock.adjust("500 millis");
400 assert.strictEqual((yield* Fiber.join(missing))._tag, "GitHubCliUnavailableError");
401 const limited = yield* read("limited");
402 yield* TestClock.adjust("500 millis");
403 const error = yield* Fiber.join(limited);
404 assert.strictEqual(error._tag, "GitHubCliRateLimitError");
405 assert.propertyVal(error, "retryAt", 123);
406 }).pipe(Effect.provide(layer));
407 });
408});
409​
410describe("GitHubCli.getPullRequest", () => {
411 it.effect("reads a pull request by number, and by URL on its own repository", () => {
412 const variables: Array<unknown> = [];
413 const { layer } = harness({
414 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
415 api: {
416 graphql: (input) =>
417 Effect.sync(() => {
418 variables.push(input.variables);
419 return encodeJson({ data: { repository: { pullRequest: node(42, "feature") } } });
420 }),
421 },
422 });
423 return Effect.gen(function* () {
424 const gh = yield* GitHubCli.GitHubCli;
425 assert.strictEqual((yield* gh.getPullRequest({ cwd: "/repo", reference: "#42" })).number, 42);
426 yield* gh.getPullRequest({
427 cwd: "/repo",
428 reference: "https://github.com/other/thing/pull/42",
429 });
430 assert.deepStrictEqual(variables, [
431 { owner: "acme", name: "web", number: 42 },
432 { owner: "other", name: "thing", number: 42 },
433 ]);
434 }).pipe(Effect.provide(layer));
435 });
436​
437 it.effect("fails a missing pull request as not found", () => {
438 const { layer } = harness({
439 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
440 api: {
441 graphql: () => Effect.succeed(encodeJson({ data: { repository: { pullRequest: null } } })),
442 },
443 });
444 return Effect.gen(function* () {
445 const gh = yield* GitHubCli.GitHubCli;
446 const error = yield* gh.getPullRequest({ cwd: "/repo", reference: "7" }).pipe(Effect.flip);
447 assert.strictEqual(error._tag, "GitHubPullRequestNotFoundError");
448 }).pipe(Effect.provide(layer));
449 });
450});
451​
452describe("GitHubCli writes", () => {
453 it.effect("creates a cross-repository pull request with an owner:branch head", () => {
454 const requests: Array<GitHubApi.GitHubRestInput> = [];
455 const { layer } = harness({
456 remotes: remotesOutput(
457 ["origin", "git@github.com:me/web.git"],
458 ["upstream", "git@github.com:acme/web.git"],
459 ),
460 api: {
461 rest: (input) =>
462 Effect.sync(() => {
463 requests.push(input);
464 return restResponse({ number: 1 }, 201);
465 }),
466 },
467 });
468 return Effect.gen(function* () {
469 const fs = yield* FileSystem.FileSystem;
470 const bodyFile = yield* fs.makeTempFileScoped({ suffix: ".md" });
471 yield* fs.writeFileString(bodyFile, "Body");
472 const gh = yield* GitHubCli.GitHubCli;
473 yield* gh.createPullRequest({
474 cwd: "/repo",
475 baseBranch: "main",
476 headSelector: "me:feature",
477 title: "Title",
478 bodyFile,
479 });
480 assert.strictEqual(requests[0]!.method, "POST");
481 assert.strictEqual(requests[0]!.path, "repos/acme/web/pulls");
482 assert.deepStrictEqual(requests[0]!.body, {
483 base: "main",
484 head: "me:feature",
485 title: "Title",
486 body: "Body",
487 maintainer_can_modify: true,
488 });
489 }).pipe(Effect.provide(Layer.merge(layer, NodeServices.layer)), Effect.scoped);
490 });
491​
492 it.effect("creates a repository under an organization the viewer is not", () => {
493 const requests: Array<string> = [];
494 const { layer } = harness({
495 remotes: "",
496 api: {
497 rest: (input) =>
498 Effect.sync(() => {
499 requests.push(`${input.method ?? "GET"} ${input.path}`);
500 return input.path === "user"
501 ? restResponse({ login: "me" })
502 : restResponse({
503 full_name: "acme/new",
504 html_url: "https://github.com/acme/new",
505 ssh_url: "git@github.com:acme/new.git",
506 });
507 }),
508 },
509 });
510 return Effect.gen(function* () {
511 const gh = yield* GitHubCli.GitHubCli;
512 const urls = yield* gh.createRepository({
513 cwd: "/repo",
514 repository: "acme/new",
515 visibility: "private",
516 });
517 assert.deepStrictEqual(urls, {
518 nameWithOwner: "acme/new",
519 url: "https://github.com/acme/new",
520 sshUrl: "git@github.com:acme/new.git",
521 });
522 assert.deepStrictEqual(requests, ["GET user", "POST orgs/acme/repos"]);
523 }).pipe(Effect.provide(layer));
524 });
525});
526​
527describe("GitHubCli.checkoutPullRequest", () => {
528 const repository = (fullName: string, defaultBranch = "main") =>
529 restResponse({
530 full_name: fullName,
531 html_url: `https://github.com/${fullName}`,
532 ssh_url: `git@github.com:${fullName}.git`,
533 default_branch: defaultBranch,
534 });
535​
536 it.effect("checks a same-repository pull request out from its head branch", () => {
537 const { layer, git } = harness({
538 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
539 api: {
540 graphql: () =>
541 Effect.succeed(
542 encodeJson({ data: { repository: { pullRequest: node(5, "feature/x") } } }),
543 ),
544 },
545 });
546 return Effect.gen(function* () {
547 const gh = yield* GitHubCli.GitHubCli;
548 yield* gh.checkoutPullRequest({ cwd: "/repo", reference: "5" });
549 assert.deepStrictEqual(git, [
550 [
551 "fetchRemoteTrackingBranch",
552 { cwd: "/repo", remoteName: "origin", remoteBranch: "feature/x" },
553 ],
554 ["execute", ["branch", "feature/x", "refs/remotes/origin/feature/x"]],
555 ["switchRef", { cwd: "/repo", refName: "feature/x" }],
556 [
557 "setBranchUpstream",
558 { cwd: "/repo", branch: "feature/x", remoteName: "origin", remoteBranch: "feature/x" },
559 ],
560 ]);
561 }).pipe(Effect.provide(layer));
562 });
563​
564 it.effect("refuses a fork checkout when the base's default branch cannot be read", () => {
565 const { layer, git } = harness({
566 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
567 localBranches: ["main"],
568 api: {
569 graphql: () =>
570 Effect.succeed(
571 encodeJson({ data: { repository: { pullRequest: node(6, "main", "someone") } } }),
572 ),
573 rest: () =>
574 Effect.fail(
575 new GitHubApi.GitHubApiRequestError({
576 host: "github.com",
577 operation: "x",
578 cause: "offline",
579 }),
580 ),
581 },
582 });
583 return Effect.gen(function* () {
584 const gh = yield* GitHubCli.GitHubCli;
585 yield* Effect.flip(gh.checkoutPullRequest({ cwd: "/repo", reference: "6", force: true }));
586 // Nothing touched the local branches: `main` must not be reset to the fork's commit.
587 assert.deepStrictEqual(git, []);
588 }).pipe(Effect.provide(layer));
589 });
590​
591 it.effect("adds a remote for a fork and names a default-branch head after its owner", () => {
592 const { layer, git } = harness({
593 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
594 localBranches: ["someone/main"],
595 api: {
596 graphql: () =>
597 Effect.succeed(
598 encodeJson({ data: { repository: { pullRequest: node(6, "main", "someone") } } }),
599 ),
600 rest: (input) =>
601 Effect.succeed(repository(input.path === "repos/acme/web" ? "acme/web" : "someone/web")),
602 },
603 });
604 return Effect.gen(function* () {
605 const gh = yield* GitHubCli.GitHubCli;
606 yield* gh.checkoutPullRequest({ cwd: "/repo", reference: "6", force: true });
607 assert.deepStrictEqual(git, [
608 [
609 "ensureRemote",
610 { cwd: "/repo", preferredName: "someone", url: "git@github.com:someone/web.git" },
611 ],
612 [
613 "fetchRemoteTrackingBranch",
614 { cwd: "/repo", remoteName: "someone", remoteBranch: "main" },
615 ],
616 ["switchRef", { cwd: "/repo", refName: "someone/main" }],
617 ["execute", ["reset", "--hard", "--quiet", "refs/remotes/someone/main"]],
618 [
619 "setBranchUpstream",
620 { cwd: "/repo", branch: "someone/main", remoteName: "someone", remoteBranch: "main" },
621 ],
622 ]);
623 }).pipe(Effect.provide(layer));
624 });
625​
626 it("names the local branch the way gh pr checkout does", () => {
627 const name = (headRefName: string, isCrossRepository: boolean) =>
628 GitHubCli.pullRequestCheckoutBranchName({
629 headRefName,
630 headOwner: "someone",
631 isCrossRepository,
632 defaultBranch: "main",
633 });
634 assert.strictEqual(name("main", true), "someone/main");
635 assert.strictEqual(name("feature", true), "feature");
636 assert.strictEqual(name("main", false), "main");
637 });
638});