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

SourceControlProviderRegistry.test.ts

1,255 lines45.6 KB

1import {
2 DEFAULT_SERVER_SETTINGS,
3 SourceControlProviderKind,
4 VcsProcessExitError,
5 VcsProcessSpawnError,
6 VcsProcessTimeoutError,
7 type ServerSettings as ContractServerSettings,
8} from "@t3tools/contracts";
9import { assert, it } from "@effect/vitest";
10import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
11import * as NodeServices from "@effect/platform-node/NodeServices";
12import * as DateTime from "effect/DateTime";
13import * as Deferred from "effect/Deferred";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Fiber from "effect/Fiber";
17import * as FileSystem from "effect/FileSystem";
18import * as HttpClient from "effect/http/HttpClient";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as PlatformError from "effect/PlatformError";
22import * as PubSub from "effect/PubSub";
23import * as Redacted from "effect/Redacted";
24import * as Stream from "effect/Stream";
25import * as TestClock from "effect/testing/TestClock";
26import { ChildProcessSpawner } from "effect/process";
27import { VcsRepositoryDetectionError } from "@t3tools/contracts";
28import * as HostProcess from "@t3tools/shared/HostProcess";
29import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
30import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
31​
32import * as ProcessRunner from "../processRunner.ts";
33import * as ServerSettings from "../serverSettings.ts";
34import * as ServerConfig from "../config.ts";
35import type * as VcsDriver from "../vcs/VcsDriver.ts";
36import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
37import * as VcsProcess from "../vcs/VcsProcess.ts";
38import * as AzureDevOpsCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsCli";
39import * as AzureDevOpsPullRequestCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsPullRequestCli";
40import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi";
41import * as BitbucketPullRequestApi from "@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi";
42import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
43import * as GitHubApi from "@t3tools/source-control-github/server/GitHubApi";
44import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi";
45import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials";
46import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
47import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli";
48import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
49import * as GitCafeApi from "@t3tools/source-control-gitcafe/server/GitCafeApi";
50import * as GitCafeCredentials from "@t3tools/source-control-gitcafe/server/GitCafeCredentials";
51import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
52import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
53​
54const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
55​
56const processOutput = (
57 stdout: string,
58 options?: {
59 readonly stderr?: string;
60 readonly exitCode?: ChildProcessSpawner.ExitCode;
61 },
62): VcsProcess.VcsProcessOutput => ({
63 exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0),
64 stdout,
65 stderr: options?.stderr ?? "",
66 stdoutTruncated: false,
67 stderrTruncated: false,
68});
69​
70// What `glab auth status` prints when no host is logged in.
71const noGitLabLogin = processOutput("", {
72 stderr:
73 "no GitLab instances have been authenticated with glab; run `glab auth login` to authenticate\n",
74 exitCode: ChildProcessSpawner.ExitCode(1),
75});
76​
77// What GitHubCredentials fails with when `gh auth token` says it holds no login for the host.
78const notSignedIn = (host: string) =>
79 new GitHubCredentials.GitHubNotSignedInError({
80 host,
81 cause: VcsProcessExitError.fromProcessExit(
82 { operation: "GitHubCredentials.get", command: "gh", cwd: "/" },
83 { exitCode: 1, stderr: `no oauth token found for ${host}`, stderrTruncated: false },
84 "authentication",
85 ),
86 });
87​
88function makeRegistry(input: {
89 readonly remotes: ReadonlyArray<{
90 readonly name: string;
91 readonly url: string;
92 }>;
93 readonly process?: Partial<VcsProcess.VcsProcess["Service"]>;
94 readonly githubApi?: Partial<GitHubApi.GitHubApi["Service"]>;
95 readonly gitlab?: Partial<GitLabCli.GitLabCli["Service"]>;
96 readonly forgejo?: Partial<ForgejoCli.ForgejoCli["Service"]>;
97 readonly settingsChanges?: Stream.Stream<ContractServerSettings>;
98 readonly resolve?: VcsDriverRegistry.VcsDriverRegistry["Service"]["resolve"];
99}) {
100 const driver = {
101 listRemotes: () =>
102 Effect.succeed({
103 remotes: input.remotes.map((remote) => ({
104 ...remote,
105 pushUrl: Option.none(),
106 isPrimary: remote.name === "origin",
107 })),
108 freshness: {
109 source: "live-local" as const,
110 observedAt: TEST_EPOCH,
111 expiresAt: Option.none(),
112 },
113 }),
114 } satisfies Partial<VcsDriver.VcsDriver["Service"]>;
115​
116 const layerRegistry = Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
117 get: () => Effect.succeed(driver as unknown as VcsDriver.VcsDriver["Service"]),
118 resolve:
119 input.resolve ??
120 (() =>
121 Effect.succeed({
122 kind: "git",
123 repository: {
124 kind: "git",
125 rootPath: "/repo",
126 metadataPath: null,
127 freshness: {
128 source: "live-local" as const,
129 observedAt: TEST_EPOCH,
130 expiresAt: Option.none(),
131 },
132 },
133 driver: driver as unknown as VcsDriver.VcsDriver["Service"],
134 })),
135 });
136​
137 const layerProcess = Layer.mock(VcsProcess.VcsProcess)({
138 run: ({ command }) => Effect.succeed(command === "glab" ? noGitLabLogin : processOutput("")),
139 ...input.process,
140 });
141​
142 return SourceControlProviderRegistry.make.pipe(
143 Effect.provide(
144 Layer.mergeAll(
145 NodeServices.layer,
146 layerRegistry,
147 layerProcess,
148 ServerSourceControlHost.layer.pipe(
149 Layer.provide(
150 Layer.mergeAll(
151 layerProcess,
152 layerRegistry,
153 ServerSettings.ServerSettingsService.layerTest(),
154 Layer.mock(GitVcsDriver.GitVcsDriver)({}),
155 ),
156 ),
157 ),
158 Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
159 Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({}),
160 Layer.mock(BitbucketApi.BitbucketApi)({}),
161 Layer.mock(BitbucketPullRequestApi.BitbucketPullRequestApi)({}),
162 Layer.mock(ServerSettings.ServerSettingsService)({
163 subscribeChanges: Effect.succeed(input.settingsChanges ?? Stream.empty),
164 }),
165 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({}),
166 Layer.mock(GitHubApi.GitHubApi)({
167 // No GitHub credential unless a test supplies one, so custom hosts stay unclaimed.
168 credential: (host) => Effect.fail(notSignedIn(host)),
169 ...input.githubApi,
170 }),
171 Layer.mock(GitVcsDriver.GitVcsDriver)({}),
172 Layer.mock(GitLabCli.GitLabCli)(input.gitlab ?? {}),
173 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({}),
174 Layer.mock(ForgejoCli.ForgejoCli)({
175 listLogins: () => Effect.succeed([]),
176 ...input.forgejo,
177 }),
178 Layer.mock(GitCafeApi.GitCafeApi)({}),
179 Layer.mock(GitCafeCredentials.GitCafeCredentials)({
180 cliEnv: () => Effect.succeed({}),
181 }),
182 ServerConfig.layerTest(process.cwd(), {
183 prefix: "t3-source-control-registry-test-",
184 }).pipe(Layer.provide(NodeServices.layer)),
185 ),
186 ),
187 );
189​
190it.effect("routes GitHub remotes to the GitHub provider", () =>
191 Effect.gen(function* () {
192 const registry = yield* makeRegistry({
193 remotes: [{ name: "origin", url: "git@github.com:pingdotgg/t3code.git" }],
194 });
195​
196 const provider = yield* registry.resolve({ cwd: "/repo" });
197​
198 assert.strictEqual(provider.kind, "github");
199 }),
200);
201​
202it.effect("routes directly by provider kind for remote-first workflows", () =>
203 Effect.gen(function* () {
204 const registry = yield* makeRegistry({
205 remotes: [],
206 });
207​
208 const provider = yield* registry.get(SourceControlProviderKind.make("github"));
209​
210 assert.strictEqual(provider.kind, "github");
211 }),
212);
213​
214it.effect("includes the request cwd when an unregistered provider is used", () =>
215 Effect.gen(function* () {
216 const registry = yield* makeRegistry({ remotes: [] });
217 const provider = yield* registry.get(SourceControlProviderKind.make("unknown"));
218​
219 const error = yield* provider
220 .getChangeRequest({ cwd: "/repo", reference: "#42" })
221 .pipe(Effect.flip);
222​
223 assert.strictEqual(error.provider, "unknown");
224 assert.strictEqual(error.operation, "getChangeRequest");
225 assert.strictEqual(error.cwd, "/repo");
226 assert.strictEqual(error.reference, "#42");
227 }),
228);
229​
230it.effect("retains VCS detection failures with structured cwd context", () =>
231 Effect.gen(function* () {
232 const cause = new VcsRepositoryDetectionError({
233 operation: "resolve",
234 cwd: "/repo",
235 detail: "raw VCS detection failure",
236 cause: new Error("raw nested failure"),
237 });
238 const registry = yield* makeRegistry({
239 remotes: [],
240 resolve: () => Effect.fail(cause),
241 });
242​
243 const error = yield* registry.resolve({ cwd: "/repo" }).pipe(Effect.flip);
244​
245 assert.strictEqual(error.provider, "unknown");
246 assert.strictEqual(error.operation, "detectProvider");
247 assert.strictEqual(error.cwd, "/repo");
248 assert.strictEqual(error.detail, "Failed to detect source control provider.");
249 assert.strictEqual(error.cause, cause);
250 assert.equal(error.message.includes(cause.message), false);
251 }),
252);
253​
254it.effect("routes GitLab remotes to the GitLab provider", () =>
255 Effect.gen(function* () {
256 const registry = yield* makeRegistry({
257 remotes: [{ name: "origin", url: "git@gitlab.com:group/project.git" }],
258 });
259​
260 const provider = yield* registry.resolve({ cwd: "/repo" });
261​
262 assert.strictEqual(provider.kind, "gitlab");
263 }),
264);
265​
266it.effect("routes authenticated self-hosted GitLab remotes without relying on host naming", () =>
267 Effect.gen(function* () {
268 const registry = yield* makeRegistry({
269 remotes: [{ name: "origin", url: "https://self-hosted.example.test/group/project.git" }],
270 process: {
271 run: () =>
272 Effect.succeed(
273 processOutput(
274 `gitlab.com
275 x gitlab.com: API call failed: 401 Unauthorized
276 ! No token found
277self-hosted.example.test
278 ✓ Logged in to self-hosted.example.test as gitlab-user
279 ✓ Token found: ******
280`,
281 { exitCode: ChildProcessSpawner.ExitCode(1) },
282 ),
283 ),
284 },
285 });
286​
287 const provider = yield* registry.resolve({ cwd: "/repo" });
288​
289 assert.strictEqual(provider.kind, "gitlab");
290 }),
291);
292​
293it.effect("refines the caller-selected remote instead of choosing another configured remote", () =>
294 Effect.gen(function* () {
295 const registry = yield* makeRegistry({
296 remotes: [{ name: "origin", url: "git@github.com:fork/project.git" }],
297 process: {
298 run: () =>
299 Effect.succeed(
300 processOutput(`self-hosted.example.test
301 ✓ Logged in to self-hosted.example.test as gitlab-user
302`),
303 ),
304 },
305 });
306​
307 const handle = yield* registry.resolveHandle({
308 cwd: "/repo",
309 context: {
310 provider: {
311 kind: SourceControlProviderKind.make("unknown"),
312 name: "self-hosted.example.test",
313 baseUrl: "https://self-hosted.example.test",
314 },
315 remoteName: "upstream",
316 remoteUrl: "https://self-hosted.example.test/group/project.git",
317 },
318 });
319​
320 assert.strictEqual(handle.context?.provider.kind, "gitlab");
321 assert.strictEqual(handle.context?.remoteName, "upstream");
322 }),
323);
324​
325it.effect("routes authenticated self-hosted GitLab remotes on non-standard ports", () =>
326 Effect.gen(function* () {
327 const registry = yield* makeRegistry({
328 remotes: [{ name: "origin", url: "https://self-hosted.example.test:8443/group/project.git" }],
329 process: {
330 run: () =>
331 Effect.succeed(
332 processOutput(
333 `self-hosted.example.test:8443
334 ✓ Logged in to self-hosted.example.test:8443 as gitlab-user
335 ✓ Token found: ******
336`,
337 ),
338 ),
339 },
340 });
341​
342 const provider = yield* registry.resolve({ cwd: "/repo" });
343​
344 assert.strictEqual(provider.kind, "gitlab");
345 }),
346);
347​
348it.effect("routes Bitbucket remotes to the Bitbucket provider", () =>
349 Effect.gen(function* () {
350 const registry = yield* makeRegistry({
351 remotes: [{ name: "origin", url: "git@bitbucket.org:pingdotgg/t3code.git" }],
352 });
353​
354 const provider = yield* registry.resolve({ cwd: "/repo" });
355​
356 assert.strictEqual(provider.kind, "bitbucket");
357 }),
358);
359​
360it.effect("routes Azure DevOps remotes to the Azure DevOps provider", () =>
361 Effect.gen(function* () {
362 const registry = yield* makeRegistry({
363 remotes: [{ name: "origin", url: "https://dev.azure.com/acme/project/_git/repo" }],
364 });
365​
366 const provider = yield* registry.resolve({ cwd: "/repo" });
367​
368 assert.strictEqual(provider.kind, "azure-devops");
369 }),
370);
371​
372it.effect("falls back to a non-origin remote when origin is not configured", () =>
373 Effect.gen(function* () {
374 const registry = yield* makeRegistry({
375 remotes: [{ name: "upstream", url: "https://dev.azure.com/acme/project/_git/repo" }],
376 });
377​
378 const provider = yield* registry.resolve({ cwd: "/repo" });
379​
380 assert.strictEqual(provider.kind, "azure-devops");
381 }),
382);
383​
384it.effect(
385 "routes linked subjects by URL independently of the checkout and skips unsupported links",
386 () =>
387 Effect.gen(function* () {
388 const registry = yield* makeRegistry({
389 remotes: [{ name: "origin", url: "https://github.com/unrelated/checkout.git" }],
390 githubApi: {
391 rest: () =>
392 Effect.succeed({
393 status: 200,
394 headers: {},
395 body: JSON.stringify({ title: "GitHub issue", body: null }),
396 truncated: false,
397 invalidUtf8: false,
398 }),
399 },
400 gitlab: {
401 execute: () =>
402 Effect.succeed(
403 processOutput(JSON.stringify({ title: "GitLab MR", description: "Nested project" })),
404 ),
405 },
406 });
407 for (const [url, expected] of [
408 ["https://github.com/team/project/issues/1", { title: "GitHub issue", body: null }],
409 [
410 "https://gitlab.com/team/sub/project/-/merge_requests/2",
411 { title: "GitLab MR", body: "Nested project" },
412 ],
413 ] as const) {
414 const lookup = registry.resolveLink({ cwd: "/unrelated", url: new URL(url) });
415 assert.ok(lookup);
416 assert.deepStrictEqual(yield* lookup, expected);
417 }
418 for (const url of [
419 "https://example.test/team/project/issues/1",
420 "https://github.attacker.test/team/project/issues/1",
421 "https://gitlab.attacker.test/team/project/-/issues/1",
422 "https://github.com/team/project",
423 "https://codeberg.org/team/project/issues/1",
424 "https://bitbucket.org/team/project/pull-requests/1",
425 "https://dev.azure.com/org/project/_git/repo/pullrequest/1",
426 "http://github.com/team/project/issues/1",
427 "https://user:secret@github.com/team/project/issues/1",
428 ]) {
429 assert.strictEqual(
430 registry.resolveLink({ cwd: "/unrelated", url: new URL(url) }),
431 undefined,
432 );
433 }
434 }).pipe(Effect.scoped),
435);
436​
437it.effect.each([
438 { name: "a credential", credential: "found", expected: "github" },
439 // Claimed so the error says the host is turned off, not that it is unsupported.
440 { name: "a host turned off in Settings", credential: "disabled", expected: "github" },
441 { name: "no credential", credential: "missing", expected: "unknown" },
442] as const)("resolves custom-host remotes with $name", (scenario) =>
443 Effect.gen(function* () {
444 const hosts: Array<string> = [];
445 const commands: Array<string> = [];
446 const registry = yield* makeRegistry({
447 remotes: [{ name: "origin", url: "git@code.example.test:team/project.git" }],
448 process: {
449 run: ({ command }) => {
450 commands.push(command);
451 return Effect.succeed(processOutput(""));
452 },
453 },
454 githubApi: {
455 credential: (host) => {
456 hosts.push(host);
457 return scenario.credential === "found"
458 ? Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:fingerprint` })
459 : scenario.credential === "disabled"
460 ? Effect.fail(new GitHubCredentials.GitHubHostDisabledError({ host }))
461 : Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host }));
462 },
463 },
464 });
465 const handle = yield* registry.resolveHandle({ cwd: "/repo" });
466 assert.strictEqual(handle.provider.kind, SourceControlProviderKind.make(scenario.expected));
467 assert.strictEqual(handle.context?.provider.baseUrl, "https://code.example.test");
468 assert.deepStrictEqual(hosts, ["code.example.test"]);
469 // Recognition goes through the credential layer; gh is only one of its sources. Once GitHub
470 // claims the host, glab and the other integrations after it are not asked.
471 assert.deepStrictEqual(commands, scenario.expected === "github" ? [] : ["glab"]);
472 }),
473);
474​
475it.effect("skips GitHub discovery for the identity resolver's empty base URL", () =>
476 Effect.gen(function* () {
477 const hosts: string[] = [];
478 const remoteUrl = "git@githubenterprise.dev.example.com:team/workspace.git";
479 const registry = yield* makeRegistry({
480 remotes: [{ name: "origin", url: remoteUrl }],
481 githubApi: {
482 credential: (host) => {
483 hosts.push(host);
484 return Effect.succeed({
485 token: Redacted.make("token"),
486 fingerprint: `${host}:fingerprint`,
487 });
488 },
489 },
490 });
491 const context = {
492 provider: { kind: SourceControlProviderKind.make("unknown"), name: "Unknown", baseUrl: "" },
493 remoteName: "origin",
494 remoteUrl,
495 };
496 const unresolved = yield* registry.resolveHandle({ cwd: "/repo", context });
497 assert.deepStrictEqual(unresolved.context, context);
498 assert.deepStrictEqual(hosts, []);
499​
500 const resolved = yield* registry.resolveHandle({ cwd: "/repo" });
501 assert.strictEqual(resolved.provider.kind, "github");
502 assert.strictEqual(
503 resolved.context?.provider.baseUrl,
504 "https://githubenterprise.dev.example.com",
505 );
506 assert.deepStrictEqual(hosts, ["githubenterprise.dev.example.com"]);
507 }),
508);
509​
510// What PullRequestService and GitManager pass for a remote whose host names no integration.
511const unknownRemote = (remoteUrl: string) => ({
512 provider: {
513 kind: SourceControlProviderKind.make("unknown"),
514 name: "git.example.internal",
515 baseUrl: "https://git.example.internal",
516 },
517 remoteName: "origin",
518 remoteUrl,
519});
520​
521// The spawner checks the cwd before it spawns, so a missing checkout fails in `FileSystem` and only
522// a missing executable fails in `ChildProcess`.
523const spawnError = (
524 command: string,
525 cwd: string,
526 reason: "NotFound" | "PermissionDenied",
527 module: "ChildProcess" | "FileSystem",
528) =>
529 new VcsProcessSpawnError({
530 operation: "source-control.discovery.refine-unknown-remote",
531 command,
532 cwd,
533 cause: PlatformError.systemError({
534 _tag: reason,
535 module,
536 method: module === "ChildProcess" ? "spawn" : "access",
537 pathOrDescriptor: module === "ChildProcess" ? command : cwd,
538 }),
539 });
540​
541const missingCli = (command: string, cwd: string) =>
542 spawnError(command, cwd, "NotFound", "ChildProcess");
543​
544it.effect("asks the hosting CLIs once for every checkout of an unclaimed host", () =>
545 Effect.gen(function* () {
546 // No hosting CLI is installed and GitHub holds no credential, so every integration answers no.
547 const makeUnclaimedRegistry = (
548 beforeSpawn: Effect.Effect<void>,
549 failure: (
550 command: string,
551 cwd: string,
552 ) => VcsProcessSpawnError | VcsProcessTimeoutError = missingCli,
553 ) =>
554 Effect.gen(function* () {
555 const commands: Array<string> = [];
556 const logins: Array<string> = [];
557 const hosts: Array<string> = [];
558 const registry = yield* makeRegistry({
559 remotes: [],
560 process: {
561 run: ({ command, cwd }) => {
562 commands.push(command);
563 return beforeSpawn.pipe(Effect.andThen(Effect.fail(failure(command, cwd))));
564 },
565 },
566 githubApi: {
567 credential: (host) => {
568 hosts.push(host);
569 return Effect.fail(notSignedIn(host));
570 },
571 },
572 forgejo: {
573 listLogins: ({ command, cwd }) => {
574 logins.push(command);
575 return command === "fj"
576 ? Effect.succeed([])
577 : Effect.fail(
578 new ForgejoCli.ForgejoCliError({
579 command,
580 cwd,
581 reason: "missing-cli",
582 detail: "tea is not installed.",
583 cause: missingCli(command, cwd),
584 }),
585 );
586 },
587 },
588 });
589 return { registry, commands, logins, hosts };
590 });
591 const checkouts = ["a", "b", "c"].map((name) => ({
592 cwd: `/${name}`,
593 remoteUrl: `https://git.example.internal/team/${name}.git`,
594 }));
595 const resolveCheckout = (
596 registry: SourceControlProviderRegistry.SourceControlProviderRegistry["Service"],
597 checkout: (typeof checkouts)[number],
598 ) => registry.resolveHandle({ cwd: checkout.cwd, context: unknownRemote(checkout.remoteUrl) });
599​
600 const sequential = yield* makeUnclaimedRegistry(Effect.void);
601 for (const checkout of [...checkouts, ...checkouts]) {
602 const handle = yield* resolveCheckout(sequential.registry, checkout);
603 assert.strictEqual(handle.provider.kind, "unknown");
604 // One answer serves the host; each checkout keeps its own remote.
605 assert.strictEqual(handle.context?.remoteUrl, checkout.remoteUrl);
606 }
607 assert.deepStrictEqual(sequential.commands, ["glab"]);
608 assert.deepStrictEqual(sequential.logins, ["fj", "tea"]);
609 assert.deepStrictEqual(sequential.hosts, ["git.example.internal"]);
610​
611 // Checkouts that ask at the same time wait for the first one's probes. glab times out, so the
612 // answer is not kept and only waiting on the pending lookup explains a single spawn.
613 const spawned = yield* Deferred.make<void>();
614 const release = yield* Deferred.make<void>();
615 const concurrent = yield* makeUnclaimedRegistry(
616 Deferred.succeed(spawned, undefined).pipe(Effect.andThen(Deferred.await(release))),
617 (command, cwd) =>
618 new VcsProcessTimeoutError({
619 operation: "source-control.discovery.refine-unknown-remote",
620 command,
621 cwd,
622 timeoutMs: 5_000,
623 }),
624 );
625 const lookups = yield* Effect.forEach(
626 checkouts,
627 (checkout) => resolveCheckout(concurrent.registry, checkout),
628 { concurrency: "unbounded" },
629 ).pipe(Effect.forkChild);
630 yield* Deferred.await(spawned);
631 yield* Effect.yieldNow;
632 yield* Deferred.succeed(release, undefined);
633 const handles = yield* Fiber.join(lookups);
634 assert.deepStrictEqual(
635 handles.map((handle) => handle.context?.remoteUrl),
636 checkouts.map((checkout) => checkout.remoteUrl),
637 );
638 assert.deepStrictEqual(concurrent.commands, ["glab"]);
639 // Nothing was kept, so a later lookup asks again.
640 yield* resolveCheckout(concurrent.registry, {
641 cwd: "/d",
642 remoteUrl: "https://git.example.internal/team/d.git",
643 });
644 assert.deepStrictEqual(concurrent.commands, ["glab", "glab"]);
645 }),
646);
647​
648// GitHub holds no credential for the host until `signIn`, as after a `gh auth login` in a terminal.
649const makeSignInRegistry = (
650 settingsChanges: Stream.Stream<ContractServerSettings> = Stream.empty,
651) =>
652 Effect.gen(function* () {
653 let signedIn = false;
654 const hosts: Array<string> = [];
655 const commands: Array<string> = [];
656 const registry = yield* makeRegistry({
657 remotes: [],
658 settingsChanges,
659 process: {
660 run: ({ command }) => {
661 commands.push(command);
662 return Effect.succeed(noGitLabLogin);
663 },
664 },
665 githubApi: {
666 credential: (host) => {
667 hosts.push(host);
668 return signedIn
669 ? Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:fingerprint` })
670 : Effect.fail(notSignedIn(host));
671 },
672 },
673 });
674 return {
675 hosts,
676 commands,
677 signIn: () => {
678 signedIn = true;
679 },
680 resolveKind: registry
681 .resolveHandle({
682 cwd: "/repo",
683 context: unknownRemote("https://git.example.internal/team/a.git"),
684 })
685 .pipe(Effect.map((handle) => handle.provider.kind)),
686 };
687 });
688​
689it.effect("notices a CLI login made outside the app once the verdict expires", () =>
690 Effect.gen(function* () {
691 const github = yield* makeSignInRegistry();
692​
693 assert.strictEqual(yield* github.resolveKind, "unknown");
694 github.signIn();
695 yield* TestClock.adjust(Duration.minutes(4));
696 assert.strictEqual(yield* github.resolveKind, "unknown");
697 assert.deepStrictEqual(github.hosts, ["git.example.internal"]);
698 assert.deepStrictEqual(github.commands, ["glab"]);
699​
700 yield* TestClock.adjust(Duration.minutes(1));
701 assert.strictEqual(yield* github.resolveKind, "github");
702 assert.deepStrictEqual(github.hosts, ["git.example.internal", "git.example.internal"]);
703 }),
704);
705​
706it.effect("asks again as soon as settings change", () =>
707 Effect.gen(function* () {
708 const changes = yield* PubSub.unbounded<ContractServerSettings>();
709 const handled = yield* Deferred.make<void>();
710 // The registry reads past the change only once it has handled it.
711 const github = yield* makeSignInRegistry(
712 Stream.fromSubscription(yield* PubSub.subscribe(changes)).pipe(
713 Stream.take(1),
714 Stream.concat(Stream.fromEffectDrain(Deferred.succeed(handled, undefined))),
715 ),
716 );
717​
718 assert.strictEqual(yield* github.resolveKind, "unknown");
719 // A token saved in Settings; the registry hears of it only through the settings stream.
720 github.signIn();
721 assert.strictEqual(yield* github.resolveKind, "unknown");
722 yield* PubSub.publish(changes, DEFAULT_SERVER_SETTINGS);
723 yield* Deferred.await(handled);
724 assert.strictEqual(yield* github.resolveKind, "github");
725 assert.deepStrictEqual(github.hosts, ["git.example.internal", "git.example.internal"]);
726 }),
727);
728​
729const signedInGitLab = processOutput(`git.example.internal
730 ✓ Logged in to git.example.internal as gitlab-user
731`);
732​
733it.effect.each([
734 { name: "a missing checkout", failure: "missing-checkout" },
735 { name: "a glab timeout", failure: "timeout" },
736 { name: "glab without permission to run", failure: "permission-denied" },
737 { name: "a tea failure", failure: "tea" },
738 { name: "a glab config glab could not read", failure: "unreadable-config" },
739] as const)("does not keep an answer a checkout could not reach: $name", (scenario) =>
740 Effect.gen(function* () {
741 // The checkouts that reached the failing CLI.
742 const asked: Array<string> = [];
743 const glabFailure = (cwd: string) =>
744 scenario.failure === "missing-checkout"
745 ? spawnError("glab", cwd, "NotFound", "FileSystem")
746 : scenario.failure === "timeout"
747 ? new VcsProcessTimeoutError({
748 operation: "source-control.discovery.refine-unknown-remote",
749 command: "glab",
750 cwd,
751 timeoutMs: 5_000,
752 })
753 : spawnError("glab", cwd, "PermissionDenied", "ChildProcess");
754 const registry = yield* makeRegistry({
755 remotes: [],
756 process: {
757 run: ({ command, cwd }) => {
758 if (scenario.failure === "tea") return Effect.fail(missingCli(command, cwd));
759 asked.push(cwd);
760 if (cwd !== "/gone") return Effect.succeed(signedInGitLab);
761 // glab ran, but its output names no host and is not its never-logged-in answer.
762 return scenario.failure === "unreadable-config"
763 ? Effect.succeed(
764 processOutput("", {
765 stderr:
766 "failed to read config: open /home/user/.config/glab-cli/config.yml: permission denied\n",
767 exitCode: ChildProcessSpawner.ExitCode(1),
768 }),
769 )
770 : Effect.fail(glabFailure(cwd));
771 },
772 },
773 forgejo: {
774 listLogins: ({ command, cwd }) => {
775 if (scenario.failure !== "tea" || command === "fj") return Effect.succeed([]);
776 asked.push(cwd);
777 return cwd === "/gone"
778 ? Effect.fail(
779 new ForgejoCli.ForgejoCliError({
780 command,
781 cwd,
782 detail: "Forgejo CLI command failed.",
783 }),
784 )
785 : Effect.succeed([
786 {
787 name: "forge",
788 url: "https://git.example.internal",
789 user: "forgejo-user",
790 default: "true",
791 },
792 ]);
793 },
794 },
795 });
796 const context = unknownRemote("https://git.example.internal/team/a.git");
797​
798 const gone = yield* registry.resolveHandle({ cwd: "/gone", context });
799 assert.strictEqual(gone.provider.kind, "unknown");
800 // A healthy checkout of the same remote asks again and gets its own answer.
801 const healthy = yield* registry.resolveHandle({ cwd: "/healthy", context });
802 assert.strictEqual(healthy.provider.kind, scenario.failure === "tea" ? "forgejo" : "gitlab");
803 assert.deepStrictEqual(asked, ["/gone", "/healthy"]);
804 }),
805);
806​
807it.effect("does not keep a decline for a host glab could not confirm", () =>
808 Effect.gen(function* () {
809 // glab lists the host, but its API call failed, so the record holds no account.
810 const unconfirmedGitLab = processOutput(
811 `git.example.internal
812 x git.example.internal: API call failed: GET https://git.example.internal/api/v4/user: dial tcp: i/o timeout
813 ✓ Git operations for git.example.internal configured to use https protocol.
814`,
815 { exitCode: ChildProcessSpawner.ExitCode(1) },
816 );
817 const outputs = [unconfirmedGitLab, signedInGitLab];
818 const registry = yield* makeRegistry({
819 remotes: [],
820 process: {
821 run: ({ command }) =>
822 Effect.succeed(
823 command === "glab" ? (outputs.shift() ?? noGitLabLogin) : processOutput(""),
824 ),
825 },
826 });
827 const resolveKind = registry
828 .resolveHandle({
829 cwd: "/repo",
830 context: unknownRemote("https://git.example.internal/team/a.git"),
831 })
832 .pipe(Effect.map((handle) => handle.provider.kind));
833​
834 assert.strictEqual(yield* resolveKind, "unknown");
835 assert.strictEqual(yield* resolveKind, "gitlab");
836 assert.strictEqual(outputs.length, 0);
837 }),
838);
839​
840it.effect.each([
841 { name: "no login, in current glab's words", output: noGitLabLogin, runs: 1 },
842 {
843 name: "no login, in older glab's words",
844 output: processOutput("", {
845 stderr:
846 "No GitLab instance has been authenticated with glab. Run `glab auth login` to authenticate.\n",
847 exitCode: ChildProcessSpawner.ExitCode(1),
848 }),
849 runs: 1,
850 },
851 // The record for this host may be in the part cut off at the output limit.
852 {
853 name: "another host, in output cut short",
854 output: {
855 ...processOutput(`other.example.internal
856 ✓ Logged in to other.example.internal as gitlab-user
857`),
858 stdoutTruncated: true,
859 },
860 runs: 2,
861 },
862 // A claim read from cut output is still used, and the next lookup asks glab again.
863 {
864 name: "this host, in output cut short",
865 output: { ...signedInGitLab, stdoutTruncated: true },
866 kind: "gitlab",
867 runs: 2,
868 },
869])("keeps a glab answer only when glab answered in full: $name", (scenario) =>
870 Effect.gen(function* () {
871 const commands: Array<string> = [];
872 const registry = yield* makeRegistry({
873 remotes: [],
874 process: {
875 run: ({ command }) => {
876 commands.push(command);
877 return Effect.succeed(scenario.output);
878 },
879 },
880 });
881 for (const cwd of ["/a", "/b"]) {
882 const handle = yield* registry.resolveHandle({
883 cwd,
884 context: unknownRemote("https://git.example.internal/team/a.git"),
885 });
886 assert.strictEqual(handle.provider.kind, scenario.kind ?? "unknown");
887 }
888 assert.strictEqual(commands.length, scenario.runs);
889 }),
890);
891​
892it.effect("keeps Forgejo mounts on one host apart", () =>
893 Effect.gen(function* () {
894 const logins: Array<string> = [];
895 const registry = yield* makeRegistry({
896 remotes: [],
897 forgejo: {
898 listLogins: ({ command }) => {
899 logins.push(command);
900 return Effect.succeed(
901 command === "tea"
902 ? [
903 {
904 name: "forge-one",
905 url: "https://git.example.internal/forge-one",
906 user: "forgejo-user",
907 default: "true",
908 },
909 ]
910 : [],
911 );
912 },
913 },
914 });
915 const resolveContext = (cwd: string, remoteUrl: string) =>
916 registry
917 .resolveHandle({ cwd, context: unknownRemote(remoteUrl) })
918 .pipe(Effect.map((handle) => handle.context));
919​
920 const mounted = yield* resolveContext(
921 "/a",
922 "https://git.example.internal/forge-one/team/a.git",
923 );
924 assert.strictEqual(mounted?.provider.kind, "forgejo");
925 assert.strictEqual(mounted?.provider.baseUrl, "https://git.example.internal/forge-one");
926 // The login serves only its mount, so another installation on the host stays unclaimed.
927 const outside = yield* resolveContext(
928 "/b",
929 "https://git.example.internal/forge-two/team/b.git",
930 );
931 assert.strictEqual(outside?.provider.kind, "unknown");
932 const sibling = yield* resolveContext(
933 "/c",
934 "https://git.example.internal/forge-one/team/c.git",
935 );
936 assert.strictEqual(sibling?.provider.kind, "forgejo");
937 assert.strictEqual(sibling?.provider.baseUrl, "https://git.example.internal/forge-one");
938 assert.strictEqual(sibling?.remoteUrl, "https://git.example.internal/forge-one/team/c.git");
939 assert.deepStrictEqual(logins, ["fj", "tea", "fj", "tea"]);
940 }),
941);
942​
943it.effect("keeps Forgejo mounts apart when only their case differs", () =>
944 Effect.gen(function* () {
945 const mount = (path: string) => ({
946 name: path,
947 url: `https://git.example.internal/${path}`,
948 user: "forgejo-user",
949 default: "false",
950 });
951 const makeMountRegistry = (paths: ReadonlyArray<string>) =>
952 makeRegistry({
953 remotes: [],
954 forgejo: {
955 listLogins: ({ command }) => Effect.succeed(command === "tea" ? paths.map(mount) : []),
956 },
957 });
958 const resolveProvider = (
959 registry: SourceControlProviderRegistry.SourceControlProviderRegistry["Service"],
960 mountPath: string,
961 ) =>
962 registry
963 .resolveHandle({
964 cwd: `/${mountPath}`,
965 context: unknownRemote(`https://git.example.internal/${mountPath}/team/a.git`),
966 })
967 .pipe(Effect.map((handle) => handle.context?.provider));
968​
969 // Forgejo compares mount paths as written, so each checkout keeps its own installation.
970 const both = yield* makeMountRegistry(["Forge-One", "forge-one"]);
971 const upper = yield* resolveProvider(both, "Forge-One");
972 assert.strictEqual(upper?.baseUrl, "https://git.example.internal/Forge-One");
973 const lower = yield* resolveProvider(both, "forge-one");
974 assert.strictEqual(lower?.baseUrl, "https://git.example.internal/forge-one");
975​
976 // An unclaimed mount asked first does not hide the login of its differently cased twin.
977 const upperOnly = yield* makeMountRegistry(["Forge-One"]);
978 assert.strictEqual((yield* resolveProvider(upperOnly, "forge-one"))?.kind, "unknown");
979 const claimed = yield* resolveProvider(upperOnly, "Forge-One");
980 assert.strictEqual(claimed?.kind, "forgejo");
981 assert.strictEqual(claimed?.baseUrl, "https://git.example.internal/Forge-One");
982 }),
983);
984​
985it.effect.each([
986 // Both logins serve group/a, so neither claims it; only the host's login serves other/b.
987 {
988 name: "the host and a group on it",
989 mounts: ["", "/group"],
990 remotes: {
991 a: "https://git.example.internal/group/a.git",
992 b: "https://git.example.internal/other/b.git",
993 },
994 expected: { a: null, b: "https://git.example.internal" },
995 },
996 {
997 name: "a group on the host",
998 mounts: ["/group"],
999 remotes: {
1000 a: "https://git.example.internal/group/a.git",
1001 b: "https://git.example.internal/other/b.git",
1002 },
1003 expected: { a: "https://git.example.internal/group", b: null },
1004 },
1005 // As the first row, one level down: the mount is `forge`, and the group login sits below it.
1007 name: "a mount and a group under it",
1008 mounts: ["/forge", "/forge/group"],
1009 remotes: {
1010 a: "https://git.example.internal/forge/group/a.git",
1011 b: "https://git.example.internal/forge/other/b.git",
1012 },
1013 expected: { a: null, b: "https://git.example.internal/forge" },
1014 },
1015 // Parsed as given, a's path keeps `...git`, so a sits under the mount `mount` and both logins
1016 // serve it. Removing `.git` before parsing would leave `team/..` and put a on the host's key.
1018 name: "the host and a mount, for a remote named ...git",
1019 mounts: ["", "/mount"],
1020 remotes: {
1021 a: "https://git.example.internal/mount/team/...git",
1022 b: "https://git.example.internal/other/b.git",
1023 },
1024 expected: { a: null, b: "https://git.example.internal" },
1025 },
1026 // Forgejo cannot read an SCP path from the root, so a gets no claim and must not key with b.
1028 name: "the host, for an SCP remote with a path from the root",
1029 mounts: [""],
1030 remotes: {
1031 a: "git@git.example.internal:/team/a.git",
1032 b: "git@git.example.internal:other/b.git",
1033 },
1034 expected: { a: null, b: "https://git.example.internal" },
1035 },
1036] as const)("gives each remote of one mount its own Forgejo answer: logins at $name", (scenario) =>
1037 Effect.gen(function* () {
1038 for (const order of [
1039 ["a", "b"],
1040 ["b", "a"],
1041 ] as const) {
1042 const registry = yield* makeRegistry({
1043 remotes: [],
1044 forgejo: {
1045 listLogins: ({ command }) =>
1046 Effect.succeed(
1047 command === "tea"
1048 ? scenario.mounts.map((mount) => ({
1049 name: `forge${mount}`,
1050 url: `https://git.example.internal${mount}`,
1051 user: "forgejo-user",
1052 default: "false",
1053 }))
1054 : [],
1055 ),
1056 },
1057 });
1058 for (const remote of order) {
1059 const handle = yield* registry.resolveHandle({
1060 cwd: `/${remote}`,
1061 context: unknownRemote(scenario.remotes[remote]),
1062 });
1063 assert.strictEqual(
1064 handle.provider.kind === "forgejo" ? handle.context?.provider.baseUrl : null,
1065 scenario.expected[remote],
1066 `${remote} after ${order[0] === remote ? "nothing" : order[0]}`,
1067 );
1070 }),
1072​
1073it.effect("asks gh again once it can read its config", () =>
1074 Effect.gen(function* () {
1075 // gh cannot load its config file at first, then hands over a token.
1076 let configReadable = false;
1077 const runs: Array<string> = [];
1078 const vcsProcess = yield* VcsProcess.make.pipe(
1079 Effect.provideService(ProcessRunner.ProcessRunner, {
1080 run: (input) => {
1081 runs.push(`${input.command} ${input.args.join(" ")}`);
1082 return Effect.succeed({
1083 stdout: configReadable ? "token\n" : "",
1084 stderr: configReadable
1085 ? ""
1086 : "failed to read configuration: invalid config file /home/user/.config/gh/hosts.yml: invalid yaml\n",
1087 code: ChildProcessSpawner.ExitCode(configReadable ? 0 : 1),
1088 timedOut: false,
1089 stdoutTruncated: false,
1090 stderrTruncated: false,
1091 stdoutInvalidUtf8: false,
1092 stderrInvalidUtf8: false,
1093 });
1094 },
1095 }),
1096 );
1097 const credentials = yield* GitHubCredentials.make.pipe(
1098 Effect.provide(
1099 Layer.mergeAll(
1100 TestSourceControlHost.layer({ process: { run: vcsProcess.run } }),
1101 NodeCrypto.layer,
1102 ),
1103 ),
1104 Effect.provideService(HostProcess.Environment, {}),
1105 );
1106 const registry = yield* makeRegistry({
1107 remotes: [],
1108 process: { run: ({ command, cwd }) => Effect.fail(missingCli(command, cwd)) },
1109 githubApi: {
1110 credential: (host) =>
1111 credentials
1112 .get(host)
1113 .pipe(Effect.map(({ token, fingerprint }) => ({ token, fingerprint }))),
1114 },
1115 });
1116 const resolveKind = registry
1117 .resolveHandle({
1118 cwd: "/repo",
1119 context: unknownRemote("https://git.example.internal/team/a.git"),
1120 })
1121 .pipe(Effect.map((handle) => handle.provider.kind));
1122​
1123 assert.strictEqual(yield* resolveKind, "unknown");
1124 configReadable = true;
1125 // Past the ten seconds GitHubCredentials keeps a missing credential, well inside the five
1126 // minutes a settled verdict lasts.
1127 yield* TestClock.adjust(Duration.seconds(11));
1128 assert.strictEqual(yield* resolveKind, "github");
1129 assert.deepStrictEqual(runs, [
1130 "gh auth token --hostname git.example.internal",
1131 "gh auth token --hostname git.example.internal",
1132 ]);
1133 }),
1135​
1136// The real ForgejoCli, reading fj's keys through `fileSystem` and running fj and tea through `run`.
1137const makeForgejoCli = (input: {
1138 readonly fileSystem: Partial<FileSystem.FileSystem>;
1139 readonly run: SourceControlHost.SourceControlHost["Service"]["process"]["run"];
1140}) =>
1141 ForgejoCli.make.pipe(
1142 Effect.provideService(FileSystem.FileSystem, FileSystem.makeNoop(input.fileSystem)),
1143 Effect.provideService(
1144 HttpClient.HttpClient,
1145 HttpClient.make(() => Effect.die("Unexpected Forgejo API request.")),
1146 ),
1147 Effect.provide(TestSourceControlHost.layer({ process: { run: input.run } })),
1148 );
1149​
1150it.effect.each([
1151 { name: "an fj that cannot run, with keys it could not read", failure: "fj" },
1152 { name: "a tea login list that is not JSON", failure: "tea" },
1153] as const)("asks Forgejo again after its logins could not be read: $name", (scenario) =>
1154 Effect.gen(function* () {
1155 let healthy = false;
1156 const cli = yield* makeForgejoCli({
1157 fileSystem: {
1158 // Only the fj scenario has a keys file.
1159 exists: () => Effect.succeed(scenario.failure === "fj"),
1160 readFileString: (path) =>
1161 healthy
1162 ? Effect.succeed(
1163 '{"hosts":{"git.example.internal":{"type":"Application","token":"token"}}}',
1165 : Effect.fail(
1166 PlatformError.systemError({
1167 _tag: "PermissionDenied",
1168 module: "FileSystem",
1169 method: "readFileString",
1170 pathOrDescriptor: path,
1171 }),
1172 ),
1173 },
1174 run: ({ command, cwd }) => {
1175 // `fj version` checks whether fj is installed: it is, but it cannot run.
1176 if (command === "fj")
1177 return Effect.fail(spawnError(command, cwd, "PermissionDenied", "ChildProcess"));
1178 if (scenario.failure === "fj") return Effect.fail(missingCli(command, cwd));
1179 return Effect.succeed(
1180 TestSourceControlHost.processOutput(
1181 healthy
1182 ? '[{"name":"forge","url":"https://git.example.internal","user":"forgejo-user","default":"true"}]'
1183 : "Error: could not read tea config\n",
1184 ),
1185 );
1186 },
1187 });
1188 const registry = yield* makeRegistry({
1189 remotes: [],
1190 process: { run: ({ command, cwd }) => Effect.fail(missingCli(command, cwd)) },
1191 forgejo: cli,
1192 });
1193 const resolveProvider = registry
1194 .resolveHandle({
1195 cwd: "/repo",
1196 context: unknownRemote("https://git.example.internal/team/a.git"),
1197 })
1198 .pipe(Effect.map((handle) => handle.context?.provider));
1199​
1200 assert.strictEqual((yield* resolveProvider)?.kind, "unknown");
1201 healthy = true;
1202 const provider = yield* resolveProvider;
1203 assert.strictEqual(provider?.kind, "forgejo");
1204 assert.strictEqual(provider?.baseUrl, "https://git.example.internal");
1205 }),
1207​
1208it.effect("does not keep a tea claim made while fj could not answer", () =>
1209 Effect.gen(function* () {
1210 let fjHealthy = false;
1211 const registry = yield* makeRegistry({
1212 remotes: [],
1213 forgejo: {
1214 listLogins: ({ command, cwd }) =>
1215 command === "tea"
1216 ? Effect.succeed([
1218 name: "forge-one",
1219 url: "https://git.example.internal/forge-one",
1220 user: "forgejo-user",
1221 default: "true",
1222 },
1223 ])
1224 : fjHealthy
1225 ? Effect.succeed([
1227 name: "git.example.internal",
1228 url: "https://git.example.internal",
1229 user: "",
1230 default: "false",
1231 },
1232 ])
1233 : Effect.fail(
1234 new ForgejoCli.ForgejoCliError({
1235 command,
1236 cwd,
1237 reason: "authentication",
1238 detail: "Could not read fj authentication storage.",
1239 }),
1240 ),
1241 },
1242 });
1243 const resolveBaseUrl = registry
1244 .resolveHandle({
1245 cwd: "/repo",
1246 context: unknownRemote("https://git.example.internal/forge-one/team/a.git"),
1247 })
1248 .pipe(Effect.map((handle) => handle.context?.provider.baseUrl));
1249​
1250 assert.strictEqual(yield* resolveBaseUrl, "https://git.example.internal/forge-one");
1251 // fj is asked first, so once it can read its keys its login for the whole host wins.
1252 fjHealthy = true;
1253 assert.strictEqual(yield* resolveBaseUrl, "https://git.example.internal");
1254 }),