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

GitHubCli.test.ts

597 lines20.7 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 heads on one repository 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 lookups = yield* Effect.all(
271 ["feature/a", "feature/b"].map((headSelector) =>
272 gh.listPullRequestsByHead({
273 cwd: "/repo",
274 headSelector,
275 state: "all",
276 limit: 100,
277 rateLimitHost: "github.com",
278 }),
279 ),
280 { concurrency: "unbounded" },
281 ).pipe(Effect.forkChild);
282 yield* TestClock.adjust("50 millis");
283 const [first, second] = yield* Fiber.join(lookups);
284 assert.deepStrictEqual(
285 first?.map((pr) => pr.number),
286 [7],
287 );
288 assert.deepStrictEqual(second, []);
289 assert.strictEqual(documents.length, 1);
290 assert.deepStrictEqual(documents[0]!.variables, {
291 owner: "acme",
292 name: "web",
293 h0: "feature/a",
294 s0: ["OPEN", "CLOSED", "MERGED"],
295 h1: "feature/b",
296 s1: ["OPEN", "CLOSED", "MERGED"],
297 });
298 }).pipe(Effect.provide(layer));
299 });
300​
301 it.effect("matches an owner:branch selector on the head owner", () => {
302 const { layer } = harness({
303 remotes,
304 api: {
305 graphql: (input) =>
306 Effect.succeed(
307 encodeJson({
308 data: {
309 repository: {
310 h0: {
311 nodes:
312 input.variables?.h0 === "main"
313 ? [node(9, "main", "someone"), node(8, "main", "me"), node(7, "main", "me")]
314 : [],
315 },
316 },
317 },
318 }),
319 ),
320 },
321 });
322 return Effect.gen(function* () {
323 const gh = yield* GitHubCli.GitHubCli;
324 const open = yield* gh
325 .listOpenPullRequests({ cwd: "/repo", headSelector: "me:main", limit: 1 })
326 .pipe(Effect.forkChild);
327 yield* TestClock.adjust("50 millis");
328 assert.deepStrictEqual(
329 (yield* Fiber.join(open)).map((pr) => pr.number),
330 [8],
331 );
332 }).pipe(Effect.provide(layer));
333 });
334​
335 it.effect("maps API failures onto the errors callers handle", () => {
336 const { layer } = harness({
337 remotes,
338 api: {
339 graphql: (input) =>
340 Effect.fail(
341 input.variables?.h0 === "missing"
342 ? new GitHubCredentials.GitHubCliMissingError({ host: "github.com" })
343 : new GitHubApi.GitHubApiRateLimitError({
344 host: "github.com",
345 operation: "x",
346 retryAt: 123,
347 }),
348 ),
349 },
350 });
351 return Effect.gen(function* () {
352 const gh = yield* GitHubCli.GitHubCli;
353 const read = (headSelector: string) =>
354 gh
355 .listPullRequestsByHead({ cwd: "/repo", headSelector, state: "open", limit: 1 })
356 .pipe(Effect.flip, Effect.forkChild);
357 const missing = yield* read("missing");
358 yield* TestClock.adjust("50 millis");
359 assert.strictEqual((yield* Fiber.join(missing))._tag, "GitHubCliUnavailableError");
360 const limited = yield* read("limited");
361 yield* TestClock.adjust("50 millis");
362 const error = yield* Fiber.join(limited);
363 assert.strictEqual(error._tag, "GitHubCliRateLimitError");
364 assert.propertyVal(error, "retryAt", 123);
365 }).pipe(Effect.provide(layer));
366 });
367});
368​
369describe("GitHubCli.getPullRequest", () => {
370 it.effect("reads a pull request by number, and by URL on its own repository", () => {
371 const variables: Array<unknown> = [];
372 const { layer } = harness({
373 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
374 api: {
375 graphql: (input) =>
376 Effect.sync(() => {
377 variables.push(input.variables);
378 return encodeJson({ data: { repository: { pullRequest: node(42, "feature") } } });
379 }),
380 },
381 });
382 return Effect.gen(function* () {
383 const gh = yield* GitHubCli.GitHubCli;
384 assert.strictEqual((yield* gh.getPullRequest({ cwd: "/repo", reference: "#42" })).number, 42);
385 yield* gh.getPullRequest({
386 cwd: "/repo",
387 reference: "https://github.com/other/thing/pull/42",
388 });
389 assert.deepStrictEqual(variables, [
390 { owner: "acme", name: "web", number: 42 },
391 { owner: "other", name: "thing", number: 42 },
392 ]);
393 }).pipe(Effect.provide(layer));
394 });
395​
396 it.effect("fails a missing pull request as not found", () => {
397 const { layer } = harness({
398 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
399 api: {
400 graphql: () => Effect.succeed(encodeJson({ data: { repository: { pullRequest: null } } })),
401 },
402 });
403 return Effect.gen(function* () {
404 const gh = yield* GitHubCli.GitHubCli;
405 const error = yield* gh.getPullRequest({ cwd: "/repo", reference: "7" }).pipe(Effect.flip);
406 assert.strictEqual(error._tag, "GitHubPullRequestNotFoundError");
407 }).pipe(Effect.provide(layer));
408 });
409});
410​
411describe("GitHubCli writes", () => {
412 it.effect("creates a cross-repository pull request with an owner:branch head", () => {
413 const requests: Array<GitHubApi.GitHubRestInput> = [];
414 const { layer } = harness({
415 remotes: remotesOutput(
416 ["origin", "git@github.com:me/web.git"],
417 ["upstream", "git@github.com:acme/web.git"],
418 ),
419 api: {
420 rest: (input) =>
421 Effect.sync(() => {
422 requests.push(input);
423 return restResponse({ number: 1 }, 201);
424 }),
425 },
426 });
427 return Effect.gen(function* () {
428 const fs = yield* FileSystem.FileSystem;
429 const bodyFile = yield* fs.makeTempFileScoped({ suffix: ".md" });
430 yield* fs.writeFileString(bodyFile, "Body");
431 const gh = yield* GitHubCli.GitHubCli;
432 yield* gh.createPullRequest({
433 cwd: "/repo",
434 baseBranch: "main",
435 headSelector: "me:feature",
436 title: "Title",
437 bodyFile,
438 });
439 assert.strictEqual(requests[0]!.method, "POST");
440 assert.strictEqual(requests[0]!.path, "repos/acme/web/pulls");
441 assert.deepStrictEqual(requests[0]!.body, {
442 base: "main",
443 head: "me:feature",
444 title: "Title",
445 body: "Body",
446 maintainer_can_modify: true,
447 });
448 }).pipe(Effect.provide(Layer.merge(layer, NodeServices.layer)), Effect.scoped);
449 });
450​
451 it.effect("creates a repository under an organization the viewer is not", () => {
452 const requests: Array<string> = [];
453 const { layer } = harness({
454 remotes: "",
455 api: {
456 rest: (input) =>
457 Effect.sync(() => {
458 requests.push(`${input.method ?? "GET"} ${input.path}`);
459 return input.path === "user"
460 ? restResponse({ login: "me" })
461 : restResponse({
462 full_name: "acme/new",
463 html_url: "https://github.com/acme/new",
464 ssh_url: "git@github.com:acme/new.git",
465 });
466 }),
467 },
468 });
469 return Effect.gen(function* () {
470 const gh = yield* GitHubCli.GitHubCli;
471 const urls = yield* gh.createRepository({
472 cwd: "/repo",
473 repository: "acme/new",
474 visibility: "private",
475 });
476 assert.deepStrictEqual(urls, {
477 nameWithOwner: "acme/new",
478 url: "https://github.com/acme/new",
479 sshUrl: "git@github.com:acme/new.git",
480 });
481 assert.deepStrictEqual(requests, ["GET user", "POST orgs/acme/repos"]);
482 }).pipe(Effect.provide(layer));
483 });
484});
485​
486describe("GitHubCli.checkoutPullRequest", () => {
487 const repository = (fullName: string, defaultBranch = "main") =>
488 restResponse({
489 full_name: fullName,
490 html_url: `https://github.com/${fullName}`,
491 ssh_url: `git@github.com:${fullName}.git`,
492 default_branch: defaultBranch,
493 });
494​
495 it.effect("checks a same-repository pull request out from its head branch", () => {
496 const { layer, git } = harness({
497 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
498 api: {
499 graphql: () =>
500 Effect.succeed(
501 encodeJson({ data: { repository: { pullRequest: node(5, "feature/x") } } }),
502 ),
503 },
504 });
505 return Effect.gen(function* () {
506 const gh = yield* GitHubCli.GitHubCli;
507 yield* gh.checkoutPullRequest({ cwd: "/repo", reference: "5" });
508 assert.deepStrictEqual(git, [
509 [
510 "fetchRemoteTrackingBranch",
511 { cwd: "/repo", remoteName: "origin", remoteBranch: "feature/x" },
512 ],
513 ["execute", ["branch", "feature/x", "refs/remotes/origin/feature/x"]],
514 ["switchRef", { cwd: "/repo", refName: "feature/x" }],
515 [
516 "setBranchUpstream",
517 { cwd: "/repo", branch: "feature/x", remoteName: "origin", remoteBranch: "feature/x" },
518 ],
519 ]);
520 }).pipe(Effect.provide(layer));
521 });
522​
523 it.effect("refuses a fork checkout when the base's default branch cannot be read", () => {
524 const { layer, git } = harness({
525 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
526 localBranches: ["main"],
527 api: {
528 graphql: () =>
529 Effect.succeed(
530 encodeJson({ data: { repository: { pullRequest: node(6, "main", "someone") } } }),
531 ),
532 rest: () =>
533 Effect.fail(
534 new GitHubApi.GitHubApiRequestError({
535 host: "github.com",
536 operation: "x",
537 cause: "offline",
538 }),
539 ),
540 },
541 });
542 return Effect.gen(function* () {
543 const gh = yield* GitHubCli.GitHubCli;
544 yield* Effect.flip(gh.checkoutPullRequest({ cwd: "/repo", reference: "6", force: true }));
545 // Nothing touched the local branches: `main` must not be reset to the fork's commit.
546 assert.deepStrictEqual(git, []);
547 }).pipe(Effect.provide(layer));
548 });
549​
550 it.effect("adds a remote for a fork and names a default-branch head after its owner", () => {
551 const { layer, git } = harness({
552 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
553 localBranches: ["someone/main"],
554 api: {
555 graphql: () =>
556 Effect.succeed(
557 encodeJson({ data: { repository: { pullRequest: node(6, "main", "someone") } } }),
558 ),
559 rest: (input) =>
560 Effect.succeed(repository(input.path === "repos/acme/web" ? "acme/web" : "someone/web")),
561 },
562 });
563 return Effect.gen(function* () {
564 const gh = yield* GitHubCli.GitHubCli;
565 yield* gh.checkoutPullRequest({ cwd: "/repo", reference: "6", force: true });
566 assert.deepStrictEqual(git, [
567 [
568 "ensureRemote",
569 { cwd: "/repo", preferredName: "someone", url: "git@github.com:someone/web.git" },
570 ],
571 [
572 "fetchRemoteTrackingBranch",
573 { cwd: "/repo", remoteName: "someone", remoteBranch: "main" },
574 ],
575 ["switchRef", { cwd: "/repo", refName: "someone/main" }],
576 ["execute", ["reset", "--hard", "--quiet", "refs/remotes/someone/main"]],
577 [
578 "setBranchUpstream",
579 { cwd: "/repo", branch: "someone/main", remoteName: "someone", remoteBranch: "main" },
580 ],
581 ]);
582 }).pipe(Effect.provide(layer));
583 });
584​
585 it("names the local branch the way gh pr checkout does", () => {
586 const name = (headRefName: string, isCrossRepository: boolean) =>
587 GitHubCli.pullRequestCheckoutBranchName({
588 headRefName,
589 headOwner: "someone",
590 isCrossRepository,
591 defaultBranch: "main",
592 });
593 assert.strictEqual(name("main", true), "someone/main");
594 assert.strictEqual(name("feature", true), "feature");
595 assert.strictEqual(name("main", false), "main");
596 });
597});