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

SourceControlProviderRegistry.test.ts

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