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