Open History to see the last commit
1import { assert, it, afterEach, describe, expect, vi } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as PlatformError from "effect/PlatformError";
5import { ChildProcessSpawner } from "effect/unstable/process";
6import { ServerSettingsError, VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
7
8import * as ServerSettings from "../serverSettings.ts";
9import * as VcsProcess from "../vcs/VcsProcess.ts";
10import * as GitHubCli from "./GitHubCli.ts";
11
12const processOutput = (stdout: string): VcsProcess.VcsProcessOutput => ({
13 exitCode: ChildProcessSpawner.ExitCode(0),
14 stdout,
15 stderr: "",
16 stdoutTruncated: false,
17 stderrTruncated: false,
18});
19
20const mockRun = vi.fn<VcsProcess.VcsProcess["Service"]["run"]>();
21
22const layerWithSettings = (overrides: Parameters<typeof ServerSettings.layerTest>[0] = {}) =>
23 GitHubCli.layer.pipe(
24 Layer.provide(ServerSettings.layerTest(overrides)),
25 Layer.provide(
26 Layer.mock(VcsProcess.VcsProcess)({
27 run: mockRun,
28 }),
29 ),
30 );
31
32const layer = layerWithSettings();
33
34const originalGitHubToken = process.env.GITHUB_TOKEN;
35
36afterEach(() => {
37 if (originalGitHubToken === undefined) delete process.env.GITHUB_TOKEN;
38 else process.env.GITHUB_TOKEN = originalGitHubToken;
39 mockRun.mockReset();
40});
41
42describe("GitHubCli.layer", () => {
43 it.effect("uses the GitHub CLI active account when no selection is configured", () =>
44 Effect.gen(function* () {
45 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("ok")));
46 const gh = yield* GitHubCli.GitHubCli;
47
48 yield* gh.execute({
49 cwd: "/repo",
50 host: "github.com",
51 repositories: ["acme/widget"],
52 args: ["api", "user"],
53 });
54
55 expect(mockRun).toHaveBeenCalledTimes(1);
56 expect(mockRun.mock.calls[0]?.[0]).not.toHaveProperty("env");
57 }).pipe(Effect.provide(layer)),
58 );
59
60 it.effect("selects an environment-backed GitHub credential by token source", () => {
61 process.env.GITHUB_TOKEN = "environment-token";
62 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("ok")));
63 const selectedLayer = layerWithSettings({
64 githubAccountRouting: {
65 "github.com": {
66 defaultAccount: { login: "DominicVonk", tokenSource: "GITHUB_TOKEN" },
67 ownerOverrides: {},
68 },
69 },
70 });
71
72 return Effect.gen(function* () {
73 const gh = yield* GitHubCli.GitHubCli;
74 yield* gh.execute({
75 cwd: "/repo",
76 host: "github.com",
77 repositories: ["acme/widget"],
78 args: ["api", "user"],
79 });
80
81 expect(mockRun).toHaveBeenCalledWith({
82 operation: "GitHubCli.execute",
83 command: "gh",
84 args: ["api", "user"],
85 cwd: "/repo",
86 env: { GH_TOKEN: "environment-token" },
87 timeoutMs: 30_000,
88 });
89 }).pipe(Effect.provide(selectedLayer));
90 });
91
92 it.effect("selects a keyring credential for a GitHub owner override", () => {
93 mockRun
94 .mockReturnValueOnce(Effect.succeed(processOutput("keyring-token\n")))
95 .mockReturnValueOnce(Effect.succeed(processOutput("ok")));
96 const selectedLayer = layerWithSettings({
97 githubAccountRouting: {
98 "github.com": {
99 ownerOverrides: { acme: { login: "work-user", tokenSource: "keyring" } },
100 },
101 },
102 });
103
104 return Effect.gen(function* () {
105 const gh = yield* GitHubCli.GitHubCli;
106 yield* gh.execute({
107 cwd: "/repo",
108 host: "github.com",
109 repositories: ["acme/widget"],
110 args: ["api", "user"],
111 });
112
113 expect(mockRun).toHaveBeenNthCalledWith(1, {
114 operation: "GitHubCli.authToken",
115 command: "gh",
116 args: ["auth", "token", "--hostname", "github.com", "--user", "work-user"],
117 cwd: "/repo",
118 timeoutMs: 30_000,
119 });
120 expect(mockRun).toHaveBeenNthCalledWith(2, {
121 operation: "GitHubCli.execute",
122 command: "gh",
123 args: ["api", "user"],
124 cwd: "/repo",
125 env: { GH_TOKEN: "keyring-token" },
126 timeoutMs: 30_000,
127 });
128 }).pipe(Effect.provide(selectedLayer));
129 });
130
131 it.effect("reads keyring credentials again after token rotation", () => {
132 mockRun
133 .mockReturnValueOnce(Effect.succeed(processOutput("first-token\n")))
134 .mockReturnValueOnce(Effect.succeed(processOutput("ok")))
135 .mockReturnValueOnce(Effect.succeed(processOutput("rotated-token\n")))
136 .mockReturnValueOnce(Effect.succeed(processOutput("ok")));
137 const selectedLayer = layerWithSettings({
138 githubAccountRouting: {
139 "github.com": {
140 defaultAccount: { login: "work-user", tokenSource: "keyring" },
141 ownerOverrides: {},
142 },
143 },
144 });
145
146 return Effect.gen(function* () {
147 const gh = yield* GitHubCli.GitHubCli;
148 const input = {
149 cwd: "/repo",
150 host: "github.com",
151 repositories: ["acme/widget"],
152 args: ["api", "user"],
153 } as const;
154
155 yield* gh.execute(input);
156 yield* gh.execute(input);
157
158 expect(mockRun).toHaveBeenNthCalledWith(2, {
159 operation: "GitHubCli.execute",
160 command: "gh",
161 args: ["api", "user"],
162 cwd: "/repo",
163 env: { GH_TOKEN: "first-token" },
164 timeoutMs: 30_000,
165 });
166 expect(mockRun).toHaveBeenNthCalledWith(4, {
167 operation: "GitHubCli.execute",
168 command: "gh",
169 args: ["api", "user"],
170 cwd: "/repo",
171 env: { GH_TOKEN: "rotated-token" },
172 timeoutMs: 30_000,
173 });
174 }).pipe(Effect.provide(selectedLayer));
175 });
176
177 it.effect("preserves missing-tool classification while reading a keyring token", () => {
178 const cause = new VcsProcessSpawnError({
179 operation: "GitHubCli.authToken",
180 command: "gh",
181 cwd: "/repo",
182 cause: PlatformError.systemError({
183 _tag: "NotFound",
184 module: "ChildProcess",
185 method: "spawn",
186 description: "gh missing",
187 }),
188 });
189 mockRun.mockReturnValueOnce(Effect.fail(cause));
190 const selectedLayer = layerWithSettings({
191 githubAccountRouting: {
192 "github.com": {
193 defaultAccount: { login: "work-user", tokenSource: "keyring" },
194 ownerOverrides: {},
195 },
196 },
197 });
198
199 return Effect.gen(function* () {
200 const gh = yield* GitHubCli.GitHubCli;
201 const error = yield* gh
202 .execute({
203 cwd: "/repo",
204 host: "github.com",
205 repositories: ["acme/widget"],
206 args: ["api", "user"],
207 })
208 .pipe(Effect.flip);
209
210 assert.equal(error._tag, "GitHubCliUnavailableError");
211 assert.strictEqual(error.cause, cause);
212 }).pipe(Effect.provide(selectedLayer));
213 });
214
215 it.effect("normalizes host casing before selecting the token environment variable", () => {
216 process.env.GITHUB_TOKEN = "environment-token";
217 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("ok")));
218 const selectedLayer = layerWithSettings({
219 githubAccountRouting: {
220 "github.com": {
221 defaultAccount: { login: "work-user", tokenSource: "GITHUB_TOKEN" },
222 ownerOverrides: {},
223 },
224 },
225 });
226
227 return Effect.gen(function* () {
228 const gh = yield* GitHubCli.GitHubCli;
229 yield* gh.execute({
230 cwd: "/repo",
231 host: "GitHub.com",
232 repositories: ["acme/widget"],
233 args: ["api", "user"],
234 });
235
236 expect(mockRun).toHaveBeenCalledWith({
237 operation: "GitHubCli.execute",
238 command: "gh",
239 args: ["api", "user"],
240 cwd: "/repo",
241 env: { GH_TOKEN: "environment-token" },
242 timeoutMs: 30_000,
243 });
244 }).pipe(Effect.provide(selectedLayer));
245 });
246
247 it.effect("reports unavailable token sources structurally", () => {
248 delete process.env.GITHUB_TOKEN;
249 const selectedLayer = layerWithSettings({
250 githubAccountRouting: {
251 "github.com": {
252 defaultAccount: { login: "environment-user", tokenSource: "GITHUB_TOKEN" },
253 ownerOverrides: {},
254 },
255 },
256 });
257
258 return Effect.gen(function* () {
259 const gh = yield* GitHubCli.GitHubCli;
260 const error = yield* gh
261 .execute({
262 cwd: "/repo",
263 host: "github.com",
264 repositories: ["acme/widget"],
265 args: ["api", "user"],
266 })
267 .pipe(Effect.flip);
268
269 assert.equal(error._tag, "GitHubTokenEnvironmentUnavailableError");
270 if (error._tag !== "GitHubTokenEnvironmentUnavailableError") return;
271 assert.equal(error.tokenSource, "GITHUB_TOKEN");
272 }).pipe(Effect.provide(selectedLayer));
273 });
274
275 it.effect("reports empty keyring token output structurally", () => {
276 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("\n")));
277 const selectedLayer = layerWithSettings({
278 githubAccountRouting: {
279 "github.com": {
280 defaultAccount: { login: "work-user", tokenSource: "keyring" },
281 ownerOverrides: {},
282 },
283 },
284 });
285
286 return Effect.gen(function* () {
287 const gh = yield* GitHubCli.GitHubCli;
288 const error = yield* gh
289 .execute({
290 cwd: "/repo",
291 host: "github.com",
292 repositories: ["acme/widget"],
293 args: ["api", "user"],
294 })
295 .pipe(Effect.flip);
296
297 assert.equal(error._tag, "GitHubTokenOutputEmptyError");
298 if (error._tag !== "GitHubTokenOutputEmptyError") return;
299 assert.equal(error.login, "work-user");
300 }).pipe(Effect.provide(selectedLayer));
301 });
302
303 it.effect("reports settings read failures at the account-selection stage", () => {
304 const cause = new ServerSettingsError({
305 settingsPath: "/settings.json",
306 operation: "read-file",
307 cause: new Error("unavailable"),
308 });
309 const selectedLayer = GitHubCli.layer.pipe(
310 Layer.provide(
311 Layer.mock(ServerSettings.ServerSettingsService)({
312 getSettings: Effect.fail(cause),
313 }),
314 ),
315 Layer.provide(
316 Layer.mock(VcsProcess.VcsProcess)({
317 run: mockRun,
318 }),
319 ),
320 );
321
322 return Effect.gen(function* () {
323 const gh = yield* GitHubCli.GitHubCli;
324 const error = yield* gh
325 .getBatchKey({
326 cwd: "/repo",
327 host: "github.com",
328 repositories: ["acme/widget"],
329 })
330 .pipe(Effect.flip);
331
332 assert.equal(error._tag, "GitHubAccountSettingsUnavailableError");
333 if (error._tag !== "GitHubAccountSettingsUnavailableError") return;
334 assert.equal(error.host, "github.com");
335 assert.strictEqual(error.cause, cause);
336 }).pipe(Effect.provide(selectedLayer));
337 });
338
339 it("does not classify a missing cwd as an unavailable gh executable", () => {
340 const context = { command: "gh", cwd: "/repo" } as const;
341 const missingCwd = new VcsProcessSpawnError({
342 operation: "GitHubCli.execute",
343 command: "gh",
344 cwd: context.cwd,
345 cause: PlatformError.systemError({
346 _tag: "NotFound",
347 module: "FileSystem",
348 method: "access",
349 pathOrDescriptor: context.cwd,
350 }),
351 });
352
353 const commandFailure = GitHubCli.fromVcsError(context, missingCwd);
354
355 assert.equal(commandFailure._tag, "GitHubCliCommandError");
356 assert.strictEqual(commandFailure.cause, missingCwd);
357 assert.notProperty(commandFailure, "operation");
358 });
359
360 it.effect("parses pull request view output", () =>
361 Effect.gen(function* () {
362 mockRun.mockReturnValueOnce(
363 Effect.succeed(
364 processOutput(
365 // @effect-diagnostics-next-line preferSchemaOverJson:off
366 JSON.stringify({
367 number: 42,
368 title: "Add PR thread creation",
369 url: "https://github.com/pingdotgg/codething-mvp/pull/42",
370 baseRefName: "main",
371 headRefName: "feature/pr-threads",
372 state: "OPEN",
373 mergedAt: null,
374 isCrossRepository: true,
375 headRepository: {
376 nameWithOwner: "octocat/codething-mvp",
377 },
378 headRepositoryOwner: {
379 login: "octocat",
380 },
381 }),
382 ),
383 ),
384 );
385
386 const gh = yield* GitHubCli.GitHubCli;
387 const result = yield* gh.getPullRequest({
388 cwd: "/repo",
389 reference: "#42",
390 });
391
392 assert.deepStrictEqual(result, {
393 number: 42,
394 title: "Add PR thread creation",
395 url: "https://github.com/pingdotgg/codething-mvp/pull/42",
396 baseRefName: "main",
397 headRefName: "feature/pr-threads",
398 state: "open",
399 isCrossRepository: true,
400 headRepositoryNameWithOwner: "octocat/codething-mvp",
401 headRepositoryOwnerLogin: "octocat",
402 });
403 expect(mockRun).toHaveBeenCalledWith({
404 operation: "GitHubCli.execute",
405 command: "gh",
406 args: [
407 "pr",
408 "view",
409 "#42",
410 "--json",
411 "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
412 ],
413 cwd: "/repo",
414 timeoutMs: 30_000,
415 });
416 }).pipe(Effect.provide(layer)),
417 );
418
419 it.effect("trims pull request fields decoded from gh json", () =>
420 Effect.gen(function* () {
421 mockRun.mockReturnValueOnce(
422 Effect.succeed(
423 processOutput(
424 // @effect-diagnostics-next-line preferSchemaOverJson:off
425 JSON.stringify({
426 number: 42,
427 title: " Add PR thread creation \n",
428 url: " https://github.com/pingdotgg/codething-mvp/pull/42 ",
429 baseRefName: " main ",
430 headRefName: "\tfeature/pr-threads\t",
431 state: "OPEN",
432 mergedAt: null,
433 isCrossRepository: true,
434 headRepository: {
435 nameWithOwner: " octocat/codething-mvp ",
436 },
437 headRepositoryOwner: {
438 login: " octocat ",
439 },
440 }),
441 ),
442 ),
443 );
444
445 const gh = yield* GitHubCli.GitHubCli;
446 const result = yield* gh.getPullRequest({
447 cwd: "/repo",
448 reference: "#42",
449 });
450
451 assert.deepStrictEqual(result, {
452 number: 42,
453 title: "Add PR thread creation",
454 url: "https://github.com/pingdotgg/codething-mvp/pull/42",
455 baseRefName: "main",
456 headRefName: "feature/pr-threads",
457 state: "open",
458 isCrossRepository: true,
459 headRepositoryNameWithOwner: "octocat/codething-mvp",
460 headRepositoryOwnerLogin: "octocat",
461 });
462 }).pipe(Effect.provide(layer)),
463 );
464
465 it.effect("skips invalid entries when parsing pr lists", () =>
466 Effect.gen(function* () {
467 mockRun.mockReturnValueOnce(
468 Effect.succeed(
469 processOutput(
470 // @effect-diagnostics-next-line preferSchemaOverJson:off
471 JSON.stringify([
472 {
473 number: 0,
474 title: "invalid",
475 url: "https://github.com/pingdotgg/codething-mvp/pull/0",
476 baseRefName: "main",
477 headRefName: "feature/invalid",
478 },
479 {
480 number: 43,
481 title: " Valid PR ",
482 url: " https://github.com/pingdotgg/codething-mvp/pull/43 ",
483 baseRefName: " main ",
484 headRefName: " feature/pr-list ",
485 headRepository: {
486 nameWithOwner: " ",
487 },
488 headRepositoryOwner: {
489 login: " ",
490 },
491 },
492 ]),
493 ),
494 ),
495 );
496
497 const gh = yield* GitHubCli.GitHubCli;
498 const result = yield* gh.listOpenPullRequests({
499 cwd: "/repo",
500 headSelector: "feature/pr-list",
501 });
502
503 assert.deepStrictEqual(result, [
504 {
505 number: 43,
506 title: "Valid PR",
507 url: "https://github.com/pingdotgg/codething-mvp/pull/43",
508 baseRefName: "main",
509 headRefName: "feature/pr-list",
510 state: "open",
511 },
512 ]);
513 }).pipe(Effect.provide(layer)),
514 );
515
516 it.effect("keeps pull requests from gh versions without headRepository.nameWithOwner", () =>
517 // gh < 2.47 (e.g. Ubuntu-packaged 2.46) exports headRepository as
518 // {id, name} only. These entries must decode instead of being dropped,
519 // with nameWithOwner rebuilt from the owner login.
520 Effect.gen(function* () {
521 mockRun.mockReturnValueOnce(
522 Effect.succeed(
523 processOutput(
524 // @effect-diagnostics-next-line preferSchemaOverJson:off
525 JSON.stringify([
526 {
527 number: 2829,
528 title: "Codex turn mapping",
529 url: "https://github.com/pingdotgg/codething-mvp/pull/2829",
530 baseRefName: "main",
531 headRefName: "t3code/codex-turn-mapping",
532 state: "OPEN",
533 mergedAt: null,
534 isCrossRepository: false,
535 headRepository: {
536 id: "R_kgDORLtfbQ",
537 name: "codething-mvp",
538 },
539 headRepositoryOwner: {
540 id: "MDEyOk9yZ2FuaXphdGlvbjg5MTkxNzI3",
541 login: "pingdotgg",
542 },
543 },
544 ]),
545 ),
546 ),
547 );
548
549 const gh = yield* GitHubCli.GitHubCli;
550 const result = yield* gh.listOpenPullRequests({
551 cwd: "/repo",
552 headSelector: "t3code/codex-turn-mapping",
553 });
554
555 assert.deepStrictEqual(result, [
556 {
557 number: 2829,
558 title: "Codex turn mapping",
559 url: "https://github.com/pingdotgg/codething-mvp/pull/2829",
560 baseRefName: "main",
561 headRefName: "t3code/codex-turn-mapping",
562 state: "open",
563 isCrossRepository: false,
564 headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
565 headRepositoryOwnerLogin: "pingdotgg",
566 },
567 ]);
568 }).pipe(Effect.provide(layer)),
569 );
570
571 it.effect("reads repository clone URLs", () =>
572 Effect.gen(function* () {
573 mockRun.mockReturnValueOnce(
574 Effect.succeed(
575 processOutput(
576 // @effect-diagnostics-next-line preferSchemaOverJson:off
577 JSON.stringify({
578 nameWithOwner: "octocat/codething-mvp",
579 url: "https://github.com/octocat/codething-mvp",
580 sshUrl: "git@github.com:octocat/codething-mvp.git",
581 }),
582 ),
583 ),
584 );
585
586 const gh = yield* GitHubCli.GitHubCli;
587 const result = yield* gh.getRepositoryCloneUrls({
588 cwd: "/repo",
589 repository: "octocat/codething-mvp",
590 });
591
592 assert.deepStrictEqual(result, {
593 nameWithOwner: "octocat/codething-mvp",
594 url: "https://github.com/octocat/codething-mvp",
595 sshUrl: "git@github.com:octocat/codething-mvp.git",
596 });
597 }).pipe(Effect.provide(layer)),
598 );
599
600 it.effect("creates repositories and parses clone URLs from create output", () =>
601 Effect.gen(function* () {
602 mockRun.mockReturnValueOnce(
603 Effect.succeed(
604 processOutput(
605 "✓ Created repository octocat/codething-mvp on github.com\nhttps://github.com/octocat/codething-mvp\n",
606 ),
607 ),
608 );
609
610 const gh = yield* GitHubCli.GitHubCli;
611 const result = yield* gh.createRepository({
612 cwd: "/repo",
613 repository: "octocat/codething-mvp",
614 visibility: "private",
615 });
616
617 assert.deepStrictEqual(result, {
618 nameWithOwner: "octocat/codething-mvp",
619 url: "https://github.com/octocat/codething-mvp",
620 sshUrl: "git@github.com:octocat/codething-mvp.git",
621 });
622 expect(mockRun).toHaveBeenCalledTimes(1);
623 expect(mockRun).toHaveBeenNthCalledWith(1, {
624 operation: "GitHubCli.execute",
625 command: "gh",
626 args: ["repo", "create", "octocat/codething-mvp", "--private"],
627 cwd: "/repo",
628 timeoutMs: 30_000,
629 });
630 }).pipe(Effect.provide(layer)),
631 );
632
633 it.effect("falls back to constructed URLs when create output omits a URL", () =>
634 Effect.gen(function* () {
635 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("")));
636
637 const gh = yield* GitHubCli.GitHubCli;
638 const result = yield* gh.createRepository({
639 cwd: "/repo",
640 repository: "octocat/codething-mvp",
641 visibility: "private",
642 });
643
644 assert.deepStrictEqual(result, {
645 nameWithOwner: "octocat/codething-mvp",
646 url: "https://github.com/octocat/codething-mvp",
647 sshUrl: "git@github.com:octocat/codething-mvp.git",
648 });
649 }).pipe(Effect.provide(layer)),
650 );
651
652 it.effect("surfaces a friendly error when the pull request is not found", () =>
653 Effect.gen(function* () {
654 const cause = new VcsProcessExitError({
655 operation: "GitHubCli.execute",
656 command: "gh pr view",
657 cwd: "/repo",
658 exitCode: 1,
659 failureKind: "not-found",
660 detail:
661 "GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
662 });
663 mockRun.mockReturnValueOnce(Effect.fail(cause));
664
665 const gh = yield* GitHubCli.GitHubCli;
666 const error = yield* gh
667 .getPullRequest({
668 cwd: "/repo",
669 reference: "4888",
670 })
671 .pipe(Effect.flip);
672
673 assert.equal(error.message.includes("Pull request not found"), true);
674 assert.strictEqual(error._tag, "GitHubPullRequestNotFoundError");
675 assert.strictEqual(error.command, "gh");
676 assert.strictEqual(error.cwd, "/repo");
677 assert.strictEqual(error.cause, cause);
678 assert.equal(error.message.includes(cause.detail), false);
679 }).pipe(Effect.provide(layer)),
680 );
681});