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

SourceControlProviderRegistry.test.ts

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