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 { 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 );
106}
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 assert.strictEqual(error.detail, "No source control provider was detected for this project.");
146 assert.strictEqual(
147 error.message,
148 "Source control getChangeRequest failed: No source control provider was detected for this project.",
149 );
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 github: {
314 execute: () =>
315 Effect.succeed(processOutput(JSON.stringify({ title: "GitHub issue", body: null }))),
316 },
317 gitlab: {
318 execute: () =>
319 Effect.succeed(
320 processOutput(JSON.stringify({ title: "GitLab MR", description: "Nested project" })),
321 ),
322 },
323 });
324 for (const [url, expected] of [
325 ["https://github.com/team/project/issues/1", { title: "GitHub issue", body: null }],
326 [
327 "https://gitlab.com/team/sub/project/-/merge_requests/2",
328 { title: "GitLab MR", body: "Nested project" },
329 ],
330 ] as const) {
331 const lookup = registry.resolveLink({ cwd: "/unrelated", url: new URL(url) });
332 assert.ok(lookup);
333 assert.deepStrictEqual(yield* lookup, expected);
334 }
335 for (const url of [
336 "https://example.test/team/project/issues/1",
337 "https://github.attacker.test/team/project/issues/1",
338 "https://gitlab.attacker.test/team/project/-/issues/1",
339 "https://github.com/team/project",
340 "https://codeberg.org/team/project/issues/1",
341 "https://bitbucket.org/team/project/pull-requests/1",
342 "https://dev.azure.com/org/project/_git/repo/pullrequest/1",
343 "http://github.com/team/project/issues/1",
344 "https://user:secret@github.com/team/project/issues/1",
345 ]) {
346 assert.strictEqual(
347 registry.resolveLink({ cwd: "/unrelated", url: new URL(url) }),
348 undefined,
349 );
350 }
351 }).pipe(Effect.scoped),
352);