Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitLabCli.test.ts

512 lines18.0 KB

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 * as HostProcess from "@t3tools/shared/HostProcess";
12import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
13import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
14import * as GitLabCli from "./GitLabCli.ts";
15import { userFacingSourceControlDetail } from "@t3tools/source-control-core/server/SourceControlProvider";
16​
17const mockedRun = vi.fn<SourceControlHost.SourceControlHost["Service"]["process"]["run"]>();
18const layer = it.layer(
19 GitLabCli.layer.pipe(
20 Layer.provide(TestSourceControlHost.layer({ process: { run: mockedRun } })),
21 Layer.provideMerge(NodeServices.layer),
22 ),
23);
24​
25function processOutput(stdout: string): SourceControlHost.SourceControlProcessOutput {
26 return {
27 exitCode: ChildProcessSpawner.ExitCode(0),
28 stdout,
29 stderr: "",
30 stdoutTruncated: false,
31 stderrTruncated: false,
32 };
34​
35afterEach(() => {
36 mockedRun.mockReset();
37});
38​
39layer("GitLabCli.layer", (it) => {
40 it.effect("parses merge request view output", () =>
41 Effect.gen(function* () {
42 mockedRun.mockReturnValueOnce(
43 Effect.succeed(
44 processOutput(
45 JSON.stringify({
46 iid: 42,
47 title: "Add MR thread creation",
48 web_url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
49 target_branch: "main\u00a0",
50 source_branch: "feature/mr-threads",
51 sha: "a".repeat(40),
52 state: "closed",
53 closed_at: "2026-08-23T10:00:00Z",
54 source_project_id: 101,
55 target_project_id: 100,
56 source_project: {
57 path_with_namespace: "octocat/t3code",
58 },
59 }),
60 ),
61 ),
62 );
63​
64 const result = yield* Effect.gen(function* () {
65 const glab = yield* GitLabCli.GitLabCli;
66 return yield* glab.getMergeRequest({
67 cwd: "/repo",
68 reference: "42",
69 });
70 });
71​
72 assert.deepStrictEqual(result, {
73 number: 42,
74 title: "Add MR thread creation",
75 url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
76 baseRefName: "main\u00a0",
77 headRefName: "feature/mr-threads",
78 headSha: "a".repeat(40),
79 state: "closed",
80 closedAt: "2026-08-23T10:00:00Z",
81 mergedAt: null,
82 isCrossRepository: true,
83 headRepositoryNameWithOwner: "octocat/t3code",
84 headRepositoryOwnerLogin: "octocat",
85 });
86 expect(mockedRun).toHaveBeenCalledWith(
87 expect.objectContaining({
88 command: "glab",
89 cwd: "/repo",
90 args: ["mr", "view", "--output", "json", "--", "42"],
91 }),
92 );
93 const classifyFailure = mockedRun.mock.calls.at(-1)?.[0].classifyFailure;
94 assert.strictEqual(
95 classifyFailure?.(
96 "x gitlab.example.test has not been authenticated with glab. Run `glab auth login`",
97 ),
98 "authentication",
99 );
100 assert.strictEqual(
101 classifyFailure?.(
102 '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."',
103 ),
104 "authentication",
105 );
106 }),
107 );
108​
109 it.effect("keeps a nonbreaking space at the end of the default branch", () =>
110 Effect.gen(function* () {
111 mockedRun.mockReturnValueOnce(
112 Effect.succeed(processOutput(JSON.stringify({ default_branch: "main\u00a0" }))),
113 );
114 const glab = yield* GitLabCli.GitLabCli;
115 assert.strictEqual(yield* glab.getDefaultBranch({ cwd: "/repo" }), "main\u00a0");
116 }),
117 );
118​
119 // A strictly confined glab (Snap) has a private /tmp, so it cannot open the server's body file.
120 it.effect("sends the merge request description to glab on stdin, not as a file path", () =>
121 Effect.gen(function* () {
122 const fileSystem = yield* FileSystem.FileSystem;
123 const path = yield* Path.Path;
124 const bodyDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-gitlab-mr-body-" });
125 const bodyFile = path.join(bodyDir, "t3code-pr-body.md");
126 yield* fileSystem.writeFileString(bodyFile, "## Summary\n\nFixes the thing.\n");
127 mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
128​
129 const glab = yield* GitLabCli.GitLabCli;
130 yield* glab.createMergeRequest({
131 cwd: "/repo",
132 baseBranch: "main",
133 headSelector: "feature/mr",
134 title: "Add MR",
135 bodyFile,
136 });
137​
138 const call = mockedRun.mock.calls.at(-1)?.[0];
139 expect(call?.args.join(" ")).not.toContain(bodyFile);
140 expect(call?.args).toContain("description=@-");
141 assert.strictEqual(call?.stdin, "## Summary\n\nFixes the thing.\n");
142 }).pipe(Effect.scoped),
143 );
144​
145 it.effect("fails with a typed error and skips glab when the description cannot be read", () =>
146 Effect.gen(function* () {
147 const fileSystem = yield* FileSystem.FileSystem;
148 const path = yield* Path.Path;
149 const bodyDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-gitlab-mr-body-" });
150 const glab = yield* GitLabCli.GitLabCli;
151 const error = yield* glab
152 .createMergeRequest({
153 cwd: "/repo",
154 baseBranch: "main",
155 headSelector: "feature/mr",
156 title: "Add MR",
157 bodyFile: path.join(bodyDir, "missing.md"),
158 })
159 .pipe(Effect.flip);
160​
161 assert.strictEqual(error._tag, "GitLabMergeRequestBodyReadError");
162 assert.strictEqual(error.detail, "The merge request description could not be read.");
163 expect(mockedRun).not.toHaveBeenCalled();
164 }).pipe(Effect.scoped),
165 );
166​
167 it.effect("skips invalid entries when parsing MR lists", () =>
168 Effect.gen(function* () {
169 mockedRun.mockReturnValueOnce(
170 Effect.succeed(
171 processOutput(
172 JSON.stringify([
173 {
174 iid: 0,
175 title: "invalid",
176 web_url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/0",
177 target_branch: "main",
178 source_branch: "feature/invalid",
179 },
180 {
181 iid: 43,
182 title: " Valid MR ",
183 web_url: " https://gitlab.com/pingdotgg/t3code/-/merge_requests/43 ",
184 target_branch: " main ",
185 source_branch: " feature/mr-list ",
186 state: "merged",
187 merged_at: "2026-08-23T11:00:00Z",
188 },
189 ]),
190 ),
191 ),
192 );
193​
194 const result = yield* Effect.gen(function* () {
195 const glab = yield* GitLabCli.GitLabCli;
196 return yield* glab.listMergeRequests({
197 cwd: "/repo",
198 headSelector: "feature/mr-list",
199 state: "all",
200 });
201 });
202​
203 assert.deepStrictEqual(result, [
204 {
205 number: 43,
206 title: "Valid MR",
207 url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/43",
208 baseRefName: "main",
209 headRefName: "feature/mr-list",
210 state: "merged",
211 closedAt: null,
212 mergedAt: "2026-08-23T11:00:00Z",
213 },
214 ]);
215 expect(mockedRun).toHaveBeenCalledWith(
216 expect.objectContaining({
217 command: "glab",
218 cwd: "/repo",
219 args: [
220 "mr",
221 "list",
222 "--source-branch",
223 "feature/mr-list",
224 "--all",
225 "--per-page",
226 "20",
227 "--output",
228 "json",
229 ],
230 }),
231 );
232 }),
233 );
234​
235 it.effect(
236 "retries oversized MR lists with smaller pages without losing same-named branches",
237 () =>
238 Effect.gen(function* () {
239 const entries = Array.from({ length: 4 }, (_, index) => ({
240 iid: index + 1,
241 title: "MR " + index,
242 // The first alone escapes past the default 1 MB cap; together they pass the list cap.
243 description: index === 0 ? '"'.repeat(600_000) : "x".repeat(3_000_000),
244 web_url: "https://gitlab.com/acme/web/-/merge_requests/" + (index + 1),
245 target_branch: "main",
246 source_branch: "feature",
247 source_project_id: index === 3 ? 100 : 101,
248 target_project_id: 100,
249 }));
250 mockedRun.mockImplementation((input) => {
251 const size = Number(input.args[input.args.indexOf("--per-page") + 1]);
252 const pageIndex = input.args.indexOf("--page");
253 const page = pageIndex < 0 ? 1 : Number(input.args[pageIndex + 1]);
254 const raw = JSON.stringify(entries.slice((page - 1) * size, page * size));
255 const cap = input.maxOutputBytes ?? 1_000_000;
256 return Effect.succeed({
257 ...processOutput(raw.slice(0, cap)),
258 stdoutTruncated: raw.length > cap,
259 });
260 });
261 const glab = yield* GitLabCli.GitLabCli;
262 const result = yield* glab.listMergeRequests({
263 cwd: "/repo",
264 headSelector: "feature",
265 state: "open",
266 limit: 4,
267 });
268 assert.deepStrictEqual(
269 result.map((mr) => mr.number),
270 [1, 2, 3, 4],
271 );
272 assert.strictEqual(result[3]?.isCrossRepository, false);
273 }),
274 );
275​
276 it.effect("creates same-project MRs without a repository lookup, drafts by title prefix", () =>
277 Effect.gen(function* () {
278 const fileSystem = yield* FileSystem.FileSystem;
279 const bodyFile = yield* fileSystem.makeTempFileScoped({ prefix: "t3-gitlab-mr-body-" });
280 mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
281 const glab = yield* GitLabCli.GitLabCli;
282 yield* glab.createMergeRequest({
283 cwd: "/repo",
284 baseBranch: "main",
285 headSelector: "feature/fix",
286 title: "Fix remote flow",
287 bodyFile,
288 });
289 expect(mockedRun).toHaveBeenCalledExactlyOnceWith(
290 expect.objectContaining({
291 args: [
292 "api",
293 "--method",
294 "POST",
295 "projects/:fullpath/merge_requests",
296 "--raw-field",
297 "source_branch=feature/fix",
298 "--raw-field",
299 "target_branch=main",
300 "--raw-field",
301 "title=Fix remote flow",
302 "--field",
303 "description=@-",
304 ],
305 }),
306 );
307​
308 const draftTitle = (title: string) =>
309 Effect.gen(function* () {
310 mockedRun.mockClear();
311 mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
312 yield* glab.createMergeRequest({
313 cwd: "/repo",
314 baseBranch: "main",
315 headSelector: "feature/fix",
316 title,
317 bodyFile,
318 draft: true,
319 });
320 return mockedRun.mock.calls[0]?.[0].args.find((arg) => arg.startsWith("title="));
321 });
322 expect(yield* draftTitle("Fix remote flow")).toBe("title=Draft: Fix remote flow");
323 expect(yield* draftTitle("draft: Fix remote flow")).toBe("title=draft: Fix remote flow");
324 expect(yield* draftTitle("[Draft] Fix remote flow")).toBe("title=[Draft] Fix remote flow");
325 }).pipe(Effect.scoped),
326 );
327​
328 it.effect("surfaces a friendly error when the merge request is not found", () =>
329 Effect.gen(function* () {
330 const cause = new VcsProcessExitError({
331 operation: "GitLabCli.execute",
332 command: "glab",
333 cwd: "/repo",
334 exitCode: 1,
335 detail: "GET 404 merge request not found",
336 failureKind: "not-found",
337 });
338 mockedRun.mockReturnValueOnce(Effect.fail(cause));
339​
340 const error = yield* Effect.gen(function* () {
341 const glab = yield* GitLabCli.GitLabCli;
342 return yield* glab.getMergeRequest({
343 cwd: "/repo",
344 reference: "4888",
345 });
346 }).pipe(Effect.flip);
347​
348 assert.equal(error.message.includes("Merge request 4888 was not found"), true);
349 assert.strictEqual(error._tag, "GitLabMergeRequestNotFoundError");
350 assert.strictEqual(error.command, "glab");
351 assert.strictEqual(error.cwd, "/repo");
352 assert.strictEqual(error.cause, cause);
353 assert.equal(error.message.includes(cause.detail), false);
354 }),
355 );
356​
357 it.effect.each([
358 { repository: "group/project", args: ["api", "projects/group%2Fproject"], env: {} },
359 {
360 repository: "https://gitlab.example.com:8443/group/sub/project.git",
361 args: ["api", "--hostname", "gitlab.example.com:8443", "projects/group%2Fsub%2Fproject"],
362 // The environment token is the default host's login, not this host's.
363 env: { GITLAB_TOKEN: "", GITLAB_ACCESS_TOKEN: "", OAUTH_TOKEN: "" },
364 },
365 {
366 repository: "https://gitlab.com/group/project/-/tree/main",
367 args: ["api", "--hostname", "gitlab.com", "projects/group%2Fproject"],
368 env: {},
369 },
370 ])("looks up $repository by its project path", ({ repository, args, env }) =>
371 Effect.gen(function* () {
372 mockedRun.mockReturnValueOnce(
373 Effect.succeed(
374 processOutput(
375 JSON.stringify({
376 path_with_namespace: "group/project",
377 web_url: "https://sourcecontrol.example.com/group/project",
378 http_url_to_repo: "https://sourcecontrol.example.com/group/project.git",
379 ssh_url_to_repo: "git@sourcecontrol.example.com:group/project.git",
380 }),
381 ),
382 ),
383 );
384​
385 const glab = yield* GitLabCli.GitLabCli;
386 yield* glab.getRepositoryCloneUrls({ cwd: "/repo", repository });
387​
388 expect(mockedRun).toHaveBeenCalledWith(
389 expect.objectContaining({ command: "glab", args, env }),
390 );
391 }),
392 );
393​
394 it.effect.each([
395 { host: "gitlab.com", withheld: {} },
396 {
397 host: "gitlab.example.com",
398 withheld: { GITLAB_TOKEN: "", GITLAB_ACCESS_TOKEN: "", OAUTH_TOKEN: "" },
399 },
400 ])(
401 "sends the environment token to a project on $host only when it is glab's default host",
402 ({ host, withheld }) =>
403 Effect.gen(function* () {
404 mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
405​
406 const glab = yield* GitLabCli.GitLabCli;
407 yield* glab.execute({ cwd: "/repo", host, args: ["api", "user"] });
408​
409 expect(mockedRun).toHaveBeenCalledWith(
410 expect.objectContaining({ env: { GITLAB_HOST: host, ...withheld } }),
411 );
412 }),
413 );
414​
415 it.effect.each([
416 { remote: "git@gitlab.com:group/project.git", reference: "42", withheld: {} },
417 {
418 remote: "https://gitlab.example.com/group/project.git",
419 reference: "42",
420 withheld: { GITLAB_TOKEN: "", GITLAB_ACCESS_TOKEN: "", OAUTH_TOKEN: "" },
421 },
422 {
423 remote: "git+ssh://git@gitlab.example.com/project.git",
424 reference: "42",
425 withheld: { GITLAB_TOKEN: "", GITLAB_ACCESS_TOKEN: "", OAUTH_TOKEN: "" },
426 },
427 {
428 remote: "git@gitlab.com:group/project.git",
429 reference: "https://gitlab.example.com/group/project/-/merge_requests/42",
430 withheld: { GITLAB_TOKEN: "", GITLAB_ACCESS_TOKEN: "", OAUTH_TOKEN: "" },
431 },
432 ])(
433 "keeps the environment token from the host glab picks for $reference in a $remote checkout",
434 ({ remote, reference, withheld }) =>
435 Effect.gen(function* () {
436 const environments: Array<unknown> = [];
437 const glab = yield* GitLabCli.make.pipe(
438 Effect.provide(
439 TestSourceControlHost.layer({
440 process: {
441 run: (input) => {
442 if (input.command === "git")
443 return Effect.succeed(processOutput(`origin\t${remote} (fetch)\n`));
444 environments.push(input.env);
445 return Effect.succeed(processOutput("{}"));
446 },
447 },
448 }),
449 ),
450 Effect.provideService(HostProcess.Environment, { GITLAB_TOKEN: "default-host-token" }),
451 );
452 yield* glab.checkoutMergeRequest({ cwd: "/repo", reference });
453​
454 assert.deepStrictEqual(environments, [withheld]);
455 }),
456 );
457​
458 it.effect.each(["not-found", "command-failed"] as const)(
459 "exposes fixed repository lookup details only for not-found (%s)",
460 (failureKind) =>
461 Effect.gen(function* () {
462 const cause = new VcsProcessExitError({
463 operation: "GitLabCli.execute",
464 command: "glab",
465 cwd: "/repo",
466 exitCode: 1,
467 detail: "GET 404 project not found",
468 failureKind,
469 });
470 mockedRun.mockReturnValueOnce(Effect.fail(cause));
471​
472 const error = yield* Effect.gen(function* () {
473 const glab = yield* GitLabCli.GitLabCli;
474 return yield* glab.getRepositoryCloneUrls({
475 cwd: "/repo",
476 repository: "missing/\tproject",
477 });
478 }).pipe(Effect.flip);
479​
480 assert.strictEqual(error._tag, "GitLabCliCommandError");
481 assert.strictEqual(error.cause, cause);
482 assert.strictEqual(
483 userFacingSourceControlDetail(error),
484 failureKind === "not-found"
485 ? "Repository missing/ project was not found. Check the owner and name and try again."
486 : undefined,
487 );
488 }),
489 );
490​
491 it.effect("preserves rate-limit failures as a distinct error", () =>
492 Effect.gen(function* () {
493 const cause = new VcsProcessExitError({
494 operation: "GitLabCli.execute",
495 command: "glab",
496 cwd: "/repo",
497 exitCode: 1,
498 detail: "API rate limit exceeded.",
499 failureKind: "rate-limited",
500 });
501 mockedRun.mockReturnValueOnce(Effect.fail(cause));
502​
503 const glab = yield* GitLabCli.GitLabCli;
504 const error = yield* glab
505 .execute({ cwd: "/repo", args: ["api", "projects"] })
506 .pipe(Effect.flip);
507​
508 assert.strictEqual(error._tag, "GitLabCliRateLimitError");
509 assert.strictEqual(error.cause, cause);
510 }),
511 );
512});