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

SourceControlProviderRegistry.test.ts

626 lines22.1 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { assert, it } from "@effect/vitest";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import * as DateTime from "effect/DateTime";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as PlatformError from "effect/PlatformError";
11import * as PubSub from "effect/PubSub";
12import * as Redacted from "effect/Redacted";
13import * as Stream from "effect/Stream";
14import * as TestClock from "effect/testing/TestClock";
15import { ChildProcessSpawner } from "effect/process";
16import {
17 DEFAULT_SERVER_SETTINGS,
18 VcsProcessSpawnError,
19 VcsProcessTimeoutError,
20 VcsRepositoryDetectionError,
21} from "@t3tools/contracts";
22​
23import * as ServerSettings from "../serverSettings.ts";
24import * as ServerConfig from "../config.ts";
25import type * as VcsDriver from "../vcs/VcsDriver.ts";
26import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
27import * as VcsProcess from "../vcs/VcsProcess.ts";
28import * as AzureDevOpsCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsCli";
29import * as AzureDevOpsPullRequestCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsPullRequestCli";
30import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi";
31import * as BitbucketPullRequestApi from "@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi";
32import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
33import * as GitHubApi from "@t3tools/source-control-github/server/GitHubApi";
34import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi";
35import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials";
36import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
37import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli";
38import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
39import * as GitCafeApi from "@t3tools/source-control-gitcafe/server/GitCafeApi";
40import * as GitCafeCredentials from "@t3tools/source-control-gitcafe/server/GitCafeCredentials";
41import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
42import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
43​
44const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
45​
46const processOutput = (
47 stdout: string,
48 options?: {
49 readonly stderr?: string;
50 readonly exitCode?: ChildProcessSpawner.ExitCode;
51 },
52): VcsProcess.VcsProcessOutput => ({
53 exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0),
54 stdout,
55 stderr: options?.stderr ?? "",
56 stdoutTruncated: false,
57 stderrTruncated: false,
58});
59​
60function makeRegistry(input: {
61 readonly remotes: ReadonlyArray<{
62 readonly name: string;
63 readonly url: string;
64 }>;
65 readonly process?: Partial<VcsProcess.VcsProcess["Service"]>;
66 readonly githubApi?: Partial<GitHubApi.GitHubApi["Service"]>;
67 readonly gitlab?: Partial<GitLabCli.GitLabCli["Service"]>;
68 readonly forgejo?: Partial<ForgejoCli.ForgejoCli["Service"]>;
69 readonly settings?: Partial<ServerSettings.ServerSettingsService["Service"]>;
70 readonly resolve?: VcsDriverRegistry.VcsDriverRegistry["Service"]["resolve"];
71}) {
72 const driver = {
73 listRemotes: () =>
74 Effect.succeed({
75 remotes: input.remotes.map((remote) => ({
76 ...remote,
77 pushUrl: Option.none(),
78 isPrimary: remote.name === "origin",
79 })),
80 freshness: {
81 source: "live-local" as const,
82 observedAt: TEST_EPOCH,
83 expiresAt: Option.none(),
84 },
85 }),
86 } satisfies Partial<VcsDriver.VcsDriver["Service"]>;
87​
88 const layerRegistry = Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
89 get: () => Effect.succeed(driver as unknown as VcsDriver.VcsDriver["Service"]),
90 resolve:
91 input.resolve ??
92 (() =>
93 Effect.succeed({
94 kind: "git",
95 repository: {
96 kind: "git",
97 rootPath: "/repo",
98 metadataPath: null,
99 freshness: {
100 source: "live-local" as const,
101 observedAt: TEST_EPOCH,
102 expiresAt: Option.none(),
103 },
104 },
105 driver: driver as unknown as VcsDriver.VcsDriver["Service"],
106 })),
107 });
108​
109 const layerProcess = Layer.mock(VcsProcess.VcsProcess)({
110 run: () => Effect.succeed(processOutput("")),
111 ...input.process,
112 });
113​
114 return SourceControlProviderRegistry.make.pipe(
115 Effect.provide(
116 Layer.mergeAll(
117 NodeServices.layer,
118 layerRegistry,
119 layerProcess,
120 ServerSourceControlHost.layer.pipe(
121 Layer.provide(
122 Layer.mergeAll(
123 layerProcess,
124 layerRegistry,
125 ServerSettings.ServerSettingsService.layerTest(),
126 Layer.mock(GitVcsDriver.GitVcsDriver)({}),
127 ),
128 ),
129 ),
130 Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
131 Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({}),
132 Layer.mock(BitbucketApi.BitbucketApi)({}),
133 Layer.mock(BitbucketPullRequestApi.BitbucketPullRequestApi)({}),
134 input.settings
135 ? Layer.mock(ServerSettings.ServerSettingsService)(input.settings)
136 : ServerSettings.ServerSettingsService.layerTest(),
137 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({}),
138 Layer.mock(GitHubApi.GitHubApi)({
139 // No GitHub credential unless a test supplies one, so custom hosts stay unclaimed.
140 credential: (host) => Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host })),
141 ...input.githubApi,
142 }),
143 Layer.mock(GitVcsDriver.GitVcsDriver)({}),
144 Layer.mock(GitLabCli.GitLabCli)(input.gitlab ?? {}),
145 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({}),
146 Layer.mock(ForgejoCli.ForgejoCli)({
147 listLogins: () => Effect.succeed([]),
148 ...input.forgejo,
149 }),
150 Layer.mock(GitCafeApi.GitCafeApi)({}),
151 Layer.mock(GitCafeCredentials.GitCafeCredentials)({
152 cliEnv: () => Effect.succeed({}),
153 }),
154 ServerConfig.layerTest(process.cwd(), {
155 prefix: "t3-source-control-registry-test-",
156 }).pipe(Layer.provide(NodeServices.layer)),
157 ),
158 ),
159 );
161​
162it.effect("routes GitHub remotes to the GitHub provider", () =>
163 Effect.gen(function* () {
164 const registry = yield* makeRegistry({
165 remotes: [{ name: "origin", url: "git@github.com:pingdotgg/t3code.git" }],
166 });
167​
168 const provider = yield* registry.resolve({ cwd: "/repo" });
169​
170 assert.strictEqual(provider.kind, "github");
171 }),
172);
173​
174it.effect("routes directly by provider kind for remote-first workflows", () =>
175 Effect.gen(function* () {
176 const registry = yield* makeRegistry({
177 remotes: [],
178 });
179​
180 const provider = yield* registry.get(SourceControlProviderKind.make("github"));
181​
182 assert.strictEqual(provider.kind, "github");
183 }),
184);
185​
186it.effect("includes the request cwd when an unregistered provider is used", () =>
187 Effect.gen(function* () {
188 const registry = yield* makeRegistry({ remotes: [] });
189 const provider = yield* registry.get(SourceControlProviderKind.make("unknown"));
190​
191 const error = yield* provider
192 .getChangeRequest({ cwd: "/repo", reference: "#42" })
193 .pipe(Effect.flip);
194​
195 assert.strictEqual(error.provider, "unknown");
196 assert.strictEqual(error.operation, "getChangeRequest");
197 assert.strictEqual(error.cwd, "/repo");
198 assert.strictEqual(error.reference, "#42");
199 }),
200);
201​
202it.effect("retains VCS detection failures with structured cwd context", () =>
203 Effect.gen(function* () {
204 const cause = new VcsRepositoryDetectionError({
205 operation: "resolve",
206 cwd: "/repo",
207 detail: "raw VCS detection failure",
208 cause: new Error("raw nested failure"),
209 });
210 const registry = yield* makeRegistry({
211 remotes: [],
212 resolve: () => Effect.fail(cause),
213 });
214​
215 const error = yield* registry.resolve({ cwd: "/repo" }).pipe(Effect.flip);
216​
217 assert.strictEqual(error.provider, "unknown");
218 assert.strictEqual(error.operation, "detectProvider");
219 assert.strictEqual(error.cwd, "/repo");
220 assert.strictEqual(error.detail, "Failed to detect source control provider.");
221 assert.strictEqual(error.cause, cause);
222 assert.equal(error.message.includes(cause.message), false);
223 }),
224);
225​
226it.effect("routes GitLab remotes to the GitLab provider", () =>
227 Effect.gen(function* () {
228 const registry = yield* makeRegistry({
229 remotes: [{ name: "origin", url: "git@gitlab.com:group/project.git" }],
230 });
231​
232 const provider = yield* registry.resolve({ cwd: "/repo" });
233​
234 assert.strictEqual(provider.kind, "gitlab");
235 }),
236);
237​
238it.effect("routes authenticated self-hosted GitLab remotes without relying on host naming", () =>
239 Effect.gen(function* () {
240 const registry = yield* makeRegistry({
241 remotes: [{ name: "origin", url: "https://self-hosted.example.test/group/project.git" }],
242 process: {
243 run: () =>
244 Effect.succeed(
245 processOutput(
246 `gitlab.com
247 x gitlab.com: API call failed: 401 Unauthorized
248 ! No token found
249self-hosted.example.test
250 ✓ Logged in to self-hosted.example.test as gitlab-user
251 ✓ Token found: ******
252`,
253 { exitCode: ChildProcessSpawner.ExitCode(1) },
254 ),
255 ),
256 },
257 });
258​
259 const provider = yield* registry.resolve({ cwd: "/repo" });
260​
261 assert.strictEqual(provider.kind, "gitlab");
262 }),
263);
264​
265it.effect("refines the caller-selected remote instead of choosing another configured remote", () =>
266 Effect.gen(function* () {
267 const registry = yield* makeRegistry({
268 remotes: [{ name: "origin", url: "git@github.com:fork/project.git" }],
269 process: {
270 run: () =>
271 Effect.succeed(
272 processOutput(`self-hosted.example.test
273 ✓ Logged in to self-hosted.example.test as gitlab-user
274`),
275 ),
276 },
277 });
278​
279 const handle = yield* registry.resolveHandle({
280 cwd: "/repo",
281 context: {
282 provider: {
283 kind: SourceControlProviderKind.make("unknown"),
284 name: "self-hosted.example.test",
285 baseUrl: "https://self-hosted.example.test",
286 },
287 remoteName: "upstream",
288 remoteUrl: "https://self-hosted.example.test/group/project.git",
289 },
290 });
291​
292 assert.strictEqual(handle.context?.provider.kind, "gitlab");
293 assert.strictEqual(handle.context?.remoteName, "upstream");
294 }),
295);
296​
297it.effect("routes authenticated self-hosted GitLab remotes on non-standard ports", () =>
298 Effect.gen(function* () {
299 const registry = yield* makeRegistry({
300 remotes: [{ name: "origin", url: "https://self-hosted.example.test:8443/group/project.git" }],
301 process: {
302 run: () =>
303 Effect.succeed(
304 processOutput(
305 `self-hosted.example.test:8443
306 ✓ Logged in to self-hosted.example.test:8443 as gitlab-user
307 ✓ Token found: ******
308`,
309 ),
310 ),
311 },
312 });
313​
314 const provider = yield* registry.resolve({ cwd: "/repo" });
315​
316 assert.strictEqual(provider.kind, "gitlab");
317 }),
318);
319​
320it.effect("routes Bitbucket remotes to the Bitbucket provider", () =>
321 Effect.gen(function* () {
322 const registry = yield* makeRegistry({
323 remotes: [{ name: "origin", url: "git@bitbucket.org:pingdotgg/t3code.git" }],
324 });
325​
326 const provider = yield* registry.resolve({ cwd: "/repo" });
327​
328 assert.strictEqual(provider.kind, "bitbucket");
329 }),
330);
331​
332it.effect("routes Azure DevOps remotes to the Azure DevOps provider", () =>
333 Effect.gen(function* () {
334 const registry = yield* makeRegistry({
335 remotes: [{ name: "origin", url: "https://dev.azure.com/acme/project/_git/repo" }],
336 });
337​
338 const provider = yield* registry.resolve({ cwd: "/repo" });
339​
340 assert.strictEqual(provider.kind, "azure-devops");
341 }),
342);
343​
344it.effect("falls back to a non-origin remote when origin is not configured", () =>
345 Effect.gen(function* () {
346 const registry = yield* makeRegistry({
347 remotes: [{ name: "upstream", url: "https://dev.azure.com/acme/project/_git/repo" }],
348 });
349​
350 const provider = yield* registry.resolve({ cwd: "/repo" });
351​
352 assert.strictEqual(provider.kind, "azure-devops");
353 }),
354);
355​
356it.effect(
357 "routes linked subjects by URL independently of the checkout and skips unsupported links",
358 () =>
359 Effect.gen(function* () {
360 const registry = yield* makeRegistry({
361 remotes: [{ name: "origin", url: "https://github.com/unrelated/checkout.git" }],
362 githubApi: {
363 rest: () =>
364 Effect.succeed({
365 status: 200,
366 headers: {},
367 body: JSON.stringify({ title: "GitHub issue", body: null }),
368 truncated: false,
369 invalidUtf8: false,
370 }),
371 },
372 gitlab: {
373 execute: () =>
374 Effect.succeed(
375 processOutput(JSON.stringify({ title: "GitLab MR", description: "Nested project" })),
376 ),
377 },
378 });
379 for (const [url, expected] of [
380 ["https://github.com/team/project/issues/1", { title: "GitHub issue", body: null }],
381 [
382 "https://gitlab.com/team/sub/project/-/merge_requests/2",
383 { title: "GitLab MR", body: "Nested project" },
384 ],
385 ] as const) {
386 const lookup = registry.resolveLink({ cwd: "/unrelated", url: new URL(url) });
387 assert.ok(lookup);
388 assert.deepStrictEqual(yield* lookup, expected);
389 }
390 for (const url of [
391 "https://example.test/team/project/issues/1",
392 "https://github.attacker.test/team/project/issues/1",
393 "https://gitlab.attacker.test/team/project/-/issues/1",
394 "https://github.com/team/project",
395 "https://codeberg.org/team/project/issues/1",
396 "https://bitbucket.org/team/project/pull-requests/1",
397 "https://dev.azure.com/org/project/_git/repo/pullrequest/1",
398 "http://github.com/team/project/issues/1",
399 "https://user:secret@github.com/team/project/issues/1",
400 ]) {
401 assert.strictEqual(
402 registry.resolveLink({ cwd: "/unrelated", url: new URL(url) }),
403 undefined,
404 );
405 }
406 }).pipe(Effect.scoped),
407);
408​
409it.effect.each([
410 { name: "a credential", credential: "found", expected: "github" },
411 // Claimed so the error says the host is turned off, not that it is unsupported.
412 { name: "a host turned off in Settings", credential: "disabled", expected: "github" },
413 { name: "no credential", credential: "missing", expected: "unknown" },
414] as const)("resolves custom-host remotes with $name", (scenario) =>
415 Effect.gen(function* () {
416 const hosts: Array<string> = [];
417 const commands: Array<string> = [];
418 const registry = yield* makeRegistry({
419 remotes: [{ name: "origin", url: "git@code.example.test:team/project.git" }],
420 process: {
421 run: ({ command }) => {
422 commands.push(command);
423 return Effect.succeed(processOutput(""));
424 },
425 },
426 githubApi: {
427 credential: (host) => {
428 hosts.push(host);
429 return scenario.credential === "found"
430 ? Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:fingerprint` })
431 : scenario.credential === "disabled"
432 ? Effect.fail(new GitHubCredentials.GitHubHostDisabledError({ host }))
433 : Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host }));
434 },
435 },
436 });
437 const handle = yield* registry.resolveHandle({ cwd: "/repo" });
438 assert.strictEqual(handle.provider.kind, SourceControlProviderKind.make(scenario.expected));
439 assert.strictEqual(handle.context?.provider.baseUrl, "https://code.example.test");
440 assert.deepStrictEqual(hosts, ["code.example.test"]);
441 // Recognition goes through the credential layer; gh is only one of its sources.
442 assert.notInclude(commands, "gh");
443 }),
444);
445​
446it.effect("skips GitHub discovery for the identity resolver's empty base URL", () =>
447 Effect.gen(function* () {
448 const hosts: string[] = [];
449 const remoteUrl = "git@githubenterprise.dev.example.com:team/workspace.git";
450 const registry = yield* makeRegistry({
451 remotes: [{ name: "origin", url: remoteUrl }],
452 githubApi: {
453 credential: (host) => {
454 hosts.push(host);
455 return Effect.succeed({
456 token: Redacted.make("token"),
457 fingerprint: `${host}:fingerprint`,
458 });
459 },
460 },
461 });
462 const context = {
463 provider: { kind: SourceControlProviderKind.make("unknown"), name: "Unknown", baseUrl: "" },
464 remoteName: "origin",
465 remoteUrl,
466 };
467 const unresolved = yield* registry.resolveHandle({ cwd: "/repo", context });
468 assert.deepStrictEqual(unresolved.context, context);
469 assert.deepStrictEqual(hosts, []);
470​
471 const resolved = yield* registry.resolveHandle({ cwd: "/repo" });
472 assert.strictEqual(resolved.provider.kind, "github");
473 assert.strictEqual(
474 resolved.context?.provider.baseUrl,
475 "https://githubenterprise.dev.example.com",
476 );
477 assert.deepStrictEqual(hosts, ["githubenterprise.dev.example.com"]);
478 }),
479);
480​
481const notFound = (command: string, cwd: string) =>
482 new VcsProcessSpawnError({
483 operation: "test",
484 command,
485 cwd,
486 cause: PlatformError.systemError({ _tag: "NotFound", module: "ChildProcess", method: "spawn" }),
487 });
488​
489const resolveUnknown = (
490 registry: SourceControlProviderRegistry.SourceControlProviderRegistry["Service"],
491 repository: string,
492) =>
493 registry.resolveHandle({
494 cwd: `/${repository}`,
495 context: {
496 provider: {
497 kind: SourceControlProviderKind.make("unknown"),
498 name: "git.example.internal",
499 baseUrl: "https://git.example.internal",
500 },
501 remoteName: "origin",
502 remoteUrl: `git@Git.Example.Internal:team/${repository}.git`,
503 },
504 });
505​
506it.effect("asks once for every checkout of a server no integration claims", () =>
507 Effect.gen(function* () {
508 const asked: Array<string> = [];
509 const release = yield* Deferred.make<void>();
510 const registry = yield* makeRegistry({
511 remotes: [],
512 process: {
513 run: ({ command, args, cwd }) => {
514 asked.push([command, ...args].join(" "));
515 return Deferred.await(release).pipe(Effect.andThen(Effect.fail(notFound(command, cwd))));
516 },
517 },
518 githubApi: {
519 credential: (host) => {
520 asked.push(`credential ${host}`);
521 return Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host }));
522 },
523 },
524 forgejo: {
525 listLogins: ({ command = "tea", cwd }) => {
526 asked.push(command);
527 const cause = notFound(command, cwd);
528 return Effect.fail(new ForgejoCli.ForgejoCliError({ command, cwd, detail: "", cause }));
529 },
530 },
531 });
532​
533 // Three checkouts read while the first probe is still running share it.
534 const started = yield* Effect.forEach(["a", "b", "c"], () => Deferred.make<void>());
535 const callers = yield* Effect.forEach(
536 ["a", "b", "c"],
537 (repository, index) =>
538 Deferred.succeed(started[index]!, undefined).pipe(
539 Effect.andThen(resolveUnknown(registry, repository)),
540 ),
541 { concurrency: "unbounded" },
542 ).pipe(Effect.forkChild);
543 yield* Effect.forEach(started, Deferred.await);
544 yield* Deferred.succeed(release, undefined);
545 const handles = yield* Fiber.join(callers);
546 yield* resolveUnknown(registry, "d");
547 assert.deepStrictEqual(
548 handles.map((handle) => handle.provider.kind),
549 ["unknown", "unknown", "unknown"],
550 );
551 const once = asked.slice();
552 // glab is asked about the remote's host as the remote spells it.
553 assert.sameMembers(once, [
554 "credential git.example.internal",
555 "glab auth status --hostname Git.Example.Internal",
556 "fj",
557 "tea",
558 ]);
559​
560 // A login made in a terminal sends no signal, so the server is asked again later.
561 yield* TestClock.adjust("5 minutes");
562 yield* resolveUnknown(registry, "a");
563 assert.deepStrictEqual(asked, [...once, ...once]);
564 }),
565);
566​
567it.effect("asks again after a check that could not answer", () =>
568 Effect.gen(function* () {
569 let asks = 0;
570 const registry = yield* makeRegistry({
571 remotes: [],
572 process: {
573 run: ({ command, cwd }) => {
574 asks += 1;
575 return Effect.fail(
576 new VcsProcessTimeoutError({ operation: "test", command, cwd, timeoutMs: 1 }),
577 );
578 },
579 },
580 });
581 yield* resolveUnknown(registry, "a");
582 yield* resolveUnknown(registry, "b");
583 assert.strictEqual(asks, 2);
584 }),
585);
586​
587it.effect("asks again once Settings change", () =>
588 Effect.gen(function* () {
589 const changes = yield* PubSub.unbounded<typeof DEFAULT_SERVER_SETTINGS>();
590 const handled = yield* Deferred.make<void>();
591 let signedIn = false;
592 const registry = yield* makeRegistry({
593 remotes: [],
594 settings: {
595 subscribeChanges: PubSub.subscribe(changes).pipe(
596 Effect.map((subscription) =>
597 // A change is handled once the registry asks for the next one.
598 Stream.fromSubscription(subscription).pipe(
599 Stream.flatMap((settings) =>
600 Stream.concat(
601 Stream.make(settings),
602 Stream.fromEffectDrain(Deferred.succeed(handled, undefined)),
603 ),
604 ),
605 ),
606 ),
607 ),
608 },
609 process: { run: ({ command, cwd }) => Effect.fail(notFound(command, cwd)) },
610 githubApi: {
611 credential: (host) =>
612 signedIn
613 ? Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:fingerprint` })
614 : Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host })),
615 },
616 });
617 assert.strictEqual((yield* resolveUnknown(registry, "a")).provider.kind, "unknown");
618 signedIn = true;
619 assert.strictEqual((yield* resolveUnknown(registry, "b")).provider.kind, "unknown");
620​
621 // A token saved for the host in Settings.
622 yield* PubSub.publish(changes, DEFAULT_SERVER_SETTINGS);
623 yield* Deferred.await(handled);
624 assert.strictEqual((yield* resolveUnknown(registry, "c")).provider.kind, "github");
625 }),
626);