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