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