Open History to see the last commit
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 };
106}
107
108describe("GitHubCli repository lookups", () => {
109 it.effect("reads a repository as the account that owns it", () => {
110 const calls: Array<GitHubApi.GitHubRestInput> = [];
111 const { layer } = harness({
112 remotes: "",
113 api: {
114 rest: (input) =>
115 Effect.sync(() => {
116 calls.push(input);
117 return restResponse({
118 full_name: "noext/tire-price-checker-v3",
119 html_url: "https://github.com/noext/tire-price-checker-v3",
120 ssh_url: "git@github.com:noext/tire-price-checker-v3.git",
121 });
122 }),
123 },
124 });
125 return Effect.gen(function* () {
126 const cli = yield* GitHubCli.GitHubCli;
127 const urls = yield* cli.getRepositoryCloneUrls({
128 cwd: "/tmp/checkout",
129 repository: "noext/tire-price-checker-v3",
130 });
131 assert.strictEqual(urls.nameWithOwner, "noext/tire-price-checker-v3");
132 // The owner travels with the request, so a second signed-in account can read it.
133 assert.deepStrictEqual(
134 calls.map((call) => call.account),
135 ["noext"],
136 );
137 assert.strictEqual(calls[0]?.path, "repos/noext/tire-price-checker-v3");
138 }).pipe(Effect.provide(layer));
139 });
140});
141
142describe("selectGitHubBaseRepository", () => {
143 const remotes = (...entries: ReadonlyArray<readonly [string, string]>) =>
144 entries
145 .flatMap(([name, url]) => [`${name}\t${url} (fetch)`, `${name}\t${url} (push)`])
146 .join("\n");
147 const select = (input: { remotes: string; resolved?: string }) =>
148 GitHubCli.selectGitHubBaseRepository({ resolved: "", host: "github.com", ...input });
149
150 it("picks the repository gh reads without a prompt", () => {
151 assert.deepStrictEqual(select({ remotes: remotes(["fork", "git@github.com:me/web.git"]) }), {
152 owner: "me",
153 name: "web",
154 });
155 const fork = remotes(
156 ["origin", "git@github.com:me/web.git"],
157 ["upstream", "https://github.com/Acme/Web.git"],
158 );
159 assert.deepStrictEqual(select({ remotes: fork }), { owner: "acme", name: "web" });
160 assert.deepStrictEqual(select({ remotes: fork, resolved: "remote.origin.gh-resolved base" }), {
161 owner: "me",
162 name: "web",
163 });
164 assert.deepStrictEqual(
165 select({ remotes: fork, resolved: "remote.origin.gh-resolved acme/other" }),
166 { owner: "acme", name: "other" },
167 );
168 // gh ranks remote names in any case.
169 assert.deepStrictEqual(
170 select({
171 remotes: remotes(
172 ["origin", "git@github.com:me/web.git"],
173 ["Upstream", "git@github.com:acme/web.git"],
174 ),
175 }),
176 { owner: "acme", name: "web" },
177 );
178 });
179
180 it("leaves gh to choose when it might weigh the remotes differently", () => {
181 for (const input of [
182 { remotes: "" },
183 {
184 remotes: remotes(["a", "git@github.com:me/web.git"], ["b", "git@github.com:acme/web.git"]),
185 },
186 {
187 remotes: remotes(
188 ["origin", "git@github.com:me/web.git"],
189 ["mirror", "git@gitlab.com:me/web.git"],
190 ),
191 },
192 { remotes: remotes(["origin", "git@github-work:me/web.git"]) },
193 {
194 remotes: remotes(
195 ["origin", "git@github.com:me/web.git"],
196 ["Origin", "git@github.com:acme/web.git"],
197 ),
198 },
199 {
200 remotes: remotes(
201 ["origin", "git@github.com:me/web.git"],
202 ["upstream", "git@github.com:acme/web.git"],
203 ),
204 resolved: "remote.origin.gh-resolved base\nremote.upstream.gh-resolved base",
205 },
206 ]) {
207 assert.strictEqual(select(input), null);
208 }
209 });
210});
211
212describe("GitHubCli repository resolution", () => {
213 it.effect("reads the repository gh would pick from the remotes", () => {
214 const paths: string[] = [];
215 const { layer } = harness({
216 remotes: remotesOutput(
217 ["origin", "git@github.com:me/web.git"],
218 ["upstream", "https://github.com/acme/web.git"],
219 ),
220 api: {
221 rest: (input) =>
222 Effect.sync(() => {
223 paths.push(`${input.host} ${input.path}`);
224 return restResponse({
225 full_name: "acme/web",
226 html_url: "https://github.com/acme/web",
227 ssh_url: "git@github.com:acme/web.git",
228 default_branch: "trunk",
229 });
230 }),
231 },
232 });
233 return Effect.gen(function* () {
234 const gh = yield* GitHubCli.GitHubCli;
235 assert.strictEqual(yield* gh.getDefaultBranch({ cwd: "/repo" }), "trunk");
236 assert.deepStrictEqual(paths, ["github.com repos/acme/web"]);
237 }).pipe(Effect.provide(layer));
238 });
239
240 it.effect("reads an SSH alias remote through github.com", () => {
241 const hosts: string[] = [];
242 const { layer } = harness({
243 remotes: remotesOutput(["origin", "git@github:acme/web.git"]),
244 api: {
245 rest: (input) =>
246 Effect.sync(() => {
247 hosts.push(`${input.host} ${input.path}`);
248 return restResponse({
249 full_name: "acme/web",
250 html_url: "https://github.com/acme/web",
251 ssh_url: "git@github.com:acme/web.git",
252 default_branch: "main",
253 });
254 }),
255 },
256 });
257 return Effect.gen(function* () {
258 const gh = yield* GitHubCli.GitHubCli;
259 yield* gh.getDefaultBranch({ cwd: "/repo" });
260 // A provider's host hint for the same alias (`github` here) resolves the same way.
261 yield* gh.getDefaultBranch({ cwd: "/repo", rateLimitHost: "github" });
262 assert.deepStrictEqual(hosts, ["github.com repos/acme/web", "github.com repos/acme/web"]);
263 assert.strictEqual(
264 GitHubCli.gitHubApiHostForRemote("git@github.example.com:a/b.git"),
265 "github.example.com",
266 );
267 assert.strictEqual(GitHubCli.gitHubApiHostForRemote("git@gitlab.com:a/b.git"), null);
268 }).pipe(Effect.provide(layer));
269 });
270
271 it.effect("fails clearly when no remote is on GitHub", () => {
272 const { layer } = harness({
273 remotes: remotesOutput(["origin", "git@gitlab.com:a/b.git"]),
274 api: {},
275 });
276 return Effect.gen(function* () {
277 const gh = yield* GitHubCli.GitHubCli;
278 const error = yield* gh.getDefaultBranch({ cwd: "/repo" }).pipe(Effect.flip);
279 assert.strictEqual(error._tag, "GitHubCliCommandError");
280 assert.include(String((error.cause as Error).message), "No GitHub repository");
281 }).pipe(Effect.provide(layer));
282 });
283});
284
285describe("GitHubCli.listPullRequestsByHead", () => {
286 const remotes = remotesOutput(["origin", "git@github.com:acme/web.git"]);
287
288 it.effect("reads heads on one repository in one GraphQL document", () => {
289 const documents: Array<GitHubApi.GitHubGraphQlInput> = [];
290 const { layer } = harness({
291 remotes,
292 api: {
293 graphql: (input) =>
294 Effect.sync(() => {
295 documents.push(input);
296 return encodeJson({
297 data: { repository: { h0: { nodes: [node(7, "feature/a")] }, h1: { nodes: [] } } },
298 });
299 }),
300 },
301 });
302 return Effect.gen(function* () {
303 const gh = yield* GitHubCli.GitHubCli;
304 const lookups = yield* Effect.all(
305 ["feature/a", "feature/b"].map((headSelector) =>
306 gh.listPullRequestsByHead({
307 cwd: "/repo",
308 headSelector,
309 state: "all",
310 limit: 100,
311 rateLimitHost: "github.com",
312 }),
313 ),
314 { concurrency: "unbounded" },
315 ).pipe(Effect.forkChild);
316 yield* TestClock.adjust("50 millis");
317 const [first, second] = yield* Fiber.join(lookups);
318 assert.deepStrictEqual(
319 first?.map((pr) => pr.number),
320 [7],
321 );
322 assert.deepStrictEqual(second, []);
323 assert.strictEqual(documents.length, 1);
324 assert.deepStrictEqual(documents[0]!.variables, {
325 owner: "acme",
326 name: "web",
327 h0: "feature/a",
328 s0: ["OPEN", "CLOSED", "MERGED"],
329 h1: "feature/b",
330 s1: ["OPEN", "CLOSED", "MERGED"],
331 });
332 }).pipe(Effect.provide(layer));
333 });
334
335 it.effect("matches an owner:branch selector on the head owner", () => {
336 const { layer } = harness({
337 remotes,
338 api: {
339 graphql: (input) =>
340 Effect.succeed(
341 encodeJson({
342 data: {
343 repository: {
344 h0: {
345 nodes:
346 input.variables?.h0 === "main"
347 ? [node(9, "main", "someone"), node(8, "main", "me"), node(7, "main", "me")]
348 : [],
349 },
350 },
351 },
352 }),
353 ),
354 },
355 });
356 return Effect.gen(function* () {
357 const gh = yield* GitHubCli.GitHubCli;
358 const open = yield* gh
359 .listOpenPullRequests({ cwd: "/repo", headSelector: "me:main", limit: 1 })
360 .pipe(Effect.forkChild);
361 yield* TestClock.adjust("50 millis");
362 assert.deepStrictEqual(
363 (yield* Fiber.join(open)).map((pr) => pr.number),
364 [8],
365 );
366 }).pipe(Effect.provide(layer));
367 });
368
369 it.effect("maps API failures onto the errors callers handle", () => {
370 const { layer } = harness({
371 remotes,
372 api: {
373 graphql: (input) =>
374 Effect.fail(
375 input.variables?.h0 === "missing"
376 ? new GitHubCredentials.GitHubCliMissingError({ host: "github.com" })
377 : new GitHubApi.GitHubApiRateLimitError({
378 host: "github.com",
379 operation: "x",
380 retryAt: 123,
381 }),
382 ),
383 },
384 });
385 return Effect.gen(function* () {
386 const gh = yield* GitHubCli.GitHubCli;
387 const read = (headSelector: string) =>
388 gh
389 .listPullRequestsByHead({ cwd: "/repo", headSelector, state: "open", limit: 1 })
390 .pipe(Effect.flip, Effect.forkChild);
391 const missing = yield* read("missing");
392 yield* TestClock.adjust("50 millis");
393 assert.strictEqual((yield* Fiber.join(missing))._tag, "GitHubCliUnavailableError");
394 const limited = yield* read("limited");
395 yield* TestClock.adjust("50 millis");
396 const error = yield* Fiber.join(limited);
397 assert.strictEqual(error._tag, "GitHubCliRateLimitError");
398 assert.propertyVal(error, "retryAt", 123);
399 }).pipe(Effect.provide(layer));
400 });
401});
402
403describe("GitHubCli.getPullRequest", () => {
404 it.effect("reads a pull request by number, and by URL on its own repository", () => {
405 const variables: Array<unknown> = [];
406 const { layer } = harness({
407 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
408 api: {
409 graphql: (input) =>
410 Effect.sync(() => {
411 variables.push(input.variables);
412 return encodeJson({ data: { repository: { pullRequest: node(42, "feature") } } });
413 }),
414 },
415 });
416 return Effect.gen(function* () {
417 const gh = yield* GitHubCli.GitHubCli;
418 assert.strictEqual((yield* gh.getPullRequest({ cwd: "/repo", reference: "#42" })).number, 42);
419 yield* gh.getPullRequest({
420 cwd: "/repo",
421 reference: "https://github.com/other/thing/pull/42",
422 });
423 assert.deepStrictEqual(variables, [
424 { owner: "acme", name: "web", number: 42 },
425 { owner: "other", name: "thing", number: 42 },
426 ]);
427 }).pipe(Effect.provide(layer));
428 });
429
430 it.effect("fails a missing pull request as not found", () => {
431 const { layer } = harness({
432 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
433 api: {
434 graphql: () => Effect.succeed(encodeJson({ data: { repository: { pullRequest: null } } })),
435 },
436 });
437 return Effect.gen(function* () {
438 const gh = yield* GitHubCli.GitHubCli;
439 const error = yield* gh.getPullRequest({ cwd: "/repo", reference: "7" }).pipe(Effect.flip);
440 assert.strictEqual(error._tag, "GitHubPullRequestNotFoundError");
441 }).pipe(Effect.provide(layer));
442 });
443});
444
445describe("GitHubCli writes", () => {
446 it.effect("creates a cross-repository pull request with an owner:branch head", () => {
447 const requests: Array<GitHubApi.GitHubRestInput> = [];
448 const { layer } = harness({
449 remotes: remotesOutput(
450 ["origin", "git@github.com:me/web.git"],
451 ["upstream", "git@github.com:acme/web.git"],
452 ),
453 api: {
454 rest: (input) =>
455 Effect.sync(() => {
456 requests.push(input);
457 return restResponse({ number: 1 }, 201);
458 }),
459 },
460 });
461 return Effect.gen(function* () {
462 const fs = yield* FileSystem.FileSystem;
463 const bodyFile = yield* fs.makeTempFileScoped({ suffix: ".md" });
464 yield* fs.writeFileString(bodyFile, "Body");
465 const gh = yield* GitHubCli.GitHubCli;
466 yield* gh.createPullRequest({
467 cwd: "/repo",
468 baseBranch: "main",
469 headSelector: "me:feature",
470 title: "Title",
471 bodyFile,
472 });
473 assert.strictEqual(requests[0]!.method, "POST");
474 assert.strictEqual(requests[0]!.path, "repos/acme/web/pulls");
475 assert.deepStrictEqual(requests[0]!.body, {
476 base: "main",
477 head: "me:feature",
478 title: "Title",
479 body: "Body",
480 maintainer_can_modify: true,
481 });
482 }).pipe(Effect.provide(Layer.merge(layer, NodeServices.layer)), Effect.scoped);
483 });
484
485 it.effect("creates a repository under an organization the viewer is not", () => {
486 const requests: Array<string> = [];
487 const { layer } = harness({
488 remotes: "",
489 api: {
490 rest: (input) =>
491 Effect.sync(() => {
492 requests.push(`${input.method ?? "GET"} ${input.path}`);
493 return input.path === "user"
494 ? restResponse({ login: "me" })
495 : restResponse({
496 full_name: "acme/new",
497 html_url: "https://github.com/acme/new",
498 ssh_url: "git@github.com:acme/new.git",
499 });
500 }),
501 },
502 });
503 return Effect.gen(function* () {
504 const gh = yield* GitHubCli.GitHubCli;
505 const urls = yield* gh.createRepository({
506 cwd: "/repo",
507 repository: "acme/new",
508 visibility: "private",
509 });
510 assert.deepStrictEqual(urls, {
511 nameWithOwner: "acme/new",
512 url: "https://github.com/acme/new",
513 sshUrl: "git@github.com:acme/new.git",
514 });
515 assert.deepStrictEqual(requests, ["GET user", "POST orgs/acme/repos"]);
516 }).pipe(Effect.provide(layer));
517 });
518});
519
520describe("GitHubCli.checkoutPullRequest", () => {
521 const repository = (fullName: string, defaultBranch = "main") =>
522 restResponse({
523 full_name: fullName,
524 html_url: `https://github.com/${fullName}`,
525 ssh_url: `git@github.com:${fullName}.git`,
526 default_branch: defaultBranch,
527 });
528
529 it.effect("checks a same-repository pull request out from its head branch", () => {
530 const { layer, git } = harness({
531 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
532 api: {
533 graphql: () =>
534 Effect.succeed(
535 encodeJson({ data: { repository: { pullRequest: node(5, "feature/x") } } }),
536 ),
537 },
538 });
539 return Effect.gen(function* () {
540 const gh = yield* GitHubCli.GitHubCli;
541 yield* gh.checkoutPullRequest({ cwd: "/repo", reference: "5" });
542 assert.deepStrictEqual(git, [
543 [
544 "fetchRemoteTrackingBranch",
545 { cwd: "/repo", remoteName: "origin", remoteBranch: "feature/x" },
546 ],
547 ["execute", ["branch", "feature/x", "refs/remotes/origin/feature/x"]],
548 ["switchRef", { cwd: "/repo", refName: "feature/x" }],
549 [
550 "setBranchUpstream",
551 { cwd: "/repo", branch: "feature/x", remoteName: "origin", remoteBranch: "feature/x" },
552 ],
553 ]);
554 }).pipe(Effect.provide(layer));
555 });
556
557 it.effect("refuses a fork checkout when the base's default branch cannot be read", () => {
558 const { layer, git } = harness({
559 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
560 localBranches: ["main"],
561 api: {
562 graphql: () =>
563 Effect.succeed(
564 encodeJson({ data: { repository: { pullRequest: node(6, "main", "someone") } } }),
565 ),
566 rest: () =>
567 Effect.fail(
568 new GitHubApi.GitHubApiRequestError({
569 host: "github.com",
570 operation: "x",
571 cause: "offline",
572 }),
573 ),
574 },
575 });
576 return Effect.gen(function* () {
577 const gh = yield* GitHubCli.GitHubCli;
578 yield* Effect.flip(gh.checkoutPullRequest({ cwd: "/repo", reference: "6", force: true }));
579 // Nothing touched the local branches: `main` must not be reset to the fork's commit.
580 assert.deepStrictEqual(git, []);
581 }).pipe(Effect.provide(layer));
582 });
583
584 it.effect("adds a remote for a fork and names a default-branch head after its owner", () => {
585 const { layer, git } = harness({
586 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
587 localBranches: ["someone/main"],
588 api: {
589 graphql: () =>
590 Effect.succeed(
591 encodeJson({ data: { repository: { pullRequest: node(6, "main", "someone") } } }),
592 ),
593 rest: (input) =>
594 Effect.succeed(repository(input.path === "repos/acme/web" ? "acme/web" : "someone/web")),
595 },
596 });
597 return Effect.gen(function* () {
598 const gh = yield* GitHubCli.GitHubCli;
599 yield* gh.checkoutPullRequest({ cwd: "/repo", reference: "6", force: true });
600 assert.deepStrictEqual(git, [
601 [
602 "ensureRemote",
603 { cwd: "/repo", preferredName: "someone", url: "git@github.com:someone/web.git" },
604 ],
605 [
606 "fetchRemoteTrackingBranch",
607 { cwd: "/repo", remoteName: "someone", remoteBranch: "main" },
608 ],
609 ["switchRef", { cwd: "/repo", refName: "someone/main" }],
610 ["execute", ["reset", "--hard", "--quiet", "refs/remotes/someone/main"]],
611 [
612 "setBranchUpstream",
613 { cwd: "/repo", branch: "someone/main", remoteName: "someone", remoteBranch: "main" },
614 ],
615 ]);
616 }).pipe(Effect.provide(layer));
617 });
618
619 it("names the local branch the way gh pr checkout does", () => {
620 const name = (headRefName: string, isCrossRepository: boolean) =>
621 GitHubCli.pullRequestCheckoutBranchName({
622 headRefName,
623 headOwner: "someone",
624 isCrossRepository,
625 defaultBranch: "main",
626 });
627 assert.strictEqual(name("main", true), "someone/main");
628 assert.strictEqual(name("feature", true), "feature");
629 assert.strictEqual(name("main", false), "main");
630 });
631});