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

GitLabCli.test.ts

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