Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it, afterEach, expect, vi } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Path from "effect/Path";
7import { ChildProcessSpawner } from "effect/process";
8
9import { VcsProcessExitError } from "@t3tools/contracts";
10
11import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
12import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
13import * as GitLabCli from "./GitLabCli.ts";
14
15const mockedRun = vi.fn<SourceControlHost.SourceControlHost["Service"]["process"]["run"]>();
16const layer = it.layer(
17 GitLabCli.layer.pipe(
18 Layer.provide(TestSourceControlHost.layer({ process: { run: mockedRun } })),
19 Layer.provideMerge(NodeServices.layer),
20 ),
21);
22
23function processOutput(stdout: string): SourceControlHost.SourceControlProcessOutput {
24 return {
25 exitCode: ChildProcessSpawner.ExitCode(0),
26 stdout,
27 stderr: "",
28 stdoutTruncated: false,
29 stderrTruncated: false,
30 };
31}
32
33afterEach(() => {
34 mockedRun.mockReset();
35});
36
37layer("GitLabCli.layer", (it) => {
38 it.effect("parses merge request view output", () =>
39 Effect.gen(function* () {
40 mockedRun.mockReturnValueOnce(
41 Effect.succeed(
42 processOutput(
43 JSON.stringify({
44 iid: 42,
45 title: "Add MR thread creation",
46 web_url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
47 target_branch: "main",
48 source_branch: "feature/mr-threads",
49 sha: "a".repeat(40),
50 state: "closed",
51 closed_at: "2026-08-23T10:00:00Z",
52 source_project_id: 101,
53 target_project_id: 100,
54 source_project: {
55 path_with_namespace: "octocat/t3code",
56 },
57 }),
58 ),
59 ),
60 );
61
62 const result = yield* Effect.gen(function* () {
63 const glab = yield* GitLabCli.GitLabCli;
64 return yield* glab.getMergeRequest({
65 cwd: "/repo",
66 reference: "42",
67 });
68 });
69
70 assert.deepStrictEqual(result, {
71 number: 42,
72 title: "Add MR thread creation",
73 url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
74 baseRefName: "main",
75 headRefName: "feature/mr-threads",
76 headSha: "a".repeat(40),
77 state: "closed",
78 closedAt: "2026-08-23T10:00:00Z",
79 mergedAt: null,
80 isCrossRepository: true,
81 headRepositoryNameWithOwner: "octocat/t3code",
82 headRepositoryOwnerLogin: "octocat",
83 });
84 expect(mockedRun).toHaveBeenCalledWith(
85 expect.objectContaining({
86 command: "glab",
87 cwd: "/repo",
88 args: ["mr", "view", "--output", "json", "--", "42"],
89 }),
90 );
91 const classifyFailure = mockedRun.mock.calls.at(-1)?.[0].classifyFailure;
92 assert.strictEqual(
93 classifyFailure?.(
94 "x gitlab.example.test has not been authenticated with glab. Run `glab auth login`",
95 ),
96 "authentication",
97 );
98 assert.strictEqual(
99 classifyFailure?.(
100 'Failed to get merge request 42: oauth2: "invalid_grant" "The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client."',
101 ),
102 "authentication",
103 );
104 }),
105 );
106
107 // A strictly confined glab (Snap) has a private /tmp, so it cannot open the server's body file.
108 it.effect("sends the merge request description to glab on stdin, not as a file path", () =>
109 Effect.gen(function* () {
110 const fileSystem = yield* FileSystem.FileSystem;
111 const path = yield* Path.Path;
112 const bodyDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-gitlab-mr-body-" });
113 const bodyFile = path.join(bodyDir, "t3code-pr-body.md");
114 yield* fileSystem.writeFileString(bodyFile, "## Summary\n\nFixes the thing.\n");
115 mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
116
117 const glab = yield* GitLabCli.GitLabCli;
118 yield* glab.createMergeRequest({
119 cwd: "/repo",
120 baseBranch: "main",
121 headSelector: "feature/mr",
122 title: "Add MR",
123 bodyFile,
124 });
125
126 const call = mockedRun.mock.calls.at(-1)?.[0];
127 expect(call?.args.join(" ")).not.toContain(bodyFile);
128 expect(call?.args).toContain("description=@-");
129 assert.strictEqual(call?.stdin, "## Summary\n\nFixes the thing.\n");
130 }).pipe(Effect.scoped),
131 );
132
133 it.effect("fails with a typed error and skips glab when the description cannot be read", () =>
134 Effect.gen(function* () {
135 const fileSystem = yield* FileSystem.FileSystem;
136 const path = yield* Path.Path;
137 const bodyDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-gitlab-mr-body-" });
138 const glab = yield* GitLabCli.GitLabCli;
139 const error = yield* glab
140 .createMergeRequest({
141 cwd: "/repo",
142 baseBranch: "main",
143 headSelector: "feature/mr",
144 title: "Add MR",
145 bodyFile: path.join(bodyDir, "missing.md"),
146 })
147 .pipe(Effect.flip);
148
149 assert.strictEqual(error._tag, "GitLabMergeRequestBodyReadError");
150 assert.strictEqual(error.detail, "The merge request description could not be read.");
151 expect(mockedRun).not.toHaveBeenCalled();
152 }).pipe(Effect.scoped),
153 );
154
155 it.effect("skips invalid entries when parsing MR lists", () =>
156 Effect.gen(function* () {
157 mockedRun.mockReturnValueOnce(
158 Effect.succeed(
159 processOutput(
160 JSON.stringify([
161 {
162 iid: 0,
163 title: "invalid",
164 web_url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/0",
165 target_branch: "main",
166 source_branch: "feature/invalid",
167 },
168 {
169 iid: 43,
170 title: " Valid MR ",
171 web_url: " https://gitlab.com/pingdotgg/t3code/-/merge_requests/43 ",
172 target_branch: " main ",
173 source_branch: " feature/mr-list ",
174 state: "merged",
175 merged_at: "2026-08-23T11:00:00Z",
176 },
177 ]),
178 ),
179 ),
180 );
181
182 const result = yield* Effect.gen(function* () {
183 const glab = yield* GitLabCli.GitLabCli;
184 return yield* glab.listMergeRequests({
185 cwd: "/repo",
186 headSelector: "feature/mr-list",
187 state: "all",
188 });
189 });
190
191 assert.deepStrictEqual(result, [
192 {
193 number: 43,
194 title: "Valid MR",
195 url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/43",
196 baseRefName: "main",
197 headRefName: "feature/mr-list",
198 state: "merged",
199 closedAt: null,
200 mergedAt: "2026-08-23T11:00:00Z",
201 },
202 ]);
203 expect(mockedRun).toHaveBeenCalledWith(
204 expect.objectContaining({
205 command: "glab",
206 cwd: "/repo",
207 args: [
208 "mr",
209 "list",
210 "--source-branch",
211 "feature/mr-list",
212 "--all",
213 "--per-page",
214 "20",
215 "--output",
216 "json",
217 ],
218 }),
219 );
220 }),
221 );
222
223 it.effect(
224 "retries oversized MR lists with smaller pages without losing same-named branches",
225 () =>
226 Effect.gen(function* () {
227 const entries = Array.from({ length: 4 }, (_, index) => ({
228 iid: index + 1,
229 title: "MR " + index,
230 // The first alone escapes past the default 1 MB cap; together they pass the list cap.
231 description: index === 0 ? '"'.repeat(600_000) : "x".repeat(3_000_000),
232 web_url: "https://gitlab.com/acme/web/-/merge_requests/" + (index + 1),
233 target_branch: "main",
234 source_branch: "feature",
235 source_project_id: index === 3 ? 100 : 101,
236 target_project_id: 100,
237 }));
238 mockedRun.mockImplementation((input) => {
239 const size = Number(input.args[input.args.indexOf("--per-page") + 1]);
240 const pageIndex = input.args.indexOf("--page");
241 const page = pageIndex < 0 ? 1 : Number(input.args[pageIndex + 1]);
242 const raw = JSON.stringify(entries.slice((page - 1) * size, page * size));
243 const cap = input.maxOutputBytes ?? 1_000_000;
244 return Effect.succeed({
245 ...processOutput(raw.slice(0, cap)),
246 stdoutTruncated: raw.length > cap,
247 });
248 });
249 const glab = yield* GitLabCli.GitLabCli;
250 const result = yield* glab.listMergeRequests({
251 cwd: "/repo",
252 headSelector: "feature",
253 state: "open",
254 limit: 4,
255 });
256 assert.deepStrictEqual(
257 result.map((mr) => mr.number),
258 [1, 2, 3, 4],
259 );
260 assert.strictEqual(result[3]?.isCrossRepository, false);
261 }),
262 );
263
264 it.effect("creates same-project MRs without a repository lookup", () =>
265 Effect.gen(function* () {
266 const fileSystem = yield* FileSystem.FileSystem;
267 const bodyFile = yield* fileSystem.makeTempFileScoped({ prefix: "t3-gitlab-mr-body-" });
268 mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
269 const glab = yield* GitLabCli.GitLabCli;
270 yield* glab.createMergeRequest({
271 cwd: "/repo",
272 baseBranch: "main",
273 headSelector: "feature/fix",
274 title: "Fix remote flow",
275 bodyFile,
276 });
277 expect(mockedRun).toHaveBeenCalledExactlyOnceWith(
278 expect.objectContaining({
279 args: [
280 "api",
281 "--method",
282 "POST",
283 "projects/:fullpath/merge_requests",
284 "--raw-field",
285 "source_branch=feature/fix",
286 "--raw-field",
287 "target_branch=main",
288 "--raw-field",
289 "title=Fix remote flow",
290 "--field",
291 "description=@-",
292 ],
293 }),
294 );
295 }).pipe(Effect.scoped),
296 );
297
298 it.effect("surfaces a friendly error when the merge request is not found", () =>
299 Effect.gen(function* () {
300 const cause = new VcsProcessExitError({
301 operation: "GitLabCli.execute",
302 command: "glab",
303 cwd: "/repo",
304 exitCode: 1,
305 detail: "GET 404 merge request not found",
306 failureKind: "not-found",
307 });
308 mockedRun.mockReturnValueOnce(Effect.fail(cause));
309
310 const error = yield* Effect.gen(function* () {
311 const glab = yield* GitLabCli.GitLabCli;
312 return yield* glab.getMergeRequest({
313 cwd: "/repo",
314 reference: "4888",
315 });
316 }).pipe(Effect.flip);
317
318 assert.equal(error.message.includes("Merge request 4888 was not found"), true);
319 assert.strictEqual(error._tag, "GitLabMergeRequestNotFoundError");
320 assert.strictEqual(error.command, "glab");
321 assert.strictEqual(error.cwd, "/repo");
322 assert.strictEqual(error.cause, cause);
323 assert.equal(error.message.includes(cause.detail), false);
324 }),
325 );
326
327 it.effect.each([
328 { repository: "group/project", args: ["api", "projects/group%2Fproject"] },
329 {
330 repository: "https://gitlab.example.com:8443/group/sub/project.git",
331 args: ["api", "--hostname", "gitlab.example.com:8443", "projects/group%2Fsub%2Fproject"],
332 },
333 {
334 repository: "https://gitlab.com/group/project/-/tree/main",
335 args: ["api", "--hostname", "gitlab.com", "projects/group%2Fproject"],
336 },
337 ])("looks up $repository by its project path", ({ repository, args }) =>
338 Effect.gen(function* () {
339 mockedRun.mockReturnValueOnce(
340 Effect.succeed(
341 processOutput(
342 JSON.stringify({
343 path_with_namespace: "group/project",
344 web_url: "https://sourcecontrol.example.com/group/project",
345 http_url_to_repo: "https://sourcecontrol.example.com/group/project.git",
346 ssh_url_to_repo: "git@sourcecontrol.example.com:group/project.git",
347 }),
348 ),
349 ),
350 );
351
352 const glab = yield* GitLabCli.GitLabCli;
353 yield* glab.getRepositoryCloneUrls({ cwd: "/repo", repository });
354
355 expect(mockedRun).toHaveBeenCalledWith(expect.objectContaining({ command: "glab", args }));
356 }),
357 );
358
359 it.effect("keeps non-merge-request not-found failures generic", () =>
360 Effect.gen(function* () {
361 const cause = new VcsProcessExitError({
362 operation: "GitLabCli.execute",
363 command: "glab",
364 cwd: "/repo",
365 exitCode: 1,
366 detail: "GET 404 project not found",
367 failureKind: "not-found",
368 });
369 mockedRun.mockReturnValueOnce(Effect.fail(cause));
370
371 const error = yield* Effect.gen(function* () {
372 const glab = yield* GitLabCli.GitLabCli;
373 return yield* glab.getRepositoryCloneUrls({
374 cwd: "/repo",
375 repository: "missing/project",
376 });
377 }).pipe(Effect.flip);
378
379 assert.strictEqual(error._tag, "GitLabCliCommandError");
380 assert.strictEqual(error.cause, cause);
381 }),
382 );
383
384 it.effect("preserves rate-limit failures as a distinct error", () =>
385 Effect.gen(function* () {
386 const cause = new VcsProcessExitError({
387 operation: "GitLabCli.execute",
388 command: "glab",
389 cwd: "/repo",
390 exitCode: 1,
391 detail: "API rate limit exceeded.",
392 failureKind: "rate-limited",
393 });
394 mockedRun.mockReturnValueOnce(Effect.fail(cause));
395
396 const glab = yield* GitLabCli.GitLabCli;
397 const error = yield* glab
398 .execute({ cwd: "/repo", args: ["api", "projects"] })
399 .pipe(Effect.flip);
400
401 assert.strictEqual(error._tag, "GitLabCliRateLimitError");
402 assert.strictEqual(error.cause, cause);
403 }),
404 );
405});