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

GitHubSourceControlProvider.test.ts

1,028 lines30.5 KB

1import { afterEach, assert, describe, expect, it, vi } from "@effect/vitest";
2import * as DateTime from "effect/DateTime";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import { ChildProcessSpawner } from "effect/unstable/process";
7​
8import * as VcsProcess from "../vcs/VcsProcess.ts";
9import * as GitHubCli from "./GitHubCli.ts";
10import { parseGitHubAuthStatus } from "./gitHubAuthStatus.ts";
11import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
12​
13const processResult = (
14 stdout: string,
15 options?: {
16 readonly stderr?: string;
17 readonly exitCode?: ChildProcessSpawner.ExitCode;
18 },
19): VcsProcess.VcsProcessOutput => ({
20 exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0),
21 stdout,
22 stderr: options?.stderr ?? "",
23 stdoutTruncated: false,
24 stderrTruncated: false,
25});
26​
27function makeProvider(github: Partial<GitHubCli.GitHubCli["Service"]>) {
28 return GitHubSourceControlProvider.make.pipe(
29 Effect.provide(Layer.mock(GitHubCli.GitHubCli)(github)),
30 );
32​
33const mockRun = vi.fn<VcsProcess.VcsProcess["Service"]["run"]>();
34​
35const cliLayer = GitHubCli.layer.pipe(
36 Layer.provide(
37 Layer.mock(VcsProcess.VcsProcess)({
38 run: mockRun,
39 }),
40 ),
41);
42​
43afterEach(() => {
44 mockRun.mockReset();
45});
46​
47it.effect("maps GitHub PR summaries into provider-neutral change requests", () =>
48 Effect.gen(function* () {
49 const provider = yield* makeProvider({
50 getPullRequest: () =>
51 Effect.succeed({
52 number: 42,
53 title: "Add GitHub provider",
54 url: "https://github.com/pingdotgg/t3code/pull/42",
55 baseRefName: "main",
56 headRefName: "feature/source-control",
57 state: "open",
58 isCrossRepository: true,
59 headRepositoryNameWithOwner: "fork/t3code",
60 headRepositoryOwnerLogin: "fork",
61 }),
62 });
63​
64 const changeRequest = yield* provider.getChangeRequest({
65 cwd: "/repo",
66 reference: "42",
67 });
68​
69 assert.deepStrictEqual(changeRequest, {
70 provider: "github",
71 number: 42,
72 title: "Add GitHub provider",
73 url: "https://github.com/pingdotgg/t3code/pull/42",
74 baseRefName: "main",
75 headRefName: "feature/source-control",
76 state: "open",
77 closedAt: null,
78 mergedAt: null,
79 updatedAt: Option.none(),
80 isCrossRepository: true,
81 headRepositoryNameWithOwner: "fork/t3code",
82 headRepositoryOwnerLogin: "fork",
83 });
84 }),
85);
86​
87it.effect("adds safe request context while retaining GitHub CLI causes", () =>
88 Effect.gen(function* () {
89 const cause = new GitHubCli.GitHubPullRequestNotFoundError({
90 command: "gh",
91 cwd: "/repo",
92 cause: new Error("raw upstream detail that should remain in the cause"),
93 });
94 const provider = yield* makeProvider({
95 getPullRequest: () => Effect.fail(cause),
96 });
97​
98 const error = yield* provider
99 .getChangeRequest({
100 cwd: "/repo",
101 reference: "https://user:secret@github.com/pingdotgg/t3code/pull/42?token=secret#diff",
102 })
103 .pipe(Effect.flip);
104​
105 assert.deepStrictEqual(
106 {
107 provider: error.provider,
108 operation: error.operation,
109 command: error.command,
110 cwd: error.cwd,
111 reference: error.reference,
112 detail: error.detail,
113 },
114 {
115 provider: "github",
116 operation: "getChangeRequest",
117 command: "gh",
118 cwd: "/repo",
119 reference: "https://github.com/pingdotgg/t3code/pull/42",
120 detail: "Pull request not found. Check the PR number or URL and try again.",
121 },
122 );
123 assert.strictEqual(error.cause, cause);
124 assert.equal(error.message.includes("raw upstream detail"), false);
125 }),
126);
127​
128it.effect("uses gh json listing for non-open change request state queries", () =>
129 Effect.gen(function* () {
130 let executeArgs: ReadonlyArray<string> = [];
131 const provider = yield* makeProvider({
132 execute: (input) => {
133 executeArgs = input.args;
134 return Effect.succeed(
135 processResult(
136 JSON.stringify([
137 {
138 number: 7,
139 title: "Merged work",
140 url: "https://github.com/pingdotgg/t3code/pull/7",
141 baseRefName: "main",
142 headRefName: "feature/merged",
143 state: "merged",
144 mergedAt: "2026-01-01T00:00:00Z",
145 updatedAt: "2026-01-02T00:00:00.000Z",
146 },
147 ]),
148 ),
149 );
150 },
151 });
152​
153 const changeRequests = yield* provider.listChangeRequests({
154 cwd: "/repo",
155 headSelector: "feature/merged",
156 state: "all",
157 limit: 10,
158 });
159​
160 assert.deepStrictEqual(executeArgs, [
161 "pr",
162 "list",
163 "--head",
164 "feature/merged",
165 "--state",
166 "all",
167 "--limit",
168 "10",
169 "--json",
170 "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
171 ]);
172 assert.strictEqual(changeRequests[0]?.provider, "github");
173 assert.strictEqual(changeRequests[0]?.state, "merged");
174 assert.strictEqual(changeRequests[0]?.mergedAt, "2026-01-01T00:00:00Z");
175 assert.deepStrictEqual(
176 changeRequests[0]?.updatedAt,
177 Option.some(DateTime.makeUnsafe("2026-01-02T00:00:00.000Z")),
178 );
179 }),
180);
181​
182it.effect("treats empty non-open change request listing output as no results", () =>
183 Effect.gen(function* () {
184 const provider = yield* makeProvider({
185 execute: () => Effect.succeed(processResult("")),
186 });
187​
188 const changeRequests = yield* provider.listChangeRequests({
189 cwd: "/repo",
190 headSelector: "feature/empty",
191 state: "all",
192 limit: 10,
193 });
194​
195 assert.deepStrictEqual(changeRequests, []);
196 }),
197);
198​
199it.effect("creates GitHub PRs through provider-neutral input names", () =>
200 Effect.gen(function* () {
201 let createInput: Parameters<GitHubCli.GitHubCli["Service"]["createPullRequest"]>[0] | null =
202 null;
203 const provider = yield* makeProvider({
204 createPullRequest: (input) => {
205 createInput = input;
206 return Effect.void;
207 },
208 });
209​
210 yield* provider.createChangeRequest({
211 cwd: "/repo",
212 baseRefName: "main",
213 headSelector: "owner:feature/provider",
214 title: "Provider PR",
215 bodyFile: "/tmp/body.md",
216 });
217​
218 assert.deepStrictEqual(createInput, {
219 cwd: "/repo",
220 baseBranch: "main",
221 headSelector: "owner:feature/provider",
222 title: "Provider PR",
223 bodyFile: "/tmp/body.md",
224 });
225 }),
226);
227​
228it("accepts active authenticated GitHub accounts when another account fails", () => {
229 const auth = GitHubSourceControlProvider.discovery.parseAuth(
230 processResult(
231 JSON.stringify({
232 hosts: {
233 "github.com": [
234 {
235 state: "success",
236 active: true,
237 host: "github.com",
238 login: "active-user",
239 tokenSource: "keyring",
240 gitProtocol: "ssh",
241 },
242 {
243 state: "error",
244 active: false,
245 host: "github.com",
246 login: "stale-user",
247 tokenSource: "keyring",
248 gitProtocol: "ssh",
249 error: "The token in keyring is invalid.",
250 },
251 ],
252 },
253 }),
254 ),
255 );
256​
257 assert.deepStrictEqual(
258 {
259 status: auth.status,
260 account: auth.account,
261 host: auth.host,
262 },
263 {
264 status: "authenticated",
265 account: Option.some("active-user"),
266 host: Option.some("github.com"),
267 },
268 );
269});
270​
271it("parses GitHub auth JSON from stdout when stderr has warnings", () => {
272 const auth = GitHubSourceControlProvider.discovery.parseAuth(
273 processResult(
274 JSON.stringify({
275 hosts: {
276 "github.com": [
277 {
278 state: "success",
279 active: true,
280 host: "github.com",
281 login: "active-user",
282 tokenSource: "keyring",
283 gitProtocol: "ssh",
284 },
285 ],
286 },
287 }),
288 { stderr: "warning: ignored diagnostic from gh\n" },
289 ),
290 );
291​
292 assert.deepStrictEqual(
293 {
294 status: auth.status,
295 account: auth.account,
296 host: auth.host,
297 },
298 {
299 status: "authenticated",
300 account: Option.some("active-user"),
301 host: Option.some("github.com"),
302 },
303 );
304});
305​
306it("parses GitHub auth status accounts by host and active state", () => {
307 assert.deepStrictEqual(
308 parseGitHubAuthStatus(
309 JSON.stringify({
310 hosts: {
311 "github.com": [
312 {
313 state: "success",
314 active: true,
315 host: "github.com",
316 login: "active-user",
317 tokenSource: "keyring",
318 gitProtocol: "ssh",
319 },
320 {
321 state: "error",
322 active: false,
323 host: "github.com",
324 login: "stale-user",
325 tokenSource: "keyring",
326 gitProtocol: "ssh",
327 },
328 ],
329 "github.example.test": [
330 {
331 state: "success",
332 active: false,
333 host: "github.example.test",
334 login: "enterprise-user",
335 tokenSource: "keyring",
336 gitProtocol: "ssh",
337 },
338 ],
339 },
340 }),
341 ).accounts,
342 [
343 {
344 host: "github.com",
345 account: "active-user",
346 authenticated: true,
347 active: true,
348 error: null,
349 },
350 {
351 host: "github.com",
352 account: "stale-user",
353 authenticated: false,
354 active: false,
355 error: null,
356 },
357 {
358 host: "github.example.test",
359 account: "enterprise-user",
360 authenticated: true,
361 active: false,
362 error: null,
363 },
364 ],
365 );
366});
367​
368it("reports unauthenticated when GitHub JSON has accounts but none are valid", () => {
369 const auth = GitHubSourceControlProvider.discovery.parseAuth(
370 processResult(
371 JSON.stringify({
372 hosts: {
373 "github.com": [
374 {
375 state: "error",
376 active: true,
377 host: "github.com",
378 login: "stale-user",
379 tokenSource: "keyring",
380 gitProtocol: "ssh",
381 error: "The token in keyring is invalid.",
382 },
383 ],
384 },
385 }),
386 ),
387 );
388​
389 assert.deepStrictEqual(
390 {
391 status: auth.status,
392 host: auth.host,
393 detail: auth.detail,
394 },
395 {
396 status: "unauthenticated",
397 host: Option.some("github.com"),
398 detail: Option.some("The token in keyring is invalid."),
399 },
400 );
401});
402​
403const authStatusJson = (
404 hosts: Record<string, ReadonlyArray<{ login: string; state: string; active: boolean }>>,
405) =>
406 JSON.stringify({
407 hosts: Object.fromEntries(
408 Object.entries(hosts).map(([host, accounts]) => [
409 host,
410 accounts.map((account) => ({ ...account, host })),
411 ]),
412 ),
413 });
414​
415const probe = (stdout: string) => ({
416 stdout,
417 stderr: "",
418 exitCode: ChildProcessSpawner.ExitCode(0),
419});
420​
421describe("expandGitHubInstances", () => {
422 it("emits only a github row when no enterprise host is logged in", () => {
423 const instances = GitHubSourceControlProvider.expandGitHubInstances(
424 probe(
425 authStatusJson({ "github.com": [{ login: "octocat", state: "success", active: true }] }),
426 ),
427 );
428​
429 expect(instances.map((instance) => instance.id)).toEqual(["github"]);
430 expect(instances[0]!.kind).toBe("github");
431 expect(instances[0]!.auth.status).toBe("authenticated");
432 });
433​
434 it("emits one enterprise row per non-github.com host", () => {
435 const instances = GitHubSourceControlProvider.expandGitHubInstances(
436 probe(
437 authStatusJson({
438 "github.com": [{ login: "octocat", state: "success", active: true }],
439 "git.corp.com": [{ login: "dev", state: "success", active: false }],
440 "acme.ghe.com": [{ login: "dev2", state: "success", active: false }],
441 }),
442 ),
443 );
444​
445 expect(instances.map((instance) => instance.id)).toEqual([
446 "github",
447 "github-enterprise:acme.ghe.com",
448 "github-enterprise:git.corp.com",
449 ]);
450 expect(instances[1]!.kind).toBe("github-enterprise");
451 expect(instances[1]!.label).toBe("acme.ghe.com");
452 expect(instances[1]!.host).toBe("acme.ghe.com");
453 expect(Option.getOrNull(instances[1]!.auth.account)).toBe("dev2");
454 });
455​
456 it("collapses two authenticated accounts on the same enterprise host into one row", () => {
457 const instances = GitHubSourceControlProvider.expandGitHubInstances(
458 probe(
459 authStatusJson({
460 "github.com": [{ login: "octocat", state: "success", active: true }],
461 "git.corp.com": [
462 { login: "dev", state: "success", active: true },
463 { login: "dev2", state: "success", active: false },
464 ],
465 }),
466 ),
467 );
468​
469 expect(instances.map((instance) => instance.id)).toEqual([
470 "github",
471 "github-enterprise:git.corp.com",
472 ]);
473 expect(instances).toHaveLength(2);
474 });
475​
476 it("still emits a github row when github.com is not logged in", () => {
477 const instances = GitHubSourceControlProvider.expandGitHubInstances(
478 probe(authStatusJson({ "git.corp.com": [{ login: "dev", state: "success", active: true }] })),
479 );
480​
481 expect(instances[0]!.id).toBe("github");
482 expect(instances[0]!.auth.status).toBe("unauthenticated");
483 expect(instances).toHaveLength(2);
484 });
485​
486 it("emits only a github row with unknown auth when output is unparseable", () => {
487 const instances = GitHubSourceControlProvider.expandGitHubInstances(probe("not json"));
488​
489 expect(instances).toHaveLength(1);
490 expect(instances[0]!.id).toBe("github");
491 expect(instances[0]!.kind).toBe("github");
492 expect(instances[0]!.host).toBe("github.com");
493 expect(instances[0]!.auth.status).toBe("unknown");
494 });
495});
496​
497describe("refineUnknownGitHubRemote", () => {
498 const context = {
499 provider: { kind: "unknown" as const, name: "git.corp.com", baseUrl: "https://git.corp.com" },
500 remoteName: "origin",
501 remoteUrl: "https://git.corp.com/owner/repo.git",
502 };
503​
504 it("claims a remote whose host is authenticated in gh", () => {
505 const refined = GitHubSourceControlProvider.refineUnknownGitHubRemote({
506 cwd: "/repo",
507 context,
508 auth: probe(
509 authStatusJson({ "git.corp.com": [{ login: "dev", state: "success", active: true }] }),
510 ),
511 });
512​
513 expect(refined).toEqual({
514 kind: "github-enterprise",
515 name: "git.corp.com",
516 baseUrl: "https://git.corp.com",
517 });
518 });
519​
520 it("claims a remote whose host carries a non-default port", () => {
521 const refined = GitHubSourceControlProvider.refineUnknownGitHubRemote({
522 cwd: "/repo",
523 context: {
524 provider: {
525 kind: "unknown" as const,
526 name: "git.corp.com:8443",
527 baseUrl: "https://git.corp.com:8443",
528 },
529 remoteName: "origin",
530 remoteUrl: "https://git.corp.com:8443/owner/repo.git",
531 },
532 auth: probe(
533 authStatusJson({ "git.corp.com": [{ login: "dev", state: "success", active: true }] }),
534 ),
535 });
536​
537 expect(refined).toEqual({
538 kind: "github-enterprise",
539 name: "git.corp.com",
540 baseUrl: "https://git.corp.com:8443",
541 });
542 });
543​
544 it("does not claim a host that failed authentication", () => {
545 expect(
546 GitHubSourceControlProvider.refineUnknownGitHubRemote({
547 cwd: "/repo",
548 context,
549 auth: probe(
550 authStatusJson({ "git.corp.com": [{ login: "dev", state: "error", active: true }] }),
551 ),
552 }),
553 ).toBeNull();
554 });
555​
556 it("does not claim a host absent from gh auth status", () => {
557 expect(
558 GitHubSourceControlProvider.refineUnknownGitHubRemote({
559 cwd: "/repo",
560 context,
561 auth: probe(
562 authStatusJson({ "github.com": [{ login: "octocat", state: "success", active: true }] }),
563 ),
564 }),
565 ).toBeNull();
566 });
567});
568​
569function makeProviderOfKind(
570 kind: "github" | "github-enterprise",
571 github: Partial<GitHubCli.GitHubCli["Service"]>,
572) {
573 return GitHubSourceControlProvider.makeProvider(kind).pipe(
574 Effect.provide(Layer.mock(GitHubCli.GitHubCli)(github)),
575 );
577​
578describe("getRepositoryCloneUrls bare name resolution", () => {
579 it.effect("resolves a bare enterprise name via search, preferring the exact-name match", () =>
580 Effect.gen(function* () {
581 const searchRepositories = vi.fn(() =>
582 Effect.succeed([
583 { fullName: "Sollit/core-documentation" },
584 { fullName: "Sollit/core" },
585 { fullName: "Sollit/frontend-core" },
586 { fullName: "Sollit/portal-core-service" },
587 ]),
588 );
589 const getRepositoryCloneUrls = vi.fn(() =>
590 Effect.succeed({
591 nameWithOwner: "Sollit/core",
592 url: "https://sollit.ghe.com/Sollit/core",
593 sshUrl: "git@sollit.ghe.com:Sollit/core.git",
594 }),
595 );
596​
597 const provider = yield* makeProviderOfKind("github-enterprise", {
598 searchRepositories,
599 getRepositoryCloneUrls,
600 });
601​
602 const result = yield* provider.getRepositoryCloneUrls({
603 cwd: "/repo",
604 repository: "core",
605 host: "sollit.ghe.com",
606 });
607​
608 expect(searchRepositories).toHaveBeenCalledWith({
609 cwd: "/repo",
610 query: "core",
611 host: "sollit.ghe.com",
612 });
613 expect(getRepositoryCloneUrls).toHaveBeenCalledWith({
614 cwd: "/repo",
615 repository: "Sollit/core",
616 host: "sollit.ghe.com",
617 });
618 assert.deepStrictEqual(result, {
619 nameWithOwner: "Sollit/core",
620 url: "https://sollit.ghe.com/Sollit/core",
621 sshUrl: "git@sollit.ghe.com:Sollit/core.git",
622 });
623 }),
624 );
625​
626 it.effect("resolves a sole near match when no bare name matches exactly", () =>
627 Effect.gen(function* () {
628 const searchRepositories = vi.fn(() =>
629 Effect.succeed([{ fullName: "Sollit/widget-service" }]),
630 );
631 const getRepositoryCloneUrls = vi.fn(() =>
632 Effect.succeed({
633 nameWithOwner: "Sollit/widget-service",
634 url: "https://sollit.ghe.com/Sollit/widget-service",
635 sshUrl: "git@sollit.ghe.com:Sollit/widget-service.git",
636 }),
637 );
638​
639 const provider = yield* makeProviderOfKind("github-enterprise", {
640 searchRepositories,
641 getRepositoryCloneUrls,
642 });
643​
644 yield* provider.getRepositoryCloneUrls({
645 cwd: "/repo",
646 repository: "widget",
647 host: "sollit.ghe.com",
648 });
649​
650 expect(getRepositoryCloneUrls).toHaveBeenCalledWith({
651 cwd: "/repo",
652 repository: "Sollit/widget-service",
653 host: "sollit.ghe.com",
654 });
655 }),
656 );
657​
658 it.effect("fails rather than rank near matches when none of them is exact", () =>
659 Effect.gen(function* () {
660 const searchRepositories = vi.fn(() =>
661 Effect.succeed([{ fullName: "Sollit/widget-service" }, { fullName: "Sollit/mywidget" }]),
662 );
663 const getRepositoryCloneUrls = vi.fn(() =>
664 Effect.succeed({
665 nameWithOwner: "Sollit/widget-service",
666 url: "https://sollit.ghe.com/Sollit/widget-service",
667 sshUrl: "git@sollit.ghe.com:Sollit/widget-service.git",
668 }),
669 );
670​
671 const provider = yield* makeProviderOfKind("github-enterprise", {
672 searchRepositories,
673 getRepositoryCloneUrls,
674 });
675​
676 const error = yield* provider
677 .getRepositoryCloneUrls({
678 cwd: "/repo",
679 repository: "widget",
680 host: "sollit.ghe.com",
681 })
682 .pipe(Effect.flip);
683​
684 expect(getRepositoryCloneUrls).not.toHaveBeenCalled();
685 expect(error.detail).toContain("Sollit/widget-service");
686 expect(error.detail).toContain("Sollit/mywidget");
687 }),
688 );
689​
690 it.effect("fails with a detail naming the query and host when search returns zero results", () =>
691 Effect.gen(function* () {
692 const searchRepositories = vi.fn(() => Effect.succeed([]));
693 const getRepositoryCloneUrls = vi.fn(() =>
694 Effect.succeed({
695 nameWithOwner: "Sollit/typo-name",
696 url: "https://sollit.ghe.com/Sollit/typo-name",
697 sshUrl: "git@sollit.ghe.com:Sollit/typo-name.git",
698 }),
699 );
700​
701 const provider = yield* makeProviderOfKind("github-enterprise", {
702 searchRepositories,
703 getRepositoryCloneUrls,
704 });
705​
706 const error = yield* provider
707 .getRepositoryCloneUrls({
708 cwd: "/repo",
709 repository: "typo-name",
710 host: "sollit.ghe.com",
711 })
712 .pipe(Effect.flip);
713​
714 expect(getRepositoryCloneUrls).not.toHaveBeenCalled();
715 expect(error.detail).toContain("typo-name");
716 expect(error.detail).toContain("sollit.ghe.com");
717 }),
718 );
719​
720 it.effect("fails naming every owner when several exact matches share the bare name", () =>
721 Effect.gen(function* () {
722 const searchRepositories = vi.fn(() =>
723 Effect.succeed([
724 { fullName: "team-a/core" },
725 { fullName: "team-b/core" },
726 { fullName: "team-c/core-docs" },
727 ]),
728 );
729 const getRepositoryCloneUrls = vi.fn(() =>
730 Effect.succeed({
731 nameWithOwner: "team-a/core",
732 url: "https://sollit.ghe.com/team-a/core",
733 sshUrl: "git@sollit.ghe.com:team-a/core.git",
734 }),
735 );
736​
737 const provider = yield* makeProviderOfKind("github-enterprise", {
738 searchRepositories,
739 getRepositoryCloneUrls,
740 });
741​
742 const error = yield* provider
743 .getRepositoryCloneUrls({
744 cwd: "/repo",
745 repository: "core",
746 host: "sollit.ghe.com",
747 })
748 .pipe(Effect.flip);
749​
750 expect(getRepositoryCloneUrls).not.toHaveBeenCalled();
751 expect(error.detail).toContain("team-a/core");
752 expect(error.detail).toContain("team-b/core");
753 expect(error.detail).not.toContain("team-c/core-docs");
754 }),
755 );
756​
757 it.effect("refuses a bare enterprise name without a host rather than searching github.com", () =>
758 Effect.gen(function* () {
759 const searchRepositories = vi.fn(() => Effect.succeed([{ fullName: "Sollit/core" }]));
760 const getRepositoryCloneUrls = vi.fn(() =>
761 Effect.succeed({
762 nameWithOwner: "Sollit/core",
763 url: "https://sollit.ghe.com/Sollit/core",
764 sshUrl: "git@sollit.ghe.com:Sollit/core.git",
765 }),
766 );
767​
768 const provider = yield* makeProviderOfKind("github-enterprise", {
769 searchRepositories,
770 getRepositoryCloneUrls,
771 });
772​
773 const error = yield* provider
774 .getRepositoryCloneUrls({ cwd: "/repo", repository: "core" })
775 .pipe(Effect.flip);
776​
777 expect(searchRepositories).not.toHaveBeenCalled();
778 expect(getRepositoryCloneUrls).not.toHaveBeenCalled();
779 expect(error.detail).toContain("host");
780 }),
781 );
782​
783 // GitManager resolves the enterprise provider from the git remote and looks
784 // up owner/repo with no host, letting `gh` read the host from the clone.
785 it.effect("looks up an owner/repo reference in-repo without a host", () =>
786 Effect.gen(function* () {
787 const searchRepositories = vi.fn(() => Effect.succeed([]));
788 const getRepositoryCloneUrls = vi.fn(() =>
789 Effect.succeed({
790 nameWithOwner: "Sollit/core",
791 url: "https://sollit.ghe.com/Sollit/core",
792 sshUrl: "git@sollit.ghe.com:Sollit/core.git",
793 }),
794 );
795​
796 const provider = yield* makeProviderOfKind("github-enterprise", {
797 searchRepositories,
798 getRepositoryCloneUrls,
799 });
800​
801 const result = yield* provider.getRepositoryCloneUrls({
802 cwd: "/repo",
803 repository: "Sollit/core",
804 });
805​
806 expect(searchRepositories).not.toHaveBeenCalled();
807 expect(getRepositoryCloneUrls).toHaveBeenCalledWith({
808 cwd: "/repo",
809 repository: "Sollit/core",
810 });
811 assert.strictEqual(result.nameWithOwner, "Sollit/core");
812 }),
813 );
814​
815 it.effect("refuses to create an enterprise repository without a host", () =>
816 Effect.gen(function* () {
817 const createRepository = vi.fn(() =>
818 Effect.succeed({
819 nameWithOwner: "Sollit/core",
820 url: "https://github.com/Sollit/core",
821 sshUrl: "git@github.com:Sollit/core.git",
822 }),
823 );
824​
825 const provider = yield* makeProviderOfKind("github-enterprise", { createRepository });
826​
827 const error = yield* provider
828 .createRepository({ cwd: "/repo", repository: "Sollit/core", visibility: "private" })
829 .pipe(Effect.flip);
830​
831 expect(createRepository).not.toHaveBeenCalled();
832 expect(error.detail).toContain("host");
833 }),
834 );
835​
836 it.effect("never calls search for an owner/repo reference on enterprise", () =>
837 Effect.gen(function* () {
838 const searchRepositories = vi.fn(() => Effect.succeed([]));
839 const getRepositoryCloneUrls = vi.fn(() =>
840 Effect.succeed({
841 nameWithOwner: "Sollit/core",
842 url: "https://sollit.ghe.com/Sollit/core",
843 sshUrl: "git@sollit.ghe.com:Sollit/core.git",
844 }),
845 );
846​
847 const provider = yield* makeProviderOfKind("github-enterprise", {
848 searchRepositories,
849 getRepositoryCloneUrls,
850 });
851​
852 yield* provider.getRepositoryCloneUrls({
853 cwd: "/repo",
854 repository: "Sollit/core",
855 host: "sollit.ghe.com",
856 });
857​
858 expect(searchRepositories).not.toHaveBeenCalled();
859 expect(getRepositoryCloneUrls).toHaveBeenCalledWith({
860 cwd: "/repo",
861 repository: "Sollit/core",
862 host: "sollit.ghe.com",
863 });
864 }),
865 );
866​
867 it.effect("never calls search for a bare name on plain github.com", () =>
868 Effect.gen(function* () {
869 const searchRepositories = vi.fn(() => Effect.succeed([]));
870 const getRepositoryCloneUrls = vi.fn(() =>
871 Effect.succeed({
872 nameWithOwner: "octocat/core",
873 url: "https://github.com/octocat/core",
874 sshUrl: "git@github.com:octocat/core.git",
875 }),
876 );
877​
878 const provider = yield* makeProviderOfKind("github", {
879 searchRepositories,
880 getRepositoryCloneUrls,
881 });
882​
883 const result = yield* provider.getRepositoryCloneUrls({
884 cwd: "/repo",
885 repository: "core",
886 });
887​
888 expect(searchRepositories).not.toHaveBeenCalled();
889 expect(getRepositoryCloneUrls).toHaveBeenCalledWith({
890 cwd: "/repo",
891 repository: "core",
892 });
893 assert.deepStrictEqual(result, {
894 nameWithOwner: "octocat/core",
895 url: "https://github.com/octocat/core",
896 sshUrl: "git@github.com:octocat/core.git",
897 });
898 }),
899 );
900});
901​
902describe("makeProvider", () => {
903 it.effect("tags change requests and errors with the enterprise kind", () =>
904 Effect.gen(function* () {
905 mockRun.mockReturnValueOnce(
906 Effect.succeed(
907 processResult(
908 // @effect-diagnostics-next-line preferSchemaOverJson:off
909 JSON.stringify([
910 {
911 number: 7,
912 title: "Add widget",
913 url: "https://git.corp.com/owner/repo/pull/7",
914 baseRefName: "main",
915 headRefName: "feature",
916 state: "OPEN",
917 },
918 ]),
919 ),
920 ),
921 );
922​
923 const provider = yield* GitHubSourceControlProvider.makeProvider("github-enterprise");
924 const requests = yield* provider.listChangeRequests({
925 cwd: "/repo",
926 headSelector: "feature",
927 state: "open",
928 });
929​
930 expect(provider.kind).toBe("github-enterprise");
931 expect(requests[0]!.provider).toBe("github-enterprise");
932 }).pipe(Effect.provide(cliLayer)),
933 );
934});
935​
936it("reports an update hint instead of unauthenticated when gh predates --json", () => {
937 const auth = GitHubSourceControlProvider.discovery.parseAuth(
938 processResult("", {
939 stderr: "unknown flag: --json\n\nUsage: gh auth status [flags]\n",
940 exitCode: ChildProcessSpawner.ExitCode(1),
941 }),
942 );
943​
944 assert.strictEqual(auth.status, "unknown");
945 assert.match(
946 Option.getOrElse(auth.detail, () => ""),
947 /2\.81\.0/,
948 );
949});
950​
951for (const kind of ["pull", "issues"]) {
952 it.effect(`resolves ${kind} subjects on the linked host without using the checkout`, () =>
953 Effect.gen(function* () {
954 const provider = yield* makeProvider({
955 execute: (input) => {
956 assert.deepStrictEqual(input.args, [
957 "api",
958 "--hostname",
959 "github.com",
960 "repos/owner/repo/issues/42",
961 "--jq",
962 "{title, body}",
963 ]);
964 assert.strictEqual(input.maxOutputBytes, 32_000);
965 assert.strictEqual(input.timeoutMs, 3_000);
966 return Effect.succeed({
967 exitCode: ChildProcessSpawner.ExitCode(0),
968 stdout: JSON.stringify({ title: "Pairing expiry", body: "Preserve remote access" }),
969 stderr: "",
970 stdoutTruncated: false,
971 stderrTruncated: false,
972 });
973 },
974 });
975 const lookup = provider.resolveLink?.({
976 cwd: "/unrelated",
977 url: new URL(`https://github.com/owner/repo/${kind}/42`),
978 });
979 assert.ok(lookup);
980 assert.deepStrictEqual(yield* lookup, {
981 title: "Pairing expiry",
982 body: "Preserve remote access",
983 });
984 assert.strictEqual(
985 provider.resolveLink?.({
986 cwd: "/unrelated",
987 url: new URL("https://github.com/owner/repo"),
988 }),
989 undefined,
990 );
991 }),
992 );
994​
995for (const stage of ["read", "decode"] as const) {
996 it.effect(`retains the ${stage} failure without exposing its raw contents`, () =>
997 Effect.gen(function* () {
998 const cause = new GitHubCli.GitHubCliCommandError({
999 command: "gh",
1000 cwd: "/repo",
1001 cause: new Error("private response text"),
1002 });
1003 const provider = yield* makeProvider({
1004 execute: () =>
1005 stage === "read"
1006 ? Effect.fail(cause)
1007 : Effect.succeed({
1008 exitCode: ChildProcessSpawner.ExitCode(0),
1009 stdout: "private response text",
1010 stderr: "",
1011 stdoutTruncated: false,
1012 stderrTruncated: false,
1013 }),
1014 });
1015 const lookup = provider.resolveLink?.({
1016 cwd: "/repo",
1017 url: new URL("https://github.com/owner/repo/issues/42"),
1018 });
1019 assert.ok(lookup);
1020 const error = yield* Effect.flip(lookup);
1021 assert.strictEqual(error.operation, stage === "read" ? "resolveLink" : "resolveLink.decode");
1022 assert.strictEqual(error.detail, "The linked subject could not be read.");
1023 assert.notInclude(error.message, "private response text");
1024 if (stage === "read") assert.strictEqual(error.cause, cause);
1025 else assert.propertyVal(error.cause, "_tag", "SchemaError");
1026 }),
1027 );