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

SourceControlProviderRegistry.test.ts

347 lines11.1 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 { ChildProcessSpawner } from "effect/unstable/process";
8import { VcsRepositoryDetectionError } from "@t3tools/contracts";
9​
10import * as ServerConfig from "../config.ts";
11import type * as VcsDriver from "../vcs/VcsDriver.ts";
12import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
13import * as VcsProcess from "../vcs/VcsProcess.ts";
14import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
15import * as BitbucketApi from "./BitbucketApi.ts";
16import * as GitHubCli from "./GitHubCli.ts";
17import * as GitLabCli from "./GitLabCli.ts";
18import * as ForgejoCli from "./ForgejoCli.ts";
19import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
20​
21const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
22​
23const processOutput = (
24 stdout: string,
25 options?: {
26 readonly stderr?: string;
27 readonly exitCode?: ChildProcessSpawner.ExitCode;
28 },
29): VcsProcess.VcsProcessOutput => ({
30 exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0),
31 stdout,
32 stderr: options?.stderr ?? "",
33 stdoutTruncated: false,
34 stderrTruncated: false,
35});
36​
37function makeRegistry(input: {
38 readonly remotes: ReadonlyArray<{
39 readonly name: string;
40 readonly url: string;
41 }>;
42 readonly process?: Partial<VcsProcess.VcsProcess["Service"]>;
43 readonly github?: Partial<GitHubCli.GitHubCli["Service"]>;
44 readonly gitlab?: Partial<GitLabCli.GitLabCli["Service"]>;
45 readonly resolve?: VcsDriverRegistry.VcsDriverRegistry["Service"]["resolve"];
46}) {
47 const driver = {
48 listRemotes: () =>
49 Effect.succeed({
50 remotes: input.remotes.map((remote) => ({
51 ...remote,
52 pushUrl: Option.none(),
53 isPrimary: remote.name === "origin",
54 })),
55 freshness: {
56 source: "live-local" as const,
57 observedAt: TEST_EPOCH,
58 expiresAt: Option.none(),
59 },
60 }),
61 } satisfies Partial<VcsDriver.VcsDriver["Service"]>;
62​
63 const registryLayer = Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
64 get: () => Effect.succeed(driver as unknown as VcsDriver.VcsDriver["Service"]),
65 resolve:
66 input.resolve ??
67 (() =>
68 Effect.succeed({
69 kind: "git",
70 repository: {
71 kind: "git",
72 rootPath: "/repo",
73 metadataPath: null,
74 freshness: {
75 source: "live-local" as const,
76 observedAt: TEST_EPOCH,
77 expiresAt: Option.none(),
78 },
79 },
80 driver: driver as unknown as VcsDriver.VcsDriver["Service"],
81 })),
82 });
83​
84 const processLayer = Layer.mock(VcsProcess.VcsProcess)({
85 run: () => Effect.succeed(processOutput("")),
86 ...input.process,
87 });
88​
89 return SourceControlProviderRegistry.make.pipe(
90 Effect.provide(
91 Layer.mergeAll(
92 NodeServices.layer,
93 registryLayer,
94 processLayer,
95 Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
96 Layer.mock(BitbucketApi.BitbucketApi)({}),
97 Layer.mock(GitHubCli.GitHubCli)(input.github ?? {}),
98 Layer.mock(GitLabCli.GitLabCli)(input.gitlab ?? {}),
99 Layer.mock(ForgejoCli.ForgejoCli)({ listLogins: () => Effect.succeed([]) }),
100 ServerConfig.layerTest(process.cwd(), {
101 prefix: "t3-source-control-registry-test-",
102 }).pipe(Layer.provide(NodeServices.layer)),
103 ),
104 ),
105 );
107​
108it.effect("routes GitHub remotes to the GitHub provider", () =>
109 Effect.gen(function* () {
110 const registry = yield* makeRegistry({
111 remotes: [{ name: "origin", url: "git@github.com:pingdotgg/t3code.git" }],
112 });
113​
114 const provider = yield* registry.resolve({ cwd: "/repo" });
115​
116 assert.strictEqual(provider.kind, "github");
117 }),
118);
119​
120it.effect("routes directly by provider kind for remote-first workflows", () =>
121 Effect.gen(function* () {
122 const registry = yield* makeRegistry({
123 remotes: [],
124 });
125​
126 const provider = yield* registry.get("github");
127​
128 assert.strictEqual(provider.kind, "github");
129 }),
130);
131​
132it.effect("includes the request cwd when an unregistered provider is used", () =>
133 Effect.gen(function* () {
134 const registry = yield* makeRegistry({ remotes: [] });
135 const provider = yield* registry.get("unknown");
136​
137 const error = yield* provider
138 .getChangeRequest({ cwd: "/repo", reference: "#42" })
139 .pipe(Effect.flip);
140​
141 assert.strictEqual(error.provider, "unknown");
142 assert.strictEqual(error.operation, "getChangeRequest");
143 assert.strictEqual(error.cwd, "/repo");
144 assert.strictEqual(error.reference, "#42");
145 }),
146);
147​
148it.effect("retains VCS detection failures with structured cwd context", () =>
149 Effect.gen(function* () {
150 const cause = new VcsRepositoryDetectionError({
151 operation: "resolve",
152 cwd: "/repo",
153 detail: "raw VCS detection failure",
154 cause: new Error("raw nested failure"),
155 });
156 const registry = yield* makeRegistry({
157 remotes: [],
158 resolve: () => Effect.fail(cause),
159 });
160​
161 const error = yield* registry.resolve({ cwd: "/repo" }).pipe(Effect.flip);
162​
163 assert.strictEqual(error.provider, "unknown");
164 assert.strictEqual(error.operation, "detectProvider");
165 assert.strictEqual(error.cwd, "/repo");
166 assert.strictEqual(error.detail, "Failed to detect source control provider.");
167 assert.strictEqual(error.cause, cause);
168 assert.equal(error.message.includes(cause.message), false);
169 }),
170);
171​
172it.effect("routes GitLab remotes to the GitLab provider", () =>
173 Effect.gen(function* () {
174 const registry = yield* makeRegistry({
175 remotes: [{ name: "origin", url: "git@gitlab.com:group/project.git" }],
176 });
177​
178 const provider = yield* registry.resolve({ cwd: "/repo" });
179​
180 assert.strictEqual(provider.kind, "gitlab");
181 }),
182);
183​
184it.effect("routes authenticated self-hosted GitLab remotes without relying on host naming", () =>
185 Effect.gen(function* () {
186 const registry = yield* makeRegistry({
187 remotes: [{ name: "origin", url: "https://self-hosted.example.test/group/project.git" }],
188 process: {
189 run: () =>
190 Effect.succeed(
191 processOutput(
192 `gitlab.com
193 x gitlab.com: API call failed: 401 Unauthorized
194 ! No token found
195self-hosted.example.test
196 ✓ Logged in to self-hosted.example.test as gitlab-user
197 ✓ Token found: ******
198`,
199 { exitCode: ChildProcessSpawner.ExitCode(1) },
200 ),
201 ),
202 },
203 });
204​
205 const provider = yield* registry.resolve({ cwd: "/repo" });
206​
207 assert.strictEqual(provider.kind, "gitlab");
208 }),
209);
210​
211it.effect("refines the caller-selected remote instead of choosing another configured remote", () =>
212 Effect.gen(function* () {
213 const registry = yield* makeRegistry({
214 remotes: [{ name: "origin", url: "git@github.com:fork/project.git" }],
215 process: {
216 run: () =>
217 Effect.succeed(
218 processOutput(`self-hosted.example.test
219 ✓ Logged in to self-hosted.example.test as gitlab-user
220`),
221 ),
222 },
223 });
224​
225 const handle = yield* registry.resolveHandle({
226 cwd: "/repo",
227 context: {
228 provider: {
229 kind: "unknown",
230 name: "self-hosted.example.test",
231 baseUrl: "https://self-hosted.example.test",
232 },
233 remoteName: "upstream",
234 remoteUrl: "https://self-hosted.example.test/group/project.git",
235 },
236 });
237​
238 assert.strictEqual(handle.context?.provider.kind, "gitlab");
239 assert.strictEqual(handle.context?.remoteName, "upstream");
240 }),
241);
242​
243it.effect("routes authenticated self-hosted GitLab remotes on non-standard ports", () =>
244 Effect.gen(function* () {
245 const registry = yield* makeRegistry({
246 remotes: [{ name: "origin", url: "https://self-hosted.example.test:8443/group/project.git" }],
247 process: {
248 run: () =>
249 Effect.succeed(
250 processOutput(
251 `self-hosted.example.test:8443
252 ✓ Logged in to self-hosted.example.test:8443 as gitlab-user
253 ✓ Token found: ******
254`,
255 ),
256 ),
257 },
258 });
259​
260 const provider = yield* registry.resolve({ cwd: "/repo" });
261​
262 assert.strictEqual(provider.kind, "gitlab");
263 }),
264);
265​
266it.effect("routes Bitbucket remotes to the Bitbucket provider", () =>
267 Effect.gen(function* () {
268 const registry = yield* makeRegistry({
269 remotes: [{ name: "origin", url: "git@bitbucket.org:pingdotgg/t3code.git" }],
270 });
271​
272 const provider = yield* registry.resolve({ cwd: "/repo" });
273​
274 assert.strictEqual(provider.kind, "bitbucket");
275 }),
276);
277​
278it.effect("routes Azure DevOps remotes to the Azure DevOps provider", () =>
279 Effect.gen(function* () {
280 const registry = yield* makeRegistry({
281 remotes: [{ name: "origin", url: "https://dev.azure.com/acme/project/_git/repo" }],
282 });
283​
284 const provider = yield* registry.resolve({ cwd: "/repo" });
285​
286 assert.strictEqual(provider.kind, "azure-devops");
287 }),
288);
289​
290it.effect("falls back to a non-origin remote when origin is not configured", () =>
291 Effect.gen(function* () {
292 const registry = yield* makeRegistry({
293 remotes: [{ name: "upstream", url: "https://dev.azure.com/acme/project/_git/repo" }],
294 });
295​
296 const provider = yield* registry.resolve({ cwd: "/repo" });
297​
298 assert.strictEqual(provider.kind, "azure-devops");
299 }),
300);
301​
302it.effect(
303 "routes linked subjects by URL independently of the checkout and skips unsupported links",
304 () =>
305 Effect.gen(function* () {
306 const registry = yield* makeRegistry({
307 remotes: [{ name: "origin", url: "https://github.com/unrelated/checkout.git" }],
308 github: {
309 execute: () =>
310 Effect.succeed(processOutput(JSON.stringify({ title: "GitHub issue", body: null }))),
311 },
312 gitlab: {
313 execute: () =>
314 Effect.succeed(
315 processOutput(JSON.stringify({ title: "GitLab MR", description: "Nested project" })),
316 ),
317 },
318 });
319 for (const [url, expected] of [
320 ["https://github.com/team/project/issues/1", { title: "GitHub issue", body: null }],
321 [
322 "https://gitlab.com/team/sub/project/-/merge_requests/2",
323 { title: "GitLab MR", body: "Nested project" },
324 ],
325 ] as const) {
326 const lookup = registry.resolveLink({ cwd: "/unrelated", url: new URL(url) });
327 assert.ok(lookup);
328 assert.deepStrictEqual(yield* lookup, expected);
329 }
330 for (const url of [
331 "https://example.test/team/project/issues/1",
332 "https://github.attacker.test/team/project/issues/1",
333 "https://gitlab.attacker.test/team/project/-/issues/1",
334 "https://github.com/team/project",
335 "https://codeberg.org/team/project/issues/1",
336 "https://bitbucket.org/team/project/pull-requests/1",
337 "https://dev.azure.com/org/project/_git/repo/pullrequest/1",
338 "http://github.com/team/project/issues/1",
339 "https://user:secret@github.com/team/project/issues/1",
340 ]) {
341 assert.strictEqual(
342 registry.resolveLink({ cwd: "/unrelated", url: new URL(url) }),
343 undefined,
344 );
345 }
346 }).pipe(Effect.scoped),
347);