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