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