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

GitHubCli.test.ts

997 lines34.5 KB

1import { assert, it, afterEach, describe, expect, vi } from "@effect/vitest";
2import * as Cache from "effect/Cache";
3import * as TestClock from "effect/testing/TestClock";
4import * as Clock from "effect/Clock";
5import * as DateTime from "effect/DateTime";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as Layer from "effect/Layer";
9import * as PlatformError from "effect/PlatformError";
10import * as Redacted from "effect/Redacted";
11import * as Schema from "effect/Schema";
12import { ChildProcessSpawner } from "effect/process";
13import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
14​
15import * as VcsProcess from "../vcs/VcsProcess.ts";
16import * as GitHubCli from "./GitHubCli.ts";
17import * as GitHubGraphQlBudget from "./githubGraphQlBudget.ts";
18import * as SourceControlRateLimit from "./SourceControlRateLimit.ts";
19​
20const encodeGitHubCliError = Schema.encodeEffect(Schema.fromJsonString(GitHubCli.GitHubCliError));
21​
22const processOutput = (stdout: string): VcsProcess.VcsProcessOutput => ({
23 exitCode: ChildProcessSpawner.ExitCode(0),
24 stdout,
25 stderr: "",
26 stdoutTruncated: false,
27 stderrTruncated: false,
28});
29​
30const quotaOutput = (remaining = 5000, resetAt = "2099-01-01T00:00:00Z") =>
31 processOutput(
32 JSON.stringify({ data: { rateLimit: { cost: 1, limit: 5000, remaining, resetAt } } }),
33 );
34​
35const isBudgetReading = (input: VcsProcess.VcsProcessInput) =>
36 input.args[0] === "api" &&
37 input.args[1] === "graphql" &&
38 input.args.at(-1)?.includes("rateLimit");
39​
40const mockRun = vi.fn<VcsProcess.VcsProcess["Service"]["run"]>();
41​
42// Budget readings are answered here, so `mockRun` sees only the commands under test.
43const layer = GitHubCli.layer.pipe(
44 Layer.provide(
45 Layer.mock(VcsProcess.VcsProcess)({
46 run: (input) => (isBudgetReading(input) ? Effect.succeed(quotaOutput()) : mockRun(input)),
47 }),
48 ),
49);
50​
51afterEach(() => {
52 mockRun.mockReset();
53});
54​
55it.effect("reads the GraphQL budget once per window, preserves the reserve, and resumes", () =>
56 Effect.gen(function* () {
57 let readings = 0;
58 const commands: string[] = [];
59 let remaining = 501;
60 let resetAt = DateTime.formatIso(
61 DateTime.makeUnsafe((yield* Clock.currentTimeMillis) + 60_000),
62 );
63 const gh = yield* GitHubCli.make.pipe(
64 Effect.provideService(VcsProcess.VcsProcess, {
65 run: (input) =>
66 Effect.sync(() => {
67 if (isBudgetReading(input)) {
68 readings++;
69 assert.strictEqual(input.args[3], "enterprise.test");
70 return quotaOutput(remaining, resetAt);
71 }
72 commands.push(input.args.slice(0, 2).join(" "));
73 return processOutput("[]");
74 }),
75 }),
76 );
77 const read = (command: string) =>
78 gh.execute({
79 cwd: "/repo",
80 args:
81 command === "repo"
82 ? ["repo", "view", "enterprise.test/acme/web", "--json", "name"]
83 : ["pr", command, "--repo=enterprise.test/acme/web", "--json", "number"],
84 });
85 yield* read("list");
86 const failure = yield* read("view").pipe(Effect.flip);
87 assert.strictEqual(failure._tag, "GitHubCliRateLimitError");
88 assert.deepStrictEqual(commands, ["pr list"]);
89 yield* read("view").pipe(Effect.provideService(GitHubCli.AllowGitHubReserve, true));
90 yield* gh.execute({ cwd: "/repo", args: ["pr", "merge", "1"] });
91 assert.deepStrictEqual(commands, ["pr list", "pr view", "pr merge"]);
92 // One reading covers the whole window.
93 assert.strictEqual(readings, 1);
94 yield* TestClock.adjust("1 minute");
95 remaining = 5000;
96 resetAt = DateTime.formatIso(DateTime.makeUnsafe((yield* Clock.currentTimeMillis) + 60_000));
97 yield* Effect.all([read("list"), read("repo")], { concurrency: 2 });
98 assert.strictEqual(readings, 2);
99 assert.deepStrictEqual(commands.slice(3).toSorted(), ["pr list", "repo view"]);
100 }).pipe(Effect.provide(Layer.merge(GitHubGraphQlBudget.layer, SourceControlRateLimit.layer))),
101);
102​
103it.effect("reads the budget again at a near reset, and every ten minutes in a long window", () =>
104 Effect.gen(function* () {
105 let readings = 0;
106 const startedAt = yield* Clock.currentTimeMillis;
107 let resetAt = DateTime.formatIso(DateTime.makeUnsafe(startedAt + 10_000));
108 const gh = yield* GitHubCli.make.pipe(
109 Effect.provideService(VcsProcess.VcsProcess, {
110 run: (input) =>
111 Effect.sync(() => {
112 if (!isBudgetReading(input)) return processOutput("[]");
113 readings++;
114 return quotaOutput(5000, resetAt);
115 }),
116 }),
117 );
118 const read = gh.execute({ cwd: "/repo", args: ["pr", "list"] });
119 yield* read;
120 // The window resets ten seconds in, so the reading expires with it.
121 resetAt = DateTime.formatIso(DateTime.makeUnsafe(startedAt + 10_000 + 3_600_000));
122 yield* TestClock.adjust("10 seconds");
123 yield* read;
124 assert.strictEqual(readings, 2);
125 yield* TestClock.adjust("9 minutes");
126 yield* read;
127 assert.strictEqual(readings, 2);
128 yield* TestClock.adjust("1 minute");
129 yield* read;
130 assert.strictEqual(readings, 3);
131 }).pipe(Effect.provide(Layer.merge(GitHubGraphQlBudget.layer, SourceControlRateLimit.layer))),
132);
133​
134it.effect("reads anyway when the budget reading fails", () =>
135 Effect.gen(function* () {
136 const gh = yield* GitHubCli.make.pipe(
137 Effect.provideService(VcsProcess.VcsProcess, {
138 run: (input) =>
139 isBudgetReading(input)
140 ? Effect.fail(
141 new VcsProcessSpawnError({
142 operation: "GitHubCli.execute",
143 command: "gh",
144 cwd: "/gone",
145 cause: new Error("ENOENT"),
146 }),
147 )
148 : Effect.succeed(processOutput("[]")),
149 }),
150 );
151 const result = yield* gh.execute({ cwd: "/repo", args: ["pr", "list"] });
152 assert.strictEqual(result.stdout, "[]");
153 }).pipe(Effect.provide(Layer.merge(GitHubGraphQlBudget.layer, SourceControlRateLimit.layer))),
154);
155​
156describe("selectGitHubBaseRepository", () => {
157 const remotes = (...entries: ReadonlyArray<readonly [string, string]>) =>
158 entries
159 .flatMap(([name, url]) => [`${name}\t${url} (fetch)`, `${name}\t${url} (push)`])
160 .join("\n");
161 const select = (input: { remotes: string; resolved?: string }) =>
162 GitHubCli.selectGitHubBaseRepository({ resolved: "", host: "github.com", ...input });
163​
164 it("picks the repository gh reads without a prompt", () => {
165 assert.deepStrictEqual(select({ remotes: remotes(["fork", "git@github.com:me/web.git"]) }), {
166 owner: "me",
167 name: "web",
168 });
169 const fork = remotes(
170 ["origin", "git@github.com:me/web.git"],
171 ["upstream", "https://github.com/Acme/Web.git"],
172 );
173 assert.deepStrictEqual(select({ remotes: fork }), { owner: "acme", name: "web" });
174 assert.deepStrictEqual(select({ remotes: fork, resolved: "remote.origin.gh-resolved base" }), {
175 owner: "me",
176 name: "web",
177 });
178 assert.deepStrictEqual(
179 select({ remotes: fork, resolved: "remote.origin.gh-resolved acme/other" }),
180 { owner: "acme", name: "other" },
181 );
182 // gh ranks remote names in any case.
183 assert.deepStrictEqual(
184 select({
185 remotes: remotes(
186 ["origin", "git@github.com:me/web.git"],
187 ["Upstream", "git@github.com:acme/web.git"],
188 ),
189 }),
190 { owner: "acme", name: "web" },
191 );
192 });
193​
194 it("leaves gh to choose when it might weigh the remotes differently", () => {
195 for (const input of [
196 { remotes: "" },
197 {
198 remotes: remotes(["a", "git@github.com:me/web.git"], ["b", "git@github.com:acme/web.git"]),
199 },
200 {
201 remotes: remotes(
202 ["origin", "git@github.com:me/web.git"],
203 ["mirror", "git@gitlab.com:me/web.git"],
204 ),
205 },
206 { remotes: remotes(["origin", "git@github-work:me/web.git"]) },
207 {
208 remotes: remotes(
209 ["origin", "git@github.com:me/web.git"],
210 ["Origin", "git@github.com:acme/web.git"],
211 ),
212 },
213 {
214 remotes: remotes(
215 ["origin", "git@github.com:me/web.git"],
216 ["upstream", "git@github.com:acme/web.git"],
217 ),
218 resolved: "remote.origin.gh-resolved base\nremote.upstream.gh-resolved base",
219 },
220 ]) {
221 assert.strictEqual(select(input), null);
222 }
223 });
224});
225​
226describe("GitHubCli.listPullRequestsByHead", () => {
227 const remoteOutput =
228 "origin\tgit@github.com:acme/web.git (fetch)\norigin\tgit@github.com:acme/web.git (push)\n";
229 const node = (number: number, headRefName: string) => ({
230 number,
231 title: `PR ${number}`,
232 url: `https://github.com/acme/web/pull/${number}`,
233 baseRefName: "main",
234 headRefName,
235 state: "MERGED",
236 mergedAt: "2026-01-01T00:00:00Z",
237 updatedAt: "2026-01-02T00:00:00Z",
238 headRepository: { name: "web", nameWithOwner: "acme/web" },
239 headRepositoryOwner: { login: "acme" },
240 });
241 const decodeRequest = Schema.decodeSync(
242 Schema.fromJsonString(
243 Schema.Struct({
244 query: Schema.String,
245 variables: Schema.Record(Schema.String, Schema.Unknown),
246 }),
247 ),
248 );
249 const jsonOutput = (value: unknown) => processOutput(JSON.stringify(value));
250 const git = (input: VcsProcess.VcsProcessInput) =>
251 input.args[0] === "remote"
252 ? processOutput(remoteOutput)
253 : { ...processOutput(""), exitCode: ChildProcessSpawner.ExitCode(1) };
254​
255 it.effect("reads heads on one repository in one GraphQL document", () =>
256 Effect.gen(function* () {
257 const documents: Array<{ query: string; variables: Record<string, unknown> }> = [];
258 mockRun.mockImplementation((input) =>
259 Effect.sync(() => {
260 if (input.command === "git") return git(input);
261 documents.push(decodeRequest(input.stdin ?? ""));
262 return jsonOutput({
263 data: {
264 repository: { h0: { nodes: [node(7, "feature/a")] }, h1: { nodes: [] } },
265 rateLimit: { cost: 1, limit: 5000, remaining: 4999, resetAt: "2099-01-01T00:00:00Z" },
266 },
267 });
268 }),
269 );
270 const gh = yield* GitHubCli.GitHubCli;
271 const lookups = yield* Effect.all(
272 ["feature/a", "feature/b"].map((headSelector) =>
273 gh.listPullRequestsByHead({
274 cwd: "/repo",
275 headSelector,
276 state: "all",
277 limit: 100,
278 rateLimitHost: "github.com",
279 }),
280 ),
281 { concurrency: "unbounded" },
282 ).pipe(Effect.forkChild);
283 yield* TestClock.adjust("50 millis");
284 const [first, second] = yield* Fiber.join(lookups);
285 assert.deepStrictEqual(
286 first?.map((pr) => [pr.number, pr.state, pr.headRepositoryNameWithOwner]),
287 [[7, "merged", "acme/web"]],
288 );
289 assert.deepStrictEqual(second, []);
290 assert.strictEqual(documents.length, 1);
291 assert.include(documents[0]!.query, "rateLimit");
292 assert.deepStrictEqual(documents[0]!.variables, {
293 owner: "acme",
294 name: "web",
295 h0: "feature/a",
296 s0: ["OPEN", "CLOSED", "MERGED"],
297 h1: "feature/b",
298 s1: ["OPEN", "CLOSED", "MERGED"],
299 });
300 }).pipe(Effect.provide(layer)),
301 );
302​
303 it.effect("asks gh pr list when gh could read another repository", () =>
304 Effect.gen(function* () {
305 const commands: Array<ReadonlyArray<string>> = [];
306 mockRun.mockImplementation((input) =>
307 Effect.sync(() => {
308 commands.push([input.command, ...input.args]);
309 if (input.command === "git") {
310 return processOutput(
311 input.args[0] === "remote"
312 ? "a\tgit@github.com:me/web.git (fetch)\nb\tgit@github.com:acme/web.git (fetch)\n"
313 : "",
314 );
315 }
316 return input.args[3] === "feature/empty"
317 ? processOutput("")
318 : jsonOutput([node(8, "feature/a")]);
319 }),
320 );
321 const gh = yield* GitHubCli.GitHubCli;
322 const pullRequests = yield* gh.listPullRequestsByHead({
323 cwd: "/repo",
324 headSelector: "feature/a",
325 state: "all",
326 limit: 100,
327 rateLimitHost: "github.com",
328 });
329 assert.deepStrictEqual(
330 pullRequests.map((pr) => pr.number),
331 [8],
332 );
333 assert.deepStrictEqual(commands.at(-1), [
334 "gh",
335 "pr",
336 "list",
337 "--head",
338 "feature/a",
339 "--state",
340 "all",
341 "--limit",
342 "100",
343 "--json",
344 "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
345 ]);
346 const empty = yield* gh.listPullRequestsByHead({
347 cwd: "/repo",
348 headSelector: "feature/empty",
349 state: "all",
350 limit: 100,
351 rateLimitHost: "github.com",
352 });
353 assert.deepStrictEqual(empty, []);
354 }).pipe(Effect.provide(layer)),
355 );
356​
357 it.effect("fails a rate-limited document whole instead of asking head by head", () =>
358 Effect.gen(function* () {
359 let ghCalls = 0;
360 mockRun.mockImplementation((input) => {
361 if (input.command === "git") return Effect.succeed(git(input));
362 ghCalls++;
363 return Effect.fail(
364 new VcsProcessExitError({
365 operation: "GitHubCli.execute",
366 command: "gh",
367 cwd: "/repo",
368 exitCode: 1,
369 failureKind: "rate-limited",
370 detail: "API rate limit exceeded.",
371 stderrLength: 24,
372 stderrTruncated: false,
373 }),
374 );
375 });
376 const gh = yield* GitHubCli.GitHubCli;
377 const lookups = yield* Effect.all(
378 ["feature/a", "feature/b"].map((headSelector) =>
379 gh
380 .listPullRequestsByHead({
381 cwd: "/repo",
382 headSelector,
383 state: "all",
384 limit: 100,
385 rateLimitHost: "github.com",
386 })
387 .pipe(Effect.flip),
388 ),
389 { concurrency: "unbounded" },
390 ).pipe(Effect.forkChild);
391 yield* TestClock.adjust("50 millis");
392 const errors = yield* Fiber.join(lookups);
393 assert.deepStrictEqual(
394 errors.map((error) => error._tag),
395 ["GitHubCliRateLimitError", "GitHubCliRateLimitError"],
396 );
397 assert.strictEqual(ghCalls, 1);
398 }).pipe(Effect.provide(layer)),
399 );
400});
401​
402describe("GitHubCli.layer", () => {
403 it.effect("shares the registry budget with CLI reads through nested layer providers", () =>
404 Effect.gen(function* () {
405 const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;
406 const gh = yield* GitHubCli.GitHubCli;
407 yield* budget.observe("github.com", quotaOutput(0).stdout);
408 const error = yield* gh.execute({ cwd: "/repo", args: ["pr", "list"] }).pipe(Effect.flip);
409 assert.strictEqual(error._tag, "GitHubCliRateLimitError");
410 expect(mockRun).not.toHaveBeenCalled();
411 }).pipe(Effect.provide(layer.pipe(Layer.provide(GitHubGraphQlBudget.layer)))),
412 );
413​
414 it.effect("keeps quota snapshots separate for verified credentials on the same host", () =>
415 Effect.gen(function* () {
416 let reads = 0;
417 const gh = yield* GitHubCli.make.pipe(
418 Effect.provideService(VcsProcess.VcsProcess, {
419 run: (input) =>
420 Effect.sync(() => {
421 if (isBudgetReading(input)) {
422 return quotaOutput(input.env?.GH_TOKEN === "empty" ? 0 : 5000);
423 }
424 reads++;
425 return processOutput("[]");
426 }),
427 }),
428 );
429 const read = (token: string) =>
430 gh.execute({ cwd: "/repo", args: ["pr", "list", "--repo", "github.com/acme/web"] }).pipe(
431 Effect.provideService(GitHubCli.PinnedGitHubCredential, {
432 host: "github.com",
433 token: Redacted.make(token),
434 credentialFingerprint: token,
435 }),
436 );
437 yield* read("empty").pipe(Effect.flip);
438 yield* read("healthy");
439 yield* read("empty").pipe(Effect.flip);
440 assert.strictEqual(reads, 1);
441 }).pipe(Effect.provide(Layer.merge(GitHubGraphQlBudget.layer, SourceControlRateLimit.layer))),
442 );
443​
444 it.effect("pins concurrent cached commands to their own verified credentials", () =>
445 Effect.gen(function* () {
446 mockRun.mockImplementation((input) =>
447 Effect.succeed(processOutput(input.env?.GH_TOKEN ?? "ambient")),
448 );
449 const gh = yield* GitHubCli.GitHubCli;
450 // Constructed outside either request, like the PR service's read caches.
451 const cache = yield* Cache.make({
452 lookup: (host: string) =>
453 gh.execute({
454 cwd: "/repo",
455 args: ["api", "user", "--hostname", host],
456 env: { GH_DEBUG: "api", GH_TOKEN: "changed-after-verification" },
457 }),
458 capacity: 2,
459 timeToLive: "1 minute",
460 });
461 const results = yield* Effect.forEach(
462 ["github.com", "github.example.test"],
463 (host, index) =>
464 Cache.get(cache, host).pipe(
465 Effect.provideService(GitHubCli.PinnedGitHubCredential, {
466 host,
467 token: Redacted.make(`credential-${index}`),
468 credentialFingerprint: `fingerprint-${index}`,
469 }),
470 ),
471 { concurrency: 2 },
472 );
473 expect(results.map((result) => result.stdout)).toEqual(["credential-0", "credential-1"]);
474 for (const [input] of mockRun.mock.calls) {
475 expect(input.env).toMatchObject({
476 GH_HOST: input.args[3],
477 GH_DEBUG: "",
478 GH_TOKEN: input.env?.GITHUB_TOKEN,
479 GH_ENTERPRISE_TOKEN: input.env?.GH_TOKEN,
480 GITHUB_ENTERPRISE_TOKEN: input.env?.GH_TOKEN,
481 });
482 }
483 expect((yield* gh.execute({ cwd: "/repo", args: ["api", "user"] })).stdout).toBe("ambient");
484 }).pipe(Effect.provide(layer)),
485 );
486​
487 it.effect("refuses other or implicit hosts before exposing a scoped credential to gh", () =>
488 Effect.gen(function* () {
489 const gh = yield* GitHubCli.GitHubCli;
490 for (const args of [
491 ["api", "user", "--hostname", "other.example.test"],
492 ["api", "user", "--hostname=other.example.test"],
493 ["pr", "view", "1", "--repo", "other.example.test/owner/repo"],
494 ["repo", "view", "other.example.test/owner/repo", "--json", "name"],
495 ["api", "https://other.example.test/user", "--hostname", "github.com"],
496 ["api", "user"],
497 ]) {
498 const failure = yield* gh.execute({ cwd: "/repo", args }).pipe(
499 Effect.provideService(GitHubCli.PinnedGitHubCredential, {
500 host: "github.com",
501 token: Redacted.make("secret-credential"),
502 credentialFingerprint: "fingerprint",
503 }),
504 Effect.flip,
505 );
506 expect(failure._tag).toBe("GitHubCliCommandError");
507 expect(yield* encodeGitHubCliError(failure)).not.toContain("secret-credential");
508 }
509 expect(mockRun).not.toHaveBeenCalled();
510 }).pipe(Effect.provide(layer)),
511 );
512​
513 it.effect("pins repository-targeted writes on enterprise hosts", () =>
514 Effect.gen(function* () {
515 mockRun.mockReturnValue(Effect.succeed(processOutput("")));
516 const gh = yield* GitHubCli.GitHubCli;
517 yield* gh
518 .execute({
519 cwd: "/repo",
520 args: ["pr", "merge", "1", "--repo", "github.example.test/owner/repo"],
521 })
522 .pipe(
523 Effect.provideService(GitHubCli.PinnedGitHubCredential, {
524 host: "github.example.test",
525 token: Redacted.make("enterprise-credential"),
526 credentialFingerprint: "fingerprint",
527 }),
528 );
529 yield* gh
530 .execute({
531 cwd: "/repo",
532 args: ["repo", "view", "github.example.test/owner/repo", "--json", "name"],
533 })
534 .pipe(
535 Effect.provideService(GitHubCli.PinnedGitHubCredential, {
536 host: "github.example.test",
537 token: Redacted.make("enterprise-credential"),
538 credentialFingerprint: "fingerprint",
539 }),
540 );
541 expect(mockRun.mock.calls[0]?.[0].env).toMatchObject({
542 GH_HOST: "github.example.test",
543 GH_ENTERPRISE_TOKEN: "enterprise-credential",
544 GH_DEBUG: "",
545 });
546 }).pipe(Effect.provide(layer)),
547 );
548​
549 it("does not classify a missing cwd as an unavailable gh executable", () => {
550 const context = { command: "gh", cwd: "/repo" } as const;
551 const missingCwd = new VcsProcessSpawnError({
552 operation: "GitHubCli.execute",
553 command: "gh",
554 cwd: context.cwd,
555 cause: PlatformError.systemError({
556 _tag: "NotFound",
557 module: "FileSystem",
558 method: "access",
559 pathOrDescriptor: context.cwd,
560 }),
561 });
562​
563 const commandFailure = GitHubCli.fromVcsError(context, missingCwd);
564​
565 assert.equal(commandFailure._tag, "GitHubCliCommandError");
566 assert.strictEqual(commandFailure.cause, missingCwd);
567 assert.notProperty(commandFailure, "operation");
568 });
569​
570 it.effect("parses pull request view output", () =>
571 Effect.gen(function* () {
572 mockRun.mockReturnValueOnce(
573 Effect.succeed(
574 processOutput(
575 // @effect-diagnostics-next-line preferSchemaOverJson:off
576 JSON.stringify({
577 number: 42,
578 title: "Add PR thread creation",
579 url: "https://github.com/pingdotgg/codething-mvp/pull/42",
580 baseRefName: "main",
581 headRefName: "feature/pr-threads",
582 state: "OPEN",
583 isDraft: true,
584 mergedAt: null,
585 updatedAt: "2026-08-24T12:34:56Z",
586 isCrossRepository: true,
587 headRepository: {
588 nameWithOwner: "octocat/codething-mvp",
589 },
590 headRepositoryOwner: {
591 login: "octocat",
592 },
593 }),
594 ),
595 ),
596 );
597​
598 const gh = yield* GitHubCli.GitHubCli;
599 const result = yield* gh.getPullRequest({
600 cwd: "/repo",
601 reference: "#42",
602 });
603​
604 assert.deepStrictEqual(result, {
605 number: 42,
606 title: "Add PR thread creation",
607 url: "https://github.com/pingdotgg/codething-mvp/pull/42",
608 baseRefName: "main",
609 headRefName: "feature/pr-threads",
610 state: "open",
611 closedAt: null,
612 mergedAt: null,
613 isDraft: true,
614 updatedAt: "2026-08-24T12:34:56.000Z",
615 isCrossRepository: true,
616 headRepositoryNameWithOwner: "octocat/codething-mvp",
617 headRepositoryOwnerLogin: "octocat",
618 });
619 expect(mockRun).toHaveBeenCalledWith({
620 operation: "GitHubCli.execute",
621 command: "gh",
622 args: [
623 "pr",
624 "view",
625 "#42",
626 "--json",
627 "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
628 ],
629 cwd: "/repo",
630 timeoutMs: 30_000,
631 });
632 }).pipe(Effect.provide(layer)),
633 );
634​
635 it.effect("trims pull request fields decoded from gh json", () =>
636 Effect.gen(function* () {
637 mockRun.mockReturnValueOnce(
638 Effect.succeed(
639 processOutput(
640 // @effect-diagnostics-next-line preferSchemaOverJson:off
641 JSON.stringify({
642 number: 42,
643 title: " Add PR thread creation \n",
644 url: " https://github.com/pingdotgg/codething-mvp/pull/42 ",
645 baseRefName: " main ",
646 headRefName: "\tfeature/pr-threads\t",
647 state: "OPEN",
648 mergedAt: null,
649 isCrossRepository: true,
650 headRepository: {
651 nameWithOwner: " octocat/codething-mvp ",
652 },
653 headRepositoryOwner: {
654 login: " octocat ",
655 },
656 }),
657 ),
658 ),
659 );
660​
661 const gh = yield* GitHubCli.GitHubCli;
662 const result = yield* gh.getPullRequest({
663 cwd: "/repo",
664 reference: "#42",
665 });
666​
667 assert.deepStrictEqual(result, {
668 number: 42,
669 title: "Add PR thread creation",
670 url: "https://github.com/pingdotgg/codething-mvp/pull/42",
671 baseRefName: "main",
672 headRefName: "feature/pr-threads",
673 state: "open",
674 closedAt: null,
675 mergedAt: null,
676 isCrossRepository: true,
677 headRepositoryNameWithOwner: "octocat/codething-mvp",
678 headRepositoryOwnerLogin: "octocat",
679 });
680 }).pipe(Effect.provide(layer)),
681 );
682​
683 it.effect("skips invalid entries when parsing pr lists", () =>
684 Effect.gen(function* () {
685 mockRun.mockReturnValueOnce(
686 Effect.succeed(
687 processOutput(
688 // @effect-diagnostics-next-line preferSchemaOverJson:off
689 JSON.stringify([
690 {
691 number: 0,
692 title: "invalid",
693 url: "https://github.com/pingdotgg/codething-mvp/pull/0",
694 baseRefName: "main",
695 headRefName: "feature/invalid",
696 },
697 {
698 number: 43,
699 title: " Valid PR ",
700 url: " https://github.com/pingdotgg/codething-mvp/pull/43 ",
701 baseRefName: " main ",
702 headRefName: " feature/pr-list ",
703 headRepository: {
704 nameWithOwner: " ",
705 },
706 headRepositoryOwner: {
707 login: " ",
708 },
709 },
710 ]),
711 ),
712 ),
713 );
714​
715 const gh = yield* GitHubCli.GitHubCli;
716 const result = yield* gh.listOpenPullRequests({
717 cwd: "/repo",
718 headSelector: "feature/pr-list",
719 });
720​
721 assert.deepStrictEqual(result, [
722 {
723 number: 43,
724 title: "Valid PR",
725 url: "https://github.com/pingdotgg/codething-mvp/pull/43",
726 baseRefName: "main",
727 headRefName: "feature/pr-list",
728 state: "open",
729 closedAt: null,
730 mergedAt: null,
731 },
732 ]);
733 }).pipe(Effect.provide(layer)),
734 );
735​
736 it.effect("keeps pull requests from gh versions without headRepository.nameWithOwner", () =>
737 // gh < 2.47 (e.g. Ubuntu-packaged 2.46) exports headRepository as
738 // {id, name} only. These entries must decode instead of being dropped,
739 // with nameWithOwner rebuilt from the owner login.
740 Effect.gen(function* () {
741 mockRun.mockReturnValueOnce(
742 Effect.succeed(
743 processOutput(
744 // @effect-diagnostics-next-line preferSchemaOverJson:off
745 JSON.stringify([
746 {
747 number: 2829,
748 title: "Codex turn mapping",
749 url: "https://github.com/pingdotgg/codething-mvp/pull/2829",
750 baseRefName: "main",
751 headRefName: "t3code/codex-turn-mapping",
752 state: "OPEN",
753 mergedAt: null,
754 isCrossRepository: false,
755 headRepository: {
756 id: "R_kgDORLtfbQ",
757 name: "codething-mvp",
758 },
759 headRepositoryOwner: {
760 id: "MDEyOk9yZ2FuaXphdGlvbjg5MTkxNzI3",
761 login: "pingdotgg",
762 },
763 },
764 ]),
765 ),
766 ),
767 );
768​
769 const gh = yield* GitHubCli.GitHubCli;
770 const result = yield* gh.listOpenPullRequests({
771 cwd: "/repo",
772 headSelector: "t3code/codex-turn-mapping",
773 });
774​
775 assert.deepStrictEqual(result, [
776 {
777 number: 2829,
778 title: "Codex turn mapping",
779 url: "https://github.com/pingdotgg/codething-mvp/pull/2829",
780 baseRefName: "main",
781 headRefName: "t3code/codex-turn-mapping",
782 state: "open",
783 closedAt: null,
784 mergedAt: null,
785 isCrossRepository: false,
786 headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
787 headRepositoryOwnerLogin: "pingdotgg",
788 },
789 ]);
790 }).pipe(Effect.provide(layer)),
791 );
792​
793 it.effect("reads repository clone URLs", () =>
794 Effect.gen(function* () {
795 mockRun.mockReturnValueOnce(
796 Effect.succeed(
797 processOutput(
798 // @effect-diagnostics-next-line preferSchemaOverJson:off
799 JSON.stringify({
800 nameWithOwner: "octocat/codething-mvp",
801 url: "https://github.com/octocat/codething-mvp",
802 sshUrl: "git@github.com:octocat/codething-mvp.git",
803 }),
804 ),
805 ),
806 );
807​
808 const gh = yield* GitHubCli.GitHubCli;
809 const result = yield* gh.getRepositoryCloneUrls({
810 cwd: "/repo",
811 repository: "octocat/codething-mvp",
812 });
813​
814 assert.deepStrictEqual(result, {
815 nameWithOwner: "octocat/codething-mvp",
816 url: "https://github.com/octocat/codething-mvp",
817 sshUrl: "git@github.com:octocat/codething-mvp.git",
818 });
819 }).pipe(Effect.provide(layer)),
820 );
821​
822 it.effect("creates repositories and parses clone URLs from create output", () =>
823 Effect.gen(function* () {
824 mockRun.mockReturnValueOnce(
825 Effect.succeed(
826 processOutput(
827 "✓ Created repository octocat/codething-mvp on github.com\nhttps://github.com/octocat/codething-mvp\n",
828 ),
829 ),
830 );
831​
832 const gh = yield* GitHubCli.GitHubCli;
833 const result = yield* gh.createRepository({
834 cwd: "/repo",
835 repository: "octocat/codething-mvp",
836 visibility: "private",
837 });
838​
839 assert.deepStrictEqual(result, {
840 nameWithOwner: "octocat/codething-mvp",
841 url: "https://github.com/octocat/codething-mvp",
842 sshUrl: "git@github.com:octocat/codething-mvp.git",
843 });
844 expect(mockRun).toHaveBeenCalledTimes(1);
845 expect(mockRun).toHaveBeenNthCalledWith(1, {
846 operation: "GitHubCli.execute",
847 command: "gh",
848 args: ["repo", "create", "octocat/codething-mvp", "--private"],
849 cwd: "/repo",
850 timeoutMs: 30_000,
851 });
852 }).pipe(Effect.provide(layer)),
853 );
854​
855 it.effect("falls back to constructed URLs when create output omits a URL", () =>
856 Effect.gen(function* () {
857 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("")));
858​
859 const gh = yield* GitHubCli.GitHubCli;
860 const result = yield* gh.createRepository({
861 cwd: "/repo",
862 repository: "octocat/codething-mvp",
863 visibility: "private",
864 });
865​
866 assert.deepStrictEqual(result, {
867 nameWithOwner: "octocat/codething-mvp",
868 url: "https://github.com/octocat/codething-mvp",
869 sshUrl: "git@github.com:octocat/codething-mvp.git",
870 });
871 }).pipe(Effect.provide(layer)),
872 );
873​
874 it.effect("surfaces a friendly error when the pull request is not found", () =>
875 Effect.gen(function* () {
876 const cause = new VcsProcessExitError({
877 operation: "GitHubCli.execute",
878 command: "gh pr view",
879 cwd: "/repo",
880 exitCode: 1,
881 failureKind: "not-found",
882 detail:
883 "GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
884 });
885 mockRun.mockReturnValueOnce(Effect.fail(cause));
886​
887 const gh = yield* GitHubCli.GitHubCli;
888 const error = yield* gh
889 .getPullRequest({
890 cwd: "/repo",
891 reference: "4888",
892 })
893 .pipe(Effect.flip);
894​
895 assert.equal(error.message.includes("Pull request not found"), true);
896 assert.strictEqual(error._tag, "GitHubPullRequestNotFoundError");
897 assert.strictEqual(error.command, "gh");
898 assert.strictEqual(error.cwd, "/repo");
899 assert.strictEqual(error.cause, cause);
900 assert.equal(error.message.includes(cause.detail), false);
901 }).pipe(Effect.provide(layer)),
902 );
903​
904 it.effect("surfaces an actionable rate-limit error without exposing provider stderr", () =>
905 Effect.gen(function* () {
906 const cause = new VcsProcessExitError({
907 operation: "GitHubCli.execute",
908 command: "gh",
909 cwd: "/repo",
910 exitCode: 1,
911 failureKind: "rate-limited",
912 detail: "API rate limit exceeded.",
913 stderrLength: 82,
914 stderrTruncated: false,
915 });
916 mockRun.mockReturnValueOnce(Effect.fail(cause));
917​
918 const gh = yield* GitHubCli.GitHubCli;
919 const error = yield* gh
920 .listOpenPullRequests({
921 cwd: "/repo",
922 headSelector: "feature/rate-limited",
923 })
924 .pipe(Effect.flip);
925​
926 assert.strictEqual(error._tag, "GitHubCliRateLimitError");
927 assert.include(error.detail, "GitHub API rate limit exceeded");
928 assert.include(error.detail, "gh api rate_limit");
929 assert.strictEqual(error.cause, cause);
930 assert.notInclude(error.message, "user ID");
931 const paused = yield* gh
932 .execute({ cwd: "/other-repo", args: ["pr", "list"] })
933 .pipe(Effect.flip);
934 assert.strictEqual(paused._tag, "GitHubCliRateLimitError");
935 expect(mockRun).toHaveBeenCalledTimes(1);
936 yield* TestClock.adjust("30 seconds");
937 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("[]")));
938 yield* gh.execute({ cwd: "/other-repo", args: ["pr", "list"] });
939 expect(mockRun).toHaveBeenCalledTimes(2);
940 }).pipe(Effect.provide(layer)),
941 );
942});
943​
944it.effect("accepts conditional 304 responses and preserves HTTP errors and retry delays", () =>
945 Effect.gen(function* () {
946 const gh = yield* GitHubCli.GitHubCli;
947 const request = {
948 cwd: "/repo",
949 args: [
950 "api",
951 "repos/acme/web/pulls/1",
952 "--hostname",
953 "github.com",
954 "--include",
955 "-H",
956 'If-None-Match: "one"',
957 ],
958 acceptNotModified: true,
959 };
960 const respond = (status: number, headers = "") =>
961 mockRun.mockImplementation(() =>
962 Effect.succeed({
963 ...processOutput(`HTTP/2.0 ${status}\r\n${headers}\r\n`),
964 exitCode: ChildProcessSpawner.ExitCode(1),
965 }),
966 );
967 respond(304);
968 expect((yield* gh.execute(request)).stdout).toContain("304");
969 expect(mockRun.mock.calls[0]?.[0].allowNonZeroExit).toBe(true);
970 respond(401);
971 expect((yield* gh.execute(request).pipe(Effect.flip))._tag).toBe(
972 "GitHubCliAuthenticationError",
973 );
974 respond(403);
975 expect((yield* gh.execute(request).pipe(Effect.flip))._tag).toBe("GitHubCliCommandError");
976 for (const status of [403, 429]) {
977 respond(status, "Retry-After: 120\r\n");
978 expect(yield* gh.execute(request).pipe(Effect.flip)).toMatchObject({
979 _tag: "GitHubCliRateLimitError",
980 retryAt: (yield* Clock.currentTimeMillis) + 120_000,
981 });
982 }
983 respond(
984 403,
985 `X-RateLimit-Remaining: 0\r\nX-RateLimit-Reset: ${Math.floor((yield* Clock.currentTimeMillis) / 1_000) + 60}\r\n`,
986 );
987 expect(yield* gh.execute(request).pipe(Effect.flip)).toMatchObject({
988 _tag: "GitHubCliRateLimitError",
989 retryAt: (yield* Clock.currentTimeMillis) + 60_000,
990 });
991 respond(500);
992 expect(yield* gh.execute(request).pipe(Effect.flip)).toMatchObject({
993 _tag: "GitHubCliCommandError",
994 httpStatus: 500,
995 });
996 }).pipe(Effect.provide(layer)),
997);