Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { changeRequestUrlFor } from "@t3tools/shared/changeRequestUrl";
3import {
4 detectSourceControlProviderFromGitRemoteUrl,
5 normalizeGitRemoteUrl,
6} from "@t3tools/shared/git";
7import { refineUnknownRemoteProvider } from "@t3tools/source-control-core/server/discovery";
8import { processOutput } from "@t3tools/source-control-testing/TestSourceControlHost";
9import { assert, it } from "@effect/vitest";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import { ChildProcessSpawner } from "effect/process";
14
15import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
16import * as GitLabCli from "./GitLabCli.ts";
17import { parseGitLabAuthStatusHosts } from "./gitLabAuthStatus.ts";
18import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
19
20function makeProvider(gitlab: Partial<GitLabCli.GitLabCli["Service"]>) {
21 return GitLabSourceControlProvider.make.pipe(
22 Effect.provide(
23 Layer.mergeAll(Layer.mock(GitLabCli.GitLabCli)(gitlab), TestSourceControlHost.layer()),
24 ),
25 );
26}
27
28it.effect("maps GitLab MR summaries into provider-neutral change requests", () =>
29 Effect.gen(function* () {
30 const provider = yield* makeProvider({
31 getMergeRequest: () =>
32 Effect.succeed({
33 number: 42,
34 title: "Add GitLab provider",
35 url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
36 baseRefName: "main",
37 headRefName: "feature/source-control",
38 headSha: "a".repeat(40),
39 state: "closed",
40 closedAt: "2026-08-23T10:00:00Z",
41 isCrossRepository: true,
42 headRepositoryNameWithOwner: "fork/t3code",
43 headRepositoryOwnerLogin: "fork",
44 }),
45 });
46
47 const changeRequest = yield* provider.getChangeRequest({
48 cwd: "/repo",
49 reference: "42",
50 });
51
52 assert.deepStrictEqual(changeRequest, {
53 provider: SourceControlProviderKind.make("gitlab"),
54 number: 42,
55 title: "Add GitLab provider",
56 url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
57 baseRefName: "main",
58 headRefName: "feature/source-control",
59 headSha: "a".repeat(40),
60 state: "closed",
61 closedAt: "2026-08-23T10:00:00Z",
62 mergedAt: null,
63 updatedAt: Option.none(),
64 isCrossRepository: true,
65 headRepositoryNameWithOwner: "fork/t3code",
66 headRepositoryOwnerLogin: "fork",
67 });
68 }),
69);
70
71it.effect("adds repository context while retaining GitLab CLI causes", () =>
72 Effect.gen(function* () {
73 const cause = new GitLabCli.GitLabCliCommandError({
74 operation: "execute",
75 command: "glab",
76 cwd: "/repo",
77 cause: new Error("raw upstream detail that should remain in the cause"),
78 });
79 const provider = yield* makeProvider({
80 createRepository: () => Effect.fail(cause),
81 });
82
83 const error = yield* provider
84 .createRepository({
85 cwd: "/repo",
86 repository: "owner/repo",
87 visibility: "private",
88 })
89 .pipe(Effect.flip);
90
91 assert.deepStrictEqual(
92 {
93 provider: error.provider,
94 operation: error.operation,
95 command: error.command,
96 cwd: error.cwd,
97 repository: error.repository,
98 detail: error.detail,
99 },
100 {
101 provider: "gitlab",
102 operation: "createRepository",
103 command: "glab",
104 cwd: "/repo",
105 repository: "owner/repo",
106 detail: "GitLab CLI command failed.",
107 },
108 );
109 assert.strictEqual(error.cause, cause);
110 assert.equal(error.message.includes("raw upstream detail"), false);
111 }),
112);
113
114it.effect("lists GitLab MRs through provider-neutral input names", () =>
115 Effect.gen(function* () {
116 let listInput: Parameters<GitLabCli.GitLabCli["Service"]["listMergeRequests"]>[0] | null = null;
117 const provider = yield* makeProvider({
118 listMergeRequests: (input) => {
119 listInput = input;
120 return Effect.succeed([]);
121 },
122 });
123
124 yield* provider.listChangeRequests({
125 cwd: "/repo",
126 headSelector: "feature/provider",
127 state: "all",
128 limit: 10,
129 });
130
131 assert.deepStrictEqual(listInput, {
132 cwd: "/repo",
133 headSelector: "feature/provider",
134 state: "all",
135 limit: 10,
136 });
137 }),
138);
139
140it.effect("creates GitLab MRs through provider-neutral input names", () =>
141 Effect.gen(function* () {
142 let createInput: Parameters<GitLabCli.GitLabCli["Service"]["createMergeRequest"]>[0] | null =
143 null;
144 const provider = yield* makeProvider({
145 createMergeRequest: (input) => {
146 createInput = input;
147 return Effect.void;
148 },
149 });
150
151 yield* provider.createChangeRequest({
152 cwd: "/repo",
153 baseRefName: "main",
154 headSelector: "owner:feature/provider",
155 title: "Provider MR",
156 bodyFile: "/tmp/body.md",
157 });
158
159 assert.deepStrictEqual(createInput, {
160 cwd: "/repo",
161 baseBranch: "main",
162 headSelector: "owner:feature/provider",
163 source: {
164 owner: "owner",
165 refName: "feature/provider",
166 },
167 title: "Provider MR",
168 bodyFile: "/tmp/body.md",
169 });
170 }),
171);
172
173it("accepts authenticated GitLab hosts when another configured host fails", () => {
174 const auth = GitLabSourceControlProvider.discovery.parseAuth({
175 exitCode: ChildProcessSpawner.ExitCode(1),
176 stdout: `gitlab.com
177 x gitlab.com: API call failed: 401 Unauthorized
178 ! No token found
179self-hosted.example.test
180 ✓ Logged in to self-hosted.example.test as gitlab-user
181 ✓ Token found: ******
182`,
183 stderr: "",
184 });
185
186 assert.deepStrictEqual(
187 {
188 status: auth.status,
189 account: auth.account,
190 host: auth.host,
191 },
192 {
193 status: "authenticated",
194 account: Option.some("gitlab-user"),
195 host: Option.some("self-hosted.example.test"),
196 },
197 );
198});
199
200it("refines unknown GitLab remotes with mixed-case provider hosts", () => {
201 const provider = GitLabSourceControlProvider.discovery.refineUnknownRemote?.({
202 cwd: "/repo",
203 context: {
204 provider: {
205 kind: SourceControlProviderKind.make("unknown"),
206 name: "Self-Hosted.Example.Test",
207 baseUrl: "https://Self-Hosted.Example.Test",
208 },
209 remoteName: "origin",
210 remoteUrl: "https://Self-Hosted.Example.Test/group/project.git",
211 },
212 auth: {
213 exitCode: ChildProcessSpawner.ExitCode(0),
214 stdout: `self-hosted.example.test
215 ✓ Logged in to self-hosted.example.test as gitlab-user
216 ✓ Token found: ******
217`,
218 stderr: "",
219 },
220 });
221
222 assert.deepStrictEqual(provider, {
223 kind: "gitlab",
224 name: "GitLab Self-Hosted",
225 baseUrl: "https://Self-Hosted.Example.Test",
226 });
227});
228
229it("tells a host glab has no login for apart from output that cannot say", () => {
230 const refine = (stderr: string) =>
231 GitLabSourceControlProvider.discovery.refineUnknownRemote?.({
232 cwd: "/repo",
233 context: {
234 provider: {
235 kind: SourceControlProviderKind.make("unknown"),
236 name: "git.example.test",
237 baseUrl: "https://git.example.test",
238 },
239 remoteName: "origin",
240 remoteUrl: "https://git.example.test/group/project.git",
241 },
242 auth: { exitCode: ChildProcessSpawner.ExitCode(1), stdout: "", stderr },
243 });
244
245 assert.strictEqual(
246 refine("x git.example.test has not been authenticated with glab. Run `glab auth login`"),
247 null,
248 );
249 assert.strictEqual(
250 refine("No GitLab instances have been authenticated with glab. Run `glab auth login`"),
251 null,
252 );
253 assert.strictEqual(refine("git.example.test\n x API call failed: 503"), undefined);
254});
255
256it.effect.each([
257 [
258 "https://code.example.test:8443@Code.Example.Test:8443/Team/Repo.git",
259 true,
260 "gitlab",
261 "Code.Example.Test:8443",
262 ],
263 ["git@code.example.test:team/repo.git", true, "gitlab"],
264 ["code.example.test:team/repo.git", true, "gitlab"],
265 ["git@code.example.test:/team/repo.git", true, "gitlab"],
266 ["https://code.example.test/team/repo.git", false, "unknown"],
267 ["https://github.com/team/repo.git", true, "github"],
268] as const)(
269 "resolves MR numbers for %s with authenticated=%s as %s",
270 ([remoteUrl, authenticated, expectedProvider, expectedAuthHost = "code.example.test"]) =>
271 Effect.gen(function* () {
272 const provider = yield* makeProvider({});
273 const identity = {
274 canonicalKey: normalizeGitRemoteUrl(remoteUrl),
275 locator: { source: "git-remote" as const, remoteName: "upstream", remoteUrl },
276 rootPath: "/repo",
277 provider: detectSourceControlProviderFromGitRemoteUrl(remoteUrl)?.kind ?? "unknown",
278 };
279 let authCalls = 0;
280 const refined = yield* (
281 provider.refineRepositoryIdentity?.({
282 identity,
283 resolveContext: (input) =>
284 refineUnknownRemoteProvider({
285 ...input,
286 specs: [GitLabSourceControlProvider.discovery],
287 process: {
288 run: ({ command, args, cwd }) => {
289 authCalls++;
290 assert.deepStrictEqual(
291 { command, args, cwd },
292 {
293 command: "glab",
294 args: ["auth", "status", "--hostname", expectedAuthHost],
295 cwd: "/repo",
296 },
297 );
298 return Effect.succeed(
299 processOutput(
300 authenticated
301 ? `${expectedAuthHost}\n ✓ Logged in to ${expectedAuthHost} as gitlab-user\n`
302 : "x code.example.test has not been authenticated with glab.",
303 { exitCode: ChildProcessSpawner.ExitCode(authenticated ? 0 : 1) },
304 ),
305 );
306 },
307 },
308 }).pipe(
309 Effect.map(({ provider }) =>
310 provider ? { ...input.context, provider } : input.context,
311 ),
312 ),
313 }) ?? Effect.succeed(identity)
314 );
315 const [host, ...repository] = refined.canonicalKey.split("/");
316 assert.strictEqual(
317 changeRequestUrlFor(refined.provider, host!, repository.join("/"), 42),
318 expectedProvider === "gitlab"
319 ? "https://code.example.test/team/repo/-/merge_requests/42"
320 : expectedProvider === "github"
321 ? "https://github.com/team/repo/pull/42"
322 : null,
323 );
324 assert.deepStrictEqual(refined, { ...identity, provider: expectedProvider });
325 if (expectedProvider === "github") assert.strictEqual(authCalls, 0);
326 }),
327);
328
329it("parses authenticated GitLab auth status hosts with ports and single-label names", () => {
330 assert.deepStrictEqual(
331 parseGitLabAuthStatusHosts(`localhost:8080
332 ✓ Logged in to localhost:8080 as local-user
333selfhosted
334 ✓ Logged in to selfhosted as single-label-user
335`),
336 [
337 { host: "localhost:8080", account: "local-user" },
338 { host: "selfhosted", account: "single-label-user" },
339 ],
340 );
341});
342
343it.effect.each(["merge_requests", "issues"])(
344 "resolves %s subjects on the linked host without using the checkout",
345 (kind) =>
346 Effect.gen(function* () {
347 const provider = yield* makeProvider({
348 execute: (input) => {
349 assert.deepStrictEqual(input.args, [
350 "api",
351 "--hostname",
352 "gitlab.com",
353 `projects/group%2Fsubgroup%2Fproject/${kind}/42`,
354 ]);
355 assert.strictEqual(input.maxOutputBytes, 32_000);
356 assert.strictEqual(input.timeoutMs, 3_000);
357 return Effect.succeed({
358 exitCode: ChildProcessSpawner.ExitCode(0),
359 stdout: JSON.stringify({
360 title: "Pairing expiry",
361 description: "Preserve remote access",
362 }),
363 stderr: "",
364 stdoutTruncated: false,
365 stderrTruncated: false,
366 });
367 },
368 });
369 const lookup = provider.resolveLink?.({
370 cwd: "/unrelated",
371 url: new URL(`https://gitlab.com/group/subgroup/project/-/${kind}/42`),
372 });
373 assert.ok(lookup);
374 assert.deepStrictEqual(yield* lookup, {
375 title: "Pairing expiry",
376 body: "Preserve remote access",
377 });
378 assert.strictEqual(
379 provider.resolveLink?.({
380 cwd: "/unrelated",
381 url: new URL("https://gitlab.com/owner/repo"),
382 }),
383 undefined,
384 );
385 }),
386);
387
388it.effect.each(["read", "decode"] as const)(
389 "retains the %s failure without exposing its raw contents",
390 (stage) =>
391 Effect.gen(function* () {
392 const cause = new GitLabCli.GitLabCliCommandError({
393 command: "glab",
394 cwd: "/repo",
395 operation: "execute",
396 cause: new Error("private response text"),
397 });
398 const provider = yield* makeProvider({
399 execute: () =>
400 stage === "read"
401 ? Effect.fail(cause)
402 : Effect.succeed({
403 exitCode: ChildProcessSpawner.ExitCode(0),
404 stdout: "private response text",
405 stderr: "",
406 stdoutTruncated: false,
407 stderrTruncated: false,
408 }),
409 });
410 const lookup = provider.resolveLink?.({
411 cwd: "/repo",
412 url: new URL("https://gitlab.com/owner/repo/-/issues/42"),
413 });
414 assert.ok(lookup);
415 const error = yield* Effect.flip(lookup);
416 assert.strictEqual(error.operation, stage === "read" ? "resolveLink" : "resolveLink.decode");
417 assert.strictEqual(error.detail, "The linked subject could not be read.");
418 assert.notInclude(error.message, "private response text");
419 if (stage === "read") assert.strictEqual(error.cause, cause);
420 else assert.propertyVal(error.cause, "_tag", "SchemaError");
421 }),
422);