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

SourceControlProviderRegistry.test.ts

476 lines17.0 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 Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Redacted from "effect/Redacted";
9import { ChildProcessSpawner } from "effect/process";
10import { VcsRepositoryDetectionError } from "@t3tools/contracts";
11​
12import * as ServerSettings from "../serverSettings.ts";
13import * as ServerConfig from "../config.ts";
14import type * as VcsDriver from "../vcs/VcsDriver.ts";
15import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
16import * as VcsProcess from "../vcs/VcsProcess.ts";
17import * as AzureDevOpsCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsCli";
18import * as AzureDevOpsPullRequestCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsPullRequestCli";
19import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi";
20import * as BitbucketPullRequestApi from "@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi";
21import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
22import * as GitHubApi from "@t3tools/source-control-github/server/GitHubApi";
23import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi";
24import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials";
25import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
26import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli";
27import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
28import * as GitCafeApi from "@t3tools/source-control-gitcafe/server/GitCafeApi";
29import * as GitCafeCredentials from "@t3tools/source-control-gitcafe/server/GitCafeCredentials";
30import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
31import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
32​
33const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
34​
35const processOutput = (
36 stdout: string,
37 options?: {
38 readonly stderr?: string;
39 readonly exitCode?: ChildProcessSpawner.ExitCode;
40 },
41): VcsProcess.VcsProcessOutput => ({
42 exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0),
43 stdout,
44 stderr: options?.stderr ?? "",
45 stdoutTruncated: false,
46 stderrTruncated: false,
47});
48​
49function makeRegistry(input: {
50 readonly remotes: ReadonlyArray<{
51 readonly name: string;
52 readonly url: string;
53 }>;
54 readonly process?: Partial<VcsProcess.VcsProcess["Service"]>;
55 readonly githubApi?: Partial<GitHubApi.GitHubApi["Service"]>;
56 readonly gitlab?: Partial<GitLabCli.GitLabCli["Service"]>;
57 readonly resolve?: VcsDriverRegistry.VcsDriverRegistry["Service"]["resolve"];
58}) {
59 const driver = {
60 listRemotes: () =>
61 Effect.succeed({
62 remotes: input.remotes.map((remote) => ({
63 ...remote,
64 pushUrl: Option.none(),
65 isPrimary: remote.name === "origin",
66 })),
67 freshness: {
68 source: "live-local" as const,
69 observedAt: TEST_EPOCH,
70 expiresAt: Option.none(),
71 },
72 }),
73 } satisfies Partial<VcsDriver.VcsDriver["Service"]>;
74​
75 const layerRegistry = Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
76 get: () => Effect.succeed(driver as unknown as VcsDriver.VcsDriver["Service"]),
77 resolve:
78 input.resolve ??
79 (() =>
80 Effect.succeed({
81 kind: "git",
82 repository: {
83 kind: "git",
84 rootPath: "/repo",
85 metadataPath: null,
86 freshness: {
87 source: "live-local" as const,
88 observedAt: TEST_EPOCH,
89 expiresAt: Option.none(),
90 },
91 },
92 driver: driver as unknown as VcsDriver.VcsDriver["Service"],
93 })),
94 });
95​
96 const layerProcess = Layer.mock(VcsProcess.VcsProcess)({
97 run: () => Effect.succeed(processOutput("")),
98 ...input.process,
99 });
100​
101 return SourceControlProviderRegistry.make.pipe(
102 Effect.provide(
103 Layer.mergeAll(
104 NodeServices.layer,
105 layerRegistry,
106 layerProcess,
107 ServerSourceControlHost.layer.pipe(
108 Layer.provide(
109 Layer.mergeAll(
110 layerProcess,
111 layerRegistry,
112 ServerSettings.ServerSettingsService.layerTest(),
113 Layer.mock(GitVcsDriver.GitVcsDriver)({}),
114 ),
115 ),
116 ),
117 Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
118 Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({}),
119 Layer.mock(BitbucketApi.BitbucketApi)({}),
120 Layer.mock(BitbucketPullRequestApi.BitbucketPullRequestApi)({}),
121 ServerSettings.ServerSettingsService.layerTest(),
122 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({}),
123 Layer.mock(GitHubApi.GitHubApi)({
124 // No GitHub credential unless a test supplies one, so custom hosts stay unclaimed.
125 credential: (host) => Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host })),
126 ...input.githubApi,
127 }),
128 Layer.mock(GitVcsDriver.GitVcsDriver)({}),
129 Layer.mock(GitLabCli.GitLabCli)(input.gitlab ?? {}),
130 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({}),
131 Layer.mock(ForgejoCli.ForgejoCli)({ listLogins: () => Effect.succeed([]) }),
132 Layer.mock(GitCafeApi.GitCafeApi)({}),
133 Layer.mock(GitCafeCredentials.GitCafeCredentials)({
134 cliEnv: () => Effect.succeed({}),
135 }),
136 ServerConfig.layerTest(process.cwd(), {
137 prefix: "t3-source-control-registry-test-",
138 }).pipe(Layer.provide(NodeServices.layer)),
139 ),
140 ),
141 );
143​
144it.effect("routes GitHub remotes to the GitHub provider", () =>
145 Effect.gen(function* () {
146 const registry = yield* makeRegistry({
147 remotes: [{ name: "origin", url: "git@github.com:pingdotgg/t3code.git" }],
148 });
149​
150 const provider = yield* registry.resolve({ cwd: "/repo" });
151​
152 assert.strictEqual(provider.kind, "github");
153 }),
154);
155​
156it.effect("routes directly by provider kind for remote-first workflows", () =>
157 Effect.gen(function* () {
158 const registry = yield* makeRegistry({
159 remotes: [],
160 });
161​
162 const provider = yield* registry.get(SourceControlProviderKind.make("github"));
163​
164 assert.strictEqual(provider.kind, "github");
165 }),
166);
167​
168it.effect("includes the request cwd when an unregistered provider is used", () =>
169 Effect.gen(function* () {
170 const registry = yield* makeRegistry({ remotes: [] });
171 const provider = yield* registry.get(SourceControlProviderKind.make("unknown"));
172​
173 const error = yield* provider
174 .getChangeRequest({ cwd: "/repo", reference: "#42" })
175 .pipe(Effect.flip);
176​
177 assert.strictEqual(error.provider, "unknown");
178 assert.strictEqual(error.operation, "getChangeRequest");
179 assert.strictEqual(error.cwd, "/repo");
180 assert.strictEqual(error.reference, "#42");
181 }),
182);
183​
184it.effect("lists no change requests for a repository on an unrecognized host", () =>
185 Effect.gen(function* () {
186 const registry = yield* makeRegistry({
187 remotes: [{ name: "origin", url: "https://git.example.internal/team/repo.git" }],
188 });
189 const provider = yield* registry.resolve({ cwd: "/repo" });
190​
191 assert.strictEqual(provider.kind, "unknown");
192 assert.deepStrictEqual(
193 yield* provider.listChangeRequests({ cwd: "/repo", headSelector: "master", state: "all" }),
194 [],
195 );
196 }),
197);
198​
199it.effect("retains VCS detection failures with structured cwd context", () =>
200 Effect.gen(function* () {
201 const cause = new VcsRepositoryDetectionError({
202 operation: "resolve",
203 cwd: "/repo",
204 detail: "raw VCS detection failure",
205 cause: new Error("raw nested failure"),
206 });
207 const registry = yield* makeRegistry({
208 remotes: [],
209 resolve: () => Effect.fail(cause),
210 });
211​
212 const error = yield* registry.resolve({ cwd: "/repo" }).pipe(Effect.flip);
213​
214 assert.strictEqual(error.provider, "unknown");
215 assert.strictEqual(error.operation, "detectProvider");
216 assert.strictEqual(error.cwd, "/repo");
217 assert.strictEqual(error.detail, "Failed to detect source control provider.");
218 assert.strictEqual(error.cause, cause);
219 assert.equal(error.message.includes(cause.message), false);
220 }),
221);
222​
223it.effect("routes GitLab remotes to the GitLab provider", () =>
224 Effect.gen(function* () {
225 const registry = yield* makeRegistry({
226 remotes: [{ name: "origin", url: "git@gitlab.com:group/project.git" }],
227 });
228​
229 const provider = yield* registry.resolve({ cwd: "/repo" });
230​
231 assert.strictEqual(provider.kind, "gitlab");
232 }),
233);
234​
235it.effect("routes authenticated self-hosted GitLab remotes without relying on host naming", () =>
236 Effect.gen(function* () {
237 const registry = yield* makeRegistry({
238 remotes: [{ name: "origin", url: "https://self-hosted.example.test/group/project.git" }],
239 process: {
240 run: () =>
241 Effect.succeed(
242 processOutput(
243 `gitlab.com
244 x gitlab.com: API call failed: 401 Unauthorized
245 ! No token found
246self-hosted.example.test
247 ✓ Logged in to self-hosted.example.test as gitlab-user
248 ✓ Token found: ******
249`,
250 { exitCode: ChildProcessSpawner.ExitCode(1) },
251 ),
252 ),
253 },
254 });
255​
256 const provider = yield* registry.resolve({ cwd: "/repo" });
257​
258 assert.strictEqual(provider.kind, "gitlab");
259 }),
260);
261​
262it.effect("refines the caller-selected remote instead of choosing another configured remote", () =>
263 Effect.gen(function* () {
264 const registry = yield* makeRegistry({
265 remotes: [{ name: "origin", url: "git@github.com:fork/project.git" }],
266 process: {
267 run: () =>
268 Effect.succeed(
269 processOutput(`self-hosted.example.test
270 ✓ Logged in to self-hosted.example.test as gitlab-user
271`),
272 ),
273 },
274 });
275​
276 const handle = yield* registry.resolveHandle({
277 cwd: "/repo",
278 context: {
279 provider: {
280 kind: SourceControlProviderKind.make("unknown"),
281 name: "self-hosted.example.test",
282 baseUrl: "https://self-hosted.example.test",
283 },
284 remoteName: "upstream",
285 remoteUrl: "https://self-hosted.example.test/group/project.git",
286 },
287 });
288​
289 assert.strictEqual(handle.context?.provider.kind, "gitlab");
290 assert.strictEqual(handle.context?.remoteName, "upstream");
291 }),
292);
293​
294it.effect("routes authenticated self-hosted GitLab remotes on non-standard ports", () =>
295 Effect.gen(function* () {
296 const registry = yield* makeRegistry({
297 remotes: [{ name: "origin", url: "https://self-hosted.example.test:8443/group/project.git" }],
298 process: {
299 run: () =>
300 Effect.succeed(
301 processOutput(
302 `self-hosted.example.test:8443
303 ✓ Logged in to self-hosted.example.test:8443 as gitlab-user
304 ✓ Token found: ******
305`,
306 ),
307 ),
308 },
309 });
310​
311 const provider = yield* registry.resolve({ cwd: "/repo" });
312​
313 assert.strictEqual(provider.kind, "gitlab");
314 }),
315);
316​
317it.effect("routes Bitbucket remotes to the Bitbucket provider", () =>
318 Effect.gen(function* () {
319 const registry = yield* makeRegistry({
320 remotes: [{ name: "origin", url: "git@bitbucket.org:pingdotgg/t3code.git" }],
321 });
322​
323 const provider = yield* registry.resolve({ cwd: "/repo" });
324​
325 assert.strictEqual(provider.kind, "bitbucket");
326 }),
327);
328​
329it.effect("routes Azure DevOps remotes to the Azure DevOps provider", () =>
330 Effect.gen(function* () {
331 const registry = yield* makeRegistry({
332 remotes: [{ name: "origin", url: "https://dev.azure.com/acme/project/_git/repo" }],
333 });
334​
335 const provider = yield* registry.resolve({ cwd: "/repo" });
336​
337 assert.strictEqual(provider.kind, "azure-devops");
338 }),
339);
340​
341it.effect("falls back to a non-origin remote when origin is not configured", () =>
342 Effect.gen(function* () {
343 const registry = yield* makeRegistry({
344 remotes: [{ name: "upstream", url: "https://dev.azure.com/acme/project/_git/repo" }],
345 });
346​
347 const provider = yield* registry.resolve({ cwd: "/repo" });
348​
349 assert.strictEqual(provider.kind, "azure-devops");
350 }),
351);
352​
353it.effect(
354 "routes linked subjects by URL independently of the checkout and skips unsupported links",
355 () =>
356 Effect.gen(function* () {
357 const registry = yield* makeRegistry({
358 remotes: [{ name: "origin", url: "https://github.com/unrelated/checkout.git" }],
359 githubApi: {
360 rest: () =>
361 Effect.succeed({
362 status: 200,
363 headers: {},
364 body: JSON.stringify({ title: "GitHub issue", body: null }),
365 truncated: false,
366 invalidUtf8: false,
367 }),
368 },
369 gitlab: {
370 execute: () =>
371 Effect.succeed(
372 processOutput(JSON.stringify({ title: "GitLab MR", description: "Nested project" })),
373 ),
374 },
375 });
376 for (const [url, expected] of [
377 ["https://github.com/team/project/issues/1", { title: "GitHub issue", body: null }],
378 [
379 "https://gitlab.com/team/sub/project/-/merge_requests/2",
380 { title: "GitLab MR", body: "Nested project" },
381 ],
382 ] as const) {
383 const lookup = registry.resolveLink({ cwd: "/unrelated", url: new URL(url) });
384 assert.ok(lookup);
385 assert.deepStrictEqual(yield* lookup, expected);
386 }
387 for (const url of [
388 "https://example.test/team/project/issues/1",
389 "https://github.attacker.test/team/project/issues/1",
390 "https://gitlab.attacker.test/team/project/-/issues/1",
391 "https://github.com/team/project",
392 "https://codeberg.org/team/project/issues/1",
393 "https://bitbucket.org/team/project/pull-requests/1",
394 "https://dev.azure.com/org/project/_git/repo/pullrequest/1",
395 "http://github.com/team/project/issues/1",
396 "https://user:secret@github.com/team/project/issues/1",
397 ]) {
398 assert.strictEqual(
399 registry.resolveLink({ cwd: "/unrelated", url: new URL(url) }),
400 undefined,
401 );
402 }
403 }).pipe(Effect.scoped),
404);
405​
406it.effect.each([
407 { name: "a credential", credential: "found", expected: "github" },
408 // Claimed so the error says the host is turned off, not that it is unsupported.
409 { name: "a host turned off in Settings", credential: "disabled", expected: "github" },
410 { name: "no credential", credential: "missing", expected: "unknown" },
411] as const)("resolves custom-host remotes with $name", (scenario) =>
412 Effect.gen(function* () {
413 const hosts: Array<string> = [];
414 const commands: Array<string> = [];
415 const registry = yield* makeRegistry({
416 remotes: [{ name: "origin", url: "git@code.example.test:team/project.git" }],
417 process: {
418 run: ({ command }) => {
419 commands.push(command);
420 return Effect.succeed(processOutput(""));
421 },
422 },
423 githubApi: {
424 credential: (host) => {
425 hosts.push(host);
426 return scenario.credential === "found"
427 ? Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:fingerprint` })
428 : scenario.credential === "disabled"
429 ? Effect.fail(new GitHubCredentials.GitHubHostDisabledError({ host }))
430 : Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host }));
431 },
432 },
433 });
434 const handle = yield* registry.resolveHandle({ cwd: "/repo" });
435 assert.strictEqual(handle.provider.kind, SourceControlProviderKind.make(scenario.expected));
436 assert.strictEqual(handle.context?.provider.baseUrl, "https://code.example.test");
437 assert.deepStrictEqual(hosts, ["code.example.test"]);
438 // Recognition goes through the credential layer; gh is only one of its sources.
439 assert.notInclude(commands, "gh");
440 }),
441);
442​
443it.effect("skips GitHub discovery for the identity resolver's empty base URL", () =>
444 Effect.gen(function* () {
445 const hosts: string[] = [];
446 const remoteUrl = "git@githubenterprise.dev.example.com:team/workspace.git";
447 const registry = yield* makeRegistry({
448 remotes: [{ name: "origin", url: remoteUrl }],
449 githubApi: {
450 credential: (host) => {
451 hosts.push(host);
452 return Effect.succeed({
453 token: Redacted.make("token"),
454 fingerprint: `${host}:fingerprint`,
455 });
456 },
457 },
458 });
459 const context = {
460 provider: { kind: SourceControlProviderKind.make("unknown"), name: "Unknown", baseUrl: "" },
461 remoteName: "origin",
462 remoteUrl,
463 };
464 const unresolved = yield* registry.resolveHandle({ cwd: "/repo", context });
465 assert.deepStrictEqual(unresolved.context, context);
466 assert.deepStrictEqual(hosts, []);
467​
468 const resolved = yield* registry.resolveHandle({ cwd: "/repo" });
469 assert.strictEqual(resolved.provider.kind, "github");
470 assert.strictEqual(
471 resolved.context?.provider.baseUrl,
472 "https://githubenterprise.dev.example.com",
473 );
474 assert.deepStrictEqual(hosts, ["githubenterprise.dev.example.com"]);
475 }),
476);