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

SourceControlProviderRegistry.test.ts

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