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

SourceControlProviderRegistry.test.ts

456 lines16.0 KB

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