Open History to see the last commit
1import { afterEach, assert, expect, it, vi } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import { ChildProcessSpawner } from "effect/process";
5
6import * as GitLabCli from "./GitLabCli.ts";
7import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
8
9const mockedExecute = vi.fn<GitLabCli.GitLabCli["Service"]["execute"]>();
10
11const layer = it.layer(
12 GitLabPullRequestCli.layer.pipe(
13 Layer.provide(
14 Layer.mock(GitLabCli.GitLabCli)({
15 execute: mockedExecute,
16 }),
17 ),
18 ),
19);
20
21function output(stdout: string, stdoutTruncated = false, stdoutInvalidUtf8 = false) {
22 return {
23 exitCode: ChildProcessSpawner.ExitCode(0),
24 stdout,
25 stderr: "",
26 stdoutTruncated,
27 stderrTruncated: false,
28 stdoutInvalidUtf8,
29 };
30}
31
32function mergeRequests(count: number, firstNumber: number): string {
33 return JSON.stringify(
34 Array.from({ length: count }, (_, index) => ({
35 iid: firstNumber + index,
36 title: `Merge request ${firstNumber + index}`,
37 web_url: `https://gitlab.com/acme/web/-/merge_requests/${firstNumber + index}`,
38 source_branch: "feat/page",
39 target_branch: "main",
40 created_at: "2026-07-01T00:00:00Z",
41 updated_at: "2026-07-02T00:00:00Z",
42 })),
43 );
44}
45
46function diffPage(firstIndex: number, count = 100): string {
47 return JSON.stringify(
48 Array.from({ length: count }, (_, index) => ({
49 old_path: `src/${firstIndex + index}.ts`,
50 new_path: `src/${firstIndex + index}.ts`,
51 diff: "@@ -1 +1 @@\n-a\n+b\n",
52 })),
53 );
54}
55
56function notes(count: number, firstId: number): string {
57 return JSON.stringify(
58 Array.from({ length: count }, (_, index) => ({
59 id: firstId + index,
60 body: `note ${firstId + index}`,
61 author: { username: "bilal" },
62 created_at: "2026-07-01T00:00:00Z",
63 })),
64 );
65}
66
67const author = { id: 1, username: "bilal" };
68const reviewer = { id: 5, username: "octocat" };
69
70function mergeRequestJson(overrides: Record<string, unknown>): string {
71 return JSON.stringify({
72 iid: 7,
73 title: "Merge request 7",
74 web_url: "https://gitlab.com/acme/web/-/merge_requests/7",
75 source_branch: "feat/page",
76 target_branch: "main",
77 created_at: "2026-07-01T00:00:00Z",
78 updated_at: "2026-07-02T00:00:00Z",
79 author,
80 ...overrides,
81 });
82}
83
84function argsOfCall(index: number): ReadonlyArray<string> {
85 return callAt(index).args;
86}
87
88function callAt(index: number) {
89 const call = mockedExecute.mock.calls[index];
90 assert.isDefined(call);
91 return call[0];
92}
93
94afterEach(() => {
95 mockedExecute.mockReset();
96});
97
98layer("GitLabPullRequestCli.layer", (it) => {
99 it.effect("asks GitLab for one row more than the page, to probe for a next page", () =>
100 Effect.gen(function* () {
101 mockedExecute.mockReturnValueOnce(Effect.succeed(output(mergeRequests(3, 1))));
102 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
103
104 const batch = yield* cli.listMergeRequests({
105 cwd: "/w",
106 repository: "acme/web",
107 state: "open",
108 involvement: "all",
109 viewer: "bilal",
110 limit: 10,
111 });
112
113 assert.strictEqual(batch.items.length, 3);
114 assert.isFalse(batch.truncated);
115 assert.strictEqual(batch.cursorAdvance, 3);
116 const path = argsOfCall(0)[1] ?? "";
117 expect(path).toContain("projects/acme%2Fweb/merge_requests");
118 expect(path).toContain("per_page=11");
119 expect(path).toContain("state=opened");
120 }),
121 );
122
123 it.effect("walks pages at a fixed size, because GitLab pages by offset", () =>
124 Effect.gen(function* () {
125 mockedExecute
126 .mockReturnValueOnce(Effect.succeed(output(mergeRequests(100, 1))))
127 .mockReturnValueOnce(Effect.succeed(output(mergeRequests(100, 101))));
128 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
129
130 const batch = yield* cli.listMergeRequests({
131 cwd: "/w",
132 repository: "acme/web",
133 state: "open",
134 involvement: "all",
135 viewer: "bilal",
136 limit: 150,
137 });
138
139 assert.strictEqual(batch.items.length, 150);
140 assert.isTrue(batch.truncated);
141 for (const index of [0, 1]) {
142 expect(argsOfCall(index)[1]).toContain("per_page=100");
143 }
144 expect(argsOfCall(0)[1]).toContain("page=1");
145 expect(argsOfCall(1)[1]).toContain("page=2");
146 }),
147 );
148
149 it.effect("asks GitLab for the labels, author and draft state it can filter on", () =>
150 Effect.gen(function* () {
151 mockedExecute.mockReturnValueOnce(Effect.succeed(output(mergeRequests(1, 1))));
152 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
153
154 yield* cli.listMergeRequests({
155 cwd: "/w",
156 repository: "acme/web",
157 state: "open",
158 involvement: "all",
159 viewer: "bilal",
160 limit: 10,
161 filters: {
162 labels: [["bug"], ["size:S", "size:XS"], ["a,b"], ["None"]],
163 excludedLabels: ["wontfix", "stale", "any"],
164 author: "@me",
165 draft: "only",
166 },
167 });
168
169 const params = new URLSearchParams((argsOfCall(0)[1] ?? "").split("?")[1]);
170 expect(params.get("labels")).toBe("bug");
171 expect(params.get("not[labels]")).toBe("wontfix,stale");
172 expect(params.get("author_username")).toBe("bilal");
173 expect(params.get("wip")).toBe("yes");
174 }),
175 );
176
177 it.effect("carries on from the number of rows already delivered", () =>
178 Effect.gen(function* () {
179 mockedExecute.mockReturnValueOnce(Effect.succeed(output(mergeRequests(3, 1))));
180 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
181
182 yield* cli.listMergeRequests({
183 cwd: "/w",
184 repository: "acme/web",
185 state: "open",
186 involvement: "all",
187 viewer: "bilal",
188 limit: 10,
189 cursor: { updatedBefore: "2026-07-02T00:00:00Z", delivered: 10 },
190 });
191
192 // GitLab's timestamp filter has no tie-breaker, so an offset is what advances through a
193 // boundary shared by more rows than one page can hold.
194 const path = argsOfCall(0)[1] ?? "";
195 expect(path).not.toContain("updated_before=");
196 expect(path).toContain("order_by=updated_at");
197 expect(path).toContain("per_page=11");
198 expect(path).toContain("page=1");
199 }),
200 );
201
202 it.effect("advances beyond several pages sharing the cursor timestamp", () =>
203 Effect.gen(function* () {
204 mockedExecute
205 .mockReturnValueOnce(Effect.succeed(output(mergeRequests(11, 144))))
206 .mockReturnValueOnce(Effect.succeed(output(mergeRequests(11, 155))));
207 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
208
209 const batch = yield* cli.listMergeRequests({
210 cwd: "/w",
211 repository: "acme/web",
212 state: "open",
213 involvement: "all",
214 viewer: "bilal",
215 limit: 10,
216 cursor: { updatedBefore: "2026-07-02T00:00:00Z", delivered: 150 },
217 });
218
219 expect(argsOfCall(0)[1]).toContain("per_page=11");
220 expect(argsOfCall(0)[1]).toContain("page=14");
221 expect(argsOfCall(1)[1]).toContain("page=15");
222 expect(batch.items.map((item) => item.number)).toEqual([
223 151, 152, 153, 154, 155, 156, 157, 158, 159, 160,
224 ]);
225 assert.isTrue(batch.truncated);
226 }),
227 );
228
229 it.effect("advances the cursor through malformed raw rows", () =>
230 Effect.gen(function* () {
231 const rows = JSON.parse(mergeRequests(2, 1)) as ReadonlyArray<unknown>;
232 mockedExecute.mockReturnValueOnce(
233 Effect.succeed(output(JSON.stringify([{ iid: "malformed" }, ...rows]))),
234 );
235 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
236
237 const batch = yield* cli.listMergeRequests({
238 cwd: "/w",
239 repository: "acme/web",
240 state: "open",
241 involvement: "all",
242 viewer: "bilal",
243 limit: 2,
244 });
245
246 expect(batch.items.map((item) => item.number)).toEqual([1, 2]);
247 assert.strictEqual(batch.cursorAdvance, 3);
248 assert.isTrue(batch.truncated);
249 }),
250 );
251
252 it.effect("URL-encodes a search, so it cannot add a parameter of its own", () =>
253 Effect.gen(function* () {
254 mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
255 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
256
257 yield* cli.listMergeRequests({
258 cwd: "/w",
259 repository: "acme/web",
260 state: "open",
261 involvement: "all",
262 viewer: "bilal",
263 limit: 10,
264 query: '-a&per_page=1 "b"',
265 });
266
267 const path = argsOfCall(0)[1] ?? "";
268 expect(path).toContain("search=-a%26per_page%3D1%20%22b%22");
269 assert.strictEqual(path.match(/per_page=/g)?.length, 1);
270 }),
271 );
272
273 it.effect("stops walking on a short page", () =>
274 Effect.gen(function* () {
275 mockedExecute.mockReturnValueOnce(Effect.succeed(output(mergeRequests(40, 1))));
276 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
277
278 const batch = yield* cli.listMergeRequests({
279 cwd: "/w",
280 repository: "acme/web",
281 state: "open",
282 involvement: "all",
283 viewer: "bilal",
284 limit: 150,
285 });
286
287 assert.strictEqual(batch.items.length, 40);
288 assert.isFalse(batch.truncated);
289 assert.strictEqual(mockedExecute.mock.calls.length, 1);
290 }),
291 );
292
293 it.effect("stops walking when every row on a page fails to decode", () =>
294 Effect.gen(function* () {
295 const unusable = JSON.stringify(Array.from({ length: 100 }, () => ({ iid: "nope" })));
296 mockedExecute.mockReturnValue(Effect.succeed(output(unusable)));
297 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
298
299 const batch = yield* cli.listMergeRequests({
300 cwd: "/w",
301 repository: "acme/web",
302 state: "open",
303 involvement: "all",
304 viewer: "bilal",
305 limit: 150,
306 });
307
308 assert.strictEqual(batch.items.length, 0);
309 assert.strictEqual(mockedExecute.mock.calls.length, 2);
310 }),
311 );
312
313 it.effect.each([
314 { action: "merge", autoMerge: "false", mergeMethod: "squash" },
315 { action: "enable-auto-merge", autoMerge: "true", mergeMethod: "squash" },
316 { action: "merge", autoMerge: "false", mergeMethod: "rebase" },
317 ] as const)(
318 "$action with $mergeMethod succeeds on a project requiring the current source SHA",
319 ({ action, autoMerge, mergeMethod }) =>
320 Effect.gen(function* () {
321 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
322
323 for (const headSha of ["first-head", "updated-head"]) {
324 let currentHeadSha = headSha;
325 mockedExecute.mockImplementation(({ cwd, args }) => {
326 if (args[0] === "mr" && args[1] === "rebase") {
327 return Effect.sync(() => {
328 currentHeadSha = `${headSha}-rebased`;
329 return output("");
330 });
331 }
332 if (args[0] === "api") {
333 return Effect.succeed(
334 output(
335 mergeRequestJson({
336 diff_refs: { base_sha: "base", head_sha: currentHeadSha, start_sha: "start" },
337 }),
338 ),
339 );
340 }
341 if (args.includes("--rebase") || args[args.indexOf("--sha") + 1] !== currentHeadSha) {
342 return Effect.fail(
343 new GitLabCli.GitLabCliCommandError({
344 operation: "execute",
345 command: "glab",
346 cwd,
347 cause: new Error(
348 args.includes("--rebase")
349 ? "Merge must not combine --rebase with --sha: rebase changes the source HEAD"
350 : "SHA must match the current source branch HEAD",
351 ),
352 }),
353 );
354 }
355 return Effect.succeed(output(""));
356 });
357
358 yield* cli.runMergeRequestAction({
359 cwd: "/w",
360 repository: "acme/web",
361 number: 7,
362 action,
363 mergeMethod,
364 });
365
366 const callsPerAction = mergeMethod === "rebase" ? 3 : 2;
367 expect(
368 mockedExecute.mock.calls.slice(-callsPerAction).map(([input]) => input.args),
369 ).toEqual([
370 ...(mergeMethod === "rebase" ? [["mr", "rebase", "7", "--repo", "acme/web"]] : []),
371 ["api", "projects/acme%2Fweb/merge_requests/7"],
372 [
373 "mr",
374 "merge",
375 "7",
376 "--repo",
377 "acme/web",
378 `--auto-merge=${autoMerge}`,
379 "--yes",
380 ...(mergeMethod === "squash" ? ["--squash"] : []),
381 "--sha",
382 mergeMethod === "rebase" ? `${headSha}-rebased` : headSha,
383 ],
384 ]);
385 }
386 expect(mockedExecute).toHaveBeenCalledTimes(mergeMethod === "rebase" ? 6 : 4);
387 }),
388 );
389
390 it.effect.each(["merge", "enable-auto-merge"] as const)(
391 "does not run %s when GitLab has no diff revisions",
392 (action) =>
393 Effect.gen(function* () {
394 mockedExecute.mockReturnValue(
395 Effect.succeed(output(mergeRequestJson({ diff_refs: null }))),
396 );
397 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
398
399 const result = yield* Effect.result(
400 cli.runMergeRequestAction({
401 cwd: "/w",
402 repository: "acme/web",
403 number: 7,
404 action,
405 mergeMethod: "squash",
406 }),
407 );
408
409 expect(mockedExecute.mock.calls.map(([input]) => input.args)).toEqual([
410 ["api", "projects/acme%2Fweb/merge_requests/7"],
411 ]);
412 expect(result).toMatchObject({
413 _tag: "Failure",
414 failure: { _tag: "GitLabDiffRefsUnavailableError" },
415 });
416 }),
417 );
418
419 it.effect("sends a comment body over stdin, never in argv", () =>
420 Effect.gen(function* () {
421 mockedExecute.mockReturnValueOnce(Effect.succeed(output("")));
422 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
423
424 yield* cli.commentOnMergeRequest({
425 cwd: "/w",
426 repository: "acme/web",
427 number: 7,
428 body: "true",
429 });
430
431 const call = mockedExecute.mock.calls[0];
432 assert.isDefined(call);
433 expect(call[0].args).toEqual([
434 "api",
435 "projects/acme%2Fweb/merge_requests/7/notes",
436 "--method",
437 "POST",
438 "--input",
439 "-",
440 "--header",
441 "Content-Type: application/json",
442 ]);
443 expect(call[0].stdin).toBe('{"body":"true"}');
444 }),
445 );
446
447 it.effect("reads one diff page and hands back the cursor for the next", () =>
448 Effect.gen(function* () {
449 mockedExecute.mockReturnValueOnce(Effect.succeed(output(diffPage(0))));
450 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
451
452 const diff = yield* cli.getMergeRequestDiff({
453 cwd: "/w",
454 repository: "acme/web",
455 number: 7,
456 });
457
458 assert.strictEqual(mockedExecute.mock.calls.length, 1);
459 assert.isNotNull(diff.nextCursor);
460 assert.isFalse(diff.truncated);
461 expect(argsOfCall(0)[1]).toContain("merge_requests/7/diffs?per_page=30&page=1");
462 }),
463 );
464
465 it.effect(
466 "pages a merge request diff 30 files at a time, which GitLab 15.7 to 17.10 accept",
467 () =>
468 Effect.gen(function* () {
469 mockedExecute
470 .mockReturnValueOnce(Effect.succeed(output(diffPage(0, 30))))
471 .mockReturnValueOnce(Effect.succeed(output(diffPage(30, 30))))
472 .mockReturnValueOnce(Effect.succeed(output(diffPage(60, 5))));
473 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
474 const target = { cwd: "/w", repository: "acme/web", number: 7 };
475
476 let patch = "";
477 let cursor: string | undefined;
478 do {
479 const slice = yield* cli.getMergeRequestDiff({ ...target, cursor });
480 patch += slice.patch;
481 cursor = slice.nextCursor ?? undefined;
482 } while (cursor !== undefined);
483
484 expect(mockedExecute.mock.calls.map(([call]) => call.args[1])).toEqual([
485 "projects/acme%2Fweb/merge_requests/7/diffs?per_page=30&page=1",
486 "projects/acme%2Fweb/merge_requests/7/diffs?per_page=30&page=2",
487 "projects/acme%2Fweb/merge_requests/7/diffs?per_page=30&page=3",
488 ]);
489 assert.strictEqual(patch.match(/^diff --git /gm)?.length, 65);
490 expect(patch).toContain("diff --git a/src/64.ts b/src/64.ts");
491 }),
492 );
493
494 it.effect("refuses a cursor it never handed out rather than reading it into a query", () =>
495 Effect.gen(function* () {
496 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
497
498 const error = yield* Effect.flip(
499 cli.getMergeRequestDiff({
500 cwd: "/w",
501 repository: "acme/web",
502 number: 7,
503 cursor: "1&per_page=1",
504 }),
505 );
506
507 assert.strictEqual(error._tag, "GitLabDiffCursorError");
508 assert.strictEqual(mockedExecute.mock.calls.length, 0);
509 }),
510 );
511
512 it.effect("reads a named commit from its own diff, and pages inside it", () =>
513 Effect.gen(function* () {
514 mockedExecute
515 .mockReturnValueOnce(Effect.succeed(output(diffPage(0))))
516 .mockReturnValueOnce(Effect.succeed(output(diffPage(100, 3))));
517 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
518 const target = {
519 cwd: "/w",
520 repository: "acme/web",
521 number: 7,
522 commit: "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0",
523 };
524
525 const first = yield* cli.getMergeRequestDiff(target);
526 assert.isNotNull(first.nextCursor);
527 const second = yield* cli.getMergeRequestDiff({ ...target, cursor: first.nextCursor });
528
529 const commitPath =
530 "projects/acme%2Fweb/repository/commits/a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0/diff";
531 expect(argsOfCall(0)[1]).toBe(`${commitPath}?per_page=100&page=1`);
532 expect(argsOfCall(1)[1]).toBe(`${commitPath}?per_page=100&page=2`);
533 assert.isNull(second.nextCursor);
534 }),
535 );
536
537 it.effect("refuses a commit that is not a sha rather than reading it into a path", () =>
538 Effect.gen(function* () {
539 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
540
541 const error = yield* Effect.flip(
542 cli.getMergeRequestDiff({
543 cwd: "/w",
544 repository: "acme/web",
545 number: 7,
546 commit: "../../merge_requests/8/diffs",
547 }),
548 );
549
550 assert.strictEqual(error._tag, "GitLabDiffCommitError");
551 assert.strictEqual(mockedExecute.mock.calls.length, 0);
552 }),
553 );
554
555 it.effect("reports a commit with no parent as a structured error", () =>
556 Effect.gen(function* () {
557 mockedExecute.mockReturnValueOnce(
558 Effect.succeed(output(JSON.stringify({ id: "a1b2c3d", parent_ids: [] }))),
559 );
560 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
561
562 const error = yield* Effect.flip(
563 cli.getMergeRequestDiffFileContents({
564 cwd: "/w",
565 repository: "acme/web",
566 number: 7,
567 commit: "a1b2c3d",
568 changeType: "change",
569 oldPath: "src/a.ts",
570 newPath: "src/a.ts",
571 }),
572 );
573
574 assert.strictEqual(error._tag, "GitLabDiffCommitParentUnavailableError");
575 if (error._tag === "GitLabDiffCommitParentUnavailableError") {
576 assert.strictEqual(error.commit, "a1b2c3d");
577 }
578 }),
579 );
580
581 it.effect("expands a new file from a root commit without requiring a parent", () =>
582 Effect.gen(function* () {
583 mockedExecute.mockReturnValueOnce(
584 Effect.succeed(output(JSON.stringify({ id: "a1b2c3d", parent_ids: [] }))),
585 );
586 mockedExecute.mockReturnValueOnce(Effect.succeed(output("first contents\n")));
587 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
588
589 const contents = yield* cli.getMergeRequestDiffFileContents({
590 cwd: "/w",
591 repository: "acme/web",
592 number: 7,
593 commit: "a1b2c3d",
594 changeType: "new",
595 oldPath: "src/first.ts",
596 newPath: "src/first.ts",
597 });
598
599 expect(contents).toEqual({ oldContents: "", newContents: "first contents\n" });
600 expect(argsOfCall(1)[1]).toContain("raw?ref=a1b2c3d");
601 }),
602 );
603
604 it.effect("reports undecodable diff file contents as binary", () =>
605 Effect.gen(function* () {
606 mockedExecute.mockReturnValueOnce(
607 Effect.succeed(
608 output(
609 JSON.stringify({
610 diff_refs: {
611 base_sha: "a1b2c3d",
612 head_sha: "b1c2d3e",
613 start_sha: "a1b2c3d",
614 },
615 }),
616 ),
617 ),
618 );
619 mockedExecute.mockReturnValueOnce(
620 Effect.succeed(output("binary\uFFFDcontents", false, true)),
621 );
622 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
623
624 const error = yield* Effect.flip(
625 cli.getMergeRequestDiffFileContents({
626 cwd: "/w",
627 repository: "acme/web",
628 number: 7,
629 changeType: "deleted",
630 oldPath: "assets/logo.png",
631 newPath: "assets/logo.png",
632 }),
633 );
634
635 assert.strictEqual(error._tag, "GitLabDiffFileContentsUnavailableError");
636 if (error._tag === "GitLabDiffFileContentsUnavailableError") {
637 assert.strictEqual(error.path, "assets/logo.png");
638 assert.strictEqual(error.reason, "binary");
639 }
640 }),
641 );
642
643 it.effect("returns valid text containing a literal replacement character", () =>
644 Effect.gen(function* () {
645 mockedExecute.mockReturnValueOnce(
646 Effect.succeed(
647 output(
648 JSON.stringify({
649 diff_refs: {
650 base_sha: "a1b2c3d",
651 head_sha: "b1c2d3e",
652 start_sha: "a1b2c3d",
653 },
654 }),
655 ),
656 ),
657 );
658 mockedExecute.mockReturnValueOnce(Effect.succeed(output("before\uFFFDafter")));
659 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
660
661 const contents = yield* cli.getMergeRequestDiffFileContents({
662 cwd: "/w",
663 repository: "acme/web",
664 number: 7,
665 changeType: "deleted",
666 oldPath: "docs/encoding.md",
667 newPath: "docs/encoding.md",
668 });
669
670 assert.strictEqual(contents.oldContents, "before\uFFFDafter");
671 }),
672 );
673
674 it.effect("ends the diff on a page with no files rather than asking for it again", () =>
675 Effect.gen(function* () {
676 mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
677 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
678
679 const diff = yield* cli.getMergeRequestDiff({
680 cwd: "/w",
681 repository: "acme/web",
682 number: 7,
683 cursor: "4",
684 });
685
686 assert.strictEqual(diff.patch, "");
687 assert.isNull(diff.nextCursor);
688 }),
689 );
690
691 it.effect("fails a diff page cut off mid-JSON rather than calling the diff whole", () =>
692 Effect.gen(function* () {
693 mockedExecute.mockReturnValueOnce(
694 Effect.succeed({ ...output('[{"old_path":"src/x.ts","new_p'), stdoutTruncated: true }),
695 );
696 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
697
698 const error = yield* Effect.flip(
699 cli.getMergeRequestDiff({ cwd: "/w", repository: "acme/web", number: 7 }),
700 );
701
702 assert.strictEqual(error._tag, "GitLabMergeRequestReadError");
703 }),
704 );
705
706 it.effect("offers no squash when the project does not say it allows one", () =>
707 Effect.gen(function* () {
708 mockedExecute.mockReturnValueOnce(
709 Effect.succeed(output(JSON.stringify({ merge_method: "merge" }))),
710 );
711 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
712
713 const capabilities = yield* cli.getProjectMergeCapabilities({
714 cwd: "/w",
715 repository: "acme/web",
716 });
717
718 assert.deepStrictEqual(capabilities, { merge: true, squash: false, rebase: false });
719 }),
720 );
721
722 it.effect("reads the project's merge settings as its merge capabilities", () =>
723 Effect.gen(function* () {
724 mockedExecute.mockReturnValueOnce(
725 Effect.succeed(output(JSON.stringify({ merge_method: "ff", squash_option: "never" }))),
726 );
727 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
728
729 const capabilities = yield* cli.getProjectMergeCapabilities({
730 cwd: "/w",
731 repository: "acme/web",
732 });
733
734 assert.deepStrictEqual(capabilities, { merge: false, squash: false, rebase: true });
735 }),
736 );
737
738 it.effect("fails when the authenticated account has no username", () =>
739 Effect.gen(function* () {
740 mockedExecute.mockReturnValueOnce(Effect.succeed(output(JSON.stringify({ username: "" }))));
741 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
742
743 const error = yield* Effect.flip(cli.getViewerUsername({ cwd: "/w" }));
744
745 assert.strictEqual(error._tag, "GitLabViewerUnavailableError");
746 }),
747 );
748
749 it.effect("walks the notes until GitLab answers with a short page", () =>
750 Effect.gen(function* () {
751 mockedExecute.mockReturnValueOnce(Effect.succeed(output(notes(100, 1))));
752 mockedExecute.mockReturnValueOnce(Effect.succeed(output(notes(2, 101))));
753 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
754
755 const { comments, truncated } = yield* cli.listNotes({
756 cwd: "/w",
757 repository: "acme/web",
758 number: 7,
759 });
760
761 expect(argsOfCall(0).join(" ")).toContain("page=1");
762 expect(argsOfCall(1).join(" ")).toContain("page=2");
763 assert.strictEqual(comments.length, 102);
764 assert.isFalse(truncated);
765 }),
766 );
767
768 it.effect("stops the note walk at its bound and says the conversation was cut short", () =>
769 Effect.gen(function* () {
770 mockedExecute.mockReturnValue(Effect.succeed(output(notes(100, 1))));
771 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
772
773 const { truncated } = yield* cli.listNotes({
774 cwd: "/w",
775 repository: "acme/web",
776 number: 7,
777 });
778
779 assert.strictEqual(mockedExecute.mock.calls.length, 10);
780 assert.isTrue(truncated);
781 }),
782 );
783
784 it.effect("reads a positioned discussion as a thread anchored to its line", () =>
785 Effect.gen(function* () {
786 mockedExecute.mockReturnValueOnce(
787 Effect.succeed(
788 output(
789 JSON.stringify([
790 {
791 id: "abc123",
792 notes: [
793 {
794 id: 1,
795 body: "rename this",
796 author: { username: "bilal", avatar_url: "https://avatars/b.png" },
797 created_at: "2026-07-01T00:00:00Z",
798 resolvable: true,
799 resolved: true,
800 position: {
801 position_type: "text",
802 new_path: "src/a.ts",
803 old_path: "src/a.ts",
804 new_line: 12,
805 old_line: null,
806 },
807 },
808 {
809 id: 2,
810 body: "done",
811 author: { username: "julius" },
812 created_at: "2026-07-01T01:00:00Z",
813 },
814 ],
815 },
816 { id: "def456", notes: [{ id: 3, body: "ship it", created_at: "2026-07-01Z" }] },
817 ]),
818 ),
819 ),
820 );
821 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
822
823 const { threads } = yield* cli.listDiscussions({
824 cwd: "/w",
825 repository: "acme/web",
826 number: 7,
827 });
828
829 assert.strictEqual(threads.length, 1);
830 expect(threads[0]).toMatchObject({
831 id: "abc123",
832 path: "src/a.ts",
833 line: 12,
834 side: "right",
835 isResolved: true,
836 });
837 assert.strictEqual(threads[0]?.comments.length, 2);
838 }),
839 );
840
841 it.effect("sends a review as its comments, then its summary, then the verdict", () =>
842 Effect.gen(function* () {
843 mockedExecute.mockReturnValueOnce(
844 Effect.succeed(
845 output(
846 JSON.stringify({
847 iid: 7,
848 title: "t",
849 web_url: "https://gitlab.com/acme/web/-/merge_requests/7",
850 source_branch: "feat",
851 target_branch: "main",
852 created_at: "2026-07-01T00:00:00Z",
853 updated_at: "2026-07-01T00:00:00Z",
854 diff_refs: { base_sha: "base", head_sha: "head", start_sha: "start" },
855 }),
856 ),
857 ),
858 );
859 mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
860 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
861
862 yield* cli.submitReview({
863 cwd: "/w",
864 repository: "acme/web",
865 number: 7,
866 verdict: "approve",
867 body: "Looks right.",
868 comments: [
869 {
870 path: "src/b.ts",
871 oldPath: "src/a.ts",
872 position: { kind: "deleted", oldLine: 4 },
873 body: "why remove?",
874 },
875 ],
876 });
877
878 expect(argsOfCall(0)[1]).toContain("merge_requests/7");
879 expect(argsOfCall(1)[1]).toContain("/discussions");
880 expect(JSON.parse(callAt(1).stdin ?? "")).toEqual({
881 body: "why remove?",
882 position: {
883 base_sha: "base",
884 head_sha: "head",
885 start_sha: "start",
886 position_type: "text",
887 // A renamed file is the only case the two differ, and GitLab cannot place a
888 // position that names the same path on both sides of the rename.
889 old_path: "src/a.ts",
890 new_path: "src/b.ts",
891 old_line: 4,
892 },
893 });
894 expect(argsOfCall(2)[1]).toContain("/notes");
895 expect(argsOfCall(3)[1]).toContain("/approve");
896 }),
897 );
898
899 it.effect("removes an award by listing them and deleting the reader's own id", () =>
900 Effect.gen(function* () {
901 mockedExecute.mockReturnValueOnce(
902 Effect.succeed(output(JSON.stringify({ username: "bilal" }))),
903 );
904 mockedExecute.mockReturnValueOnce(
905 Effect.succeed(
906 output(
907 JSON.stringify([
908 { id: 5, name: "thumbsup", user: { username: "bilal" } },
909 { id: 6, name: "thumbsup", user: { username: "julius" } },
910 ]),
911 ),
912 ),
913 );
914 mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
915 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
916
917 yield* cli.setReaction({
918 cwd: "/w",
919 repository: "acme/web",
920 number: 7,
921 content: "thumbs-up",
922 reacted: false,
923 });
924
925 assert.strictEqual(mockedExecute.mock.calls.length, 3);
926 expect(argsOfCall(2)).toEqual([
927 "api",
928 "projects/acme%2Fweb/merge_requests/7/award_emoji/5",
929 "--method",
930 "DELETE",
931 ]);
932 }),
933 );
934
935 it.effect("names a merge request with no diff revisions rather than calling it unreadable", () =>
936 Effect.gen(function* () {
937 mockedExecute.mockReturnValueOnce(
938 Effect.succeed(
939 output(
940 JSON.stringify({
941 iid: 7,
942 title: "t",
943 web_url: "https://gitlab.com/acme/web/-/merge_requests/7",
944 source_branch: "feat",
945 target_branch: "main",
946 created_at: "2026-07-01T00:00:00Z",
947 updated_at: "2026-07-01T00:00:00Z",
948 diff_refs: null,
949 }),
950 ),
951 ),
952 );
953 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
954
955 const error = yield* Effect.flip(
956 cli.submitReview({
957 cwd: "/w",
958 repository: "acme/web",
959 number: 7,
960 verdict: "comment",
961 body: "",
962 comments: [{ path: "src/a.ts", position: { kind: "added", newLine: 4 }, body: "nit" }],
963 }),
964 );
965
966 assert.strictEqual(error._tag, "GitLabDiffRefsUnavailableError");
967 }),
968 );
969
970 it.effect("reads who has access to the project and who is already on the merge request", () =>
971 Effect.gen(function* () {
972 mockedExecute
973 .mockReturnValueOnce(Effect.succeed(output(mergeRequestJson({ reviewers: [reviewer] }))))
974 .mockReturnValueOnce(
975 Effect.succeed(output(JSON.stringify([author, reviewer, { id: 9, username: "hubot" }]))),
976 );
977 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
978
979 const list = yield* cli.listReviewerCandidates({
980 cwd: "/w",
981 repository: "acme/web",
982 number: 7,
983 });
984
985 expect(argsOfCall(1)[1]).toBe("projects/acme%2Fweb/users?per_page=100");
986 expect(list.candidates.map((candidate) => [candidate.id, candidate.isRequested])).toEqual([
987 ["5", true],
988 ["9", false],
989 ]);
990 assert.isFalse(list.truncated);
991 }),
992 );
993
994 it.effect("writes the reviewer set back with the one being asked added to it", () =>
995 Effect.gen(function* () {
996 mockedExecute
997 .mockReturnValueOnce(Effect.succeed(output(mergeRequestJson({ reviewers: [reviewer] }))))
998 .mockReturnValueOnce(Effect.succeed(output("{}")));
999 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1000
1001 yield* cli.setReviewerRequest({
1002 cwd: "/w",
1003 repository: "acme/web",
1004 number: 7,
1005 reviewers: [{ id: "9" }],
1006 requested: true,
1007 });
1008
1009 // GitLab replaces the whole set, so the reviewer already on the merge request has to be
1010 // sent back with the new one or the request would take them off it.
1011 expect(argsOfCall(1)).toContain("PUT");
1012 expect(JSON.parse(callAt(1).stdin ?? "")).toEqual({ reviewer_ids: [5, 9] });
1013 }),
1014 );
1015
1016 it.effect("takes a reviewer out of the set rather than clearing it", () =>
1017 Effect.gen(function* () {
1018 mockedExecute
1019 .mockReturnValueOnce(
1020 Effect.succeed(
1021 output(mergeRequestJson({ reviewers: [reviewer, { id: 9, username: "hubot" }] })),
1022 ),
1023 )
1024 .mockReturnValueOnce(Effect.succeed(output("{}")));
1025 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1026
1027 yield* cli.setReviewerRequest({
1028 cwd: "/w",
1029 repository: "acme/web",
1030 number: 7,
1031 reviewers: [{ id: "9" }],
1032 requested: false,
1033 });
1034
1035 expect(JSON.parse(callAt(1).stdin ?? "")).toEqual({ reviewer_ids: [5] });
1036 }),
1037 );
1038
1039 it.effect("ignores an id GitLab could not have handed out, which names nobody", () =>
1040 Effect.gen(function* () {
1041 mockedExecute
1042 .mockReturnValueOnce(Effect.succeed(output(mergeRequestJson({ reviewers: [reviewer] }))))
1043 .mockReturnValueOnce(Effect.succeed(output("{}")));
1044 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1045
1046 yield* cli.setReviewerRequest({
1047 cwd: "/w",
1048 repository: "acme/web",
1049 number: 7,
1050 reviewers: [{ id: "octocat" }],
1051 requested: true,
1052 });
1053
1054 expect(JSON.parse(callAt(1).stdin ?? "")).toEqual({ reviewer_ids: [5] });
1055 }),
1056 );
1057 it.effect("reads blob ids for the marked paths at the merge request's head", () =>
1058 Effect.gen(function* () {
1059 mockedExecute.mockReturnValueOnce(
1060 Effect.succeed(
1061 output(
1062 JSON.stringify({
1063 iid: 7,
1064 title: "t",
1065 web_url: "https://gitlab.com/acme/web/-/merge_requests/7",
1066 source_branch: "feat",
1067 target_branch: "main",
1068 created_at: "2026-07-01T00:00:00Z",
1069 updated_at: "2026-07-01T00:00:00Z",
1070 diff_refs: { base_sha: "base", head_sha: "head", start_sha: "start" },
1071 }),
1072 ),
1073 ),
1074 );
1075 mockedExecute.mockReturnValueOnce(
1076 Effect.succeed(
1077 output(
1078 JSON.stringify({
1079 data: {
1080 project: { repository: { blobs: { nodes: [{ path: "src/a.ts", oid: "aaa" }] } } },
1081 },
1082 }),
1083 ),
1084 ),
1085 );
1086 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1087
1088 const revisions = yield* cli.getFileRevisions({
1089 cwd: "/w",
1090 repository: "acme/web",
1091 number: 7,
1092 paths: ["src/a.ts", "src/gone.ts"],
1093 });
1094
1095 expect([...revisions]).toEqual([
1096 ["src/a.ts", "aaa"],
1097 ["src/gone.ts", ""],
1098 ]);
1099 const body: unknown = JSON.parse(callAt(1).stdin ?? "{}");
1100 expect(body).toMatchObject({
1101 variables: { fullPath: "acme/web", ref: "head", paths: ["src/a.ts", "src/gone.ts"] },
1102 });
1103 }),
1104 );
1105
1106 it.effect("leaves the paths out when GitLab did not answer the blobs query", () =>
1107 Effect.gen(function* () {
1108 mockedExecute.mockReturnValueOnce(
1109 Effect.succeed(
1110 output(
1111 JSON.stringify({
1112 iid: 7,
1113 title: "t",
1114 web_url: "https://gitlab.com/acme/web/-/merge_requests/7",
1115 source_branch: "feat",
1116 target_branch: "main",
1117 created_at: "2026-07-01T00:00:00Z",
1118 updated_at: "2026-07-01T00:00:00Z",
1119 diff_refs: { base_sha: "base", head_sha: "head", start_sha: "start" },
1120 }),
1121 ),
1122 ),
1123 );
1124 mockedExecute.mockReturnValueOnce(
1125 Effect.succeed(output(JSON.stringify({ data: { project: null } }))),
1126 );
1127 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1128
1129 const revisions = yield* cli.getFileRevisions({
1130 cwd: "/w",
1131 repository: "acme/web",
1132 number: 7,
1133 paths: ["src/a.ts", "src/b.ts"],
1134 });
1135
1136 expect([...revisions]).toEqual([]);
1137 }),
1138 );
1139
1140 it.effect("splits the paths across requests, because GitLab charges the query by how many", () =>
1141 Effect.gen(function* () {
1142 const paths = Array.from({ length: 150 }, (_, index) => `src/${index}.ts`);
1143 mockedExecute.mockReturnValueOnce(
1144 Effect.succeed(
1145 output(
1146 JSON.stringify({
1147 iid: 7,
1148 title: "t",
1149 web_url: "https://gitlab.com/acme/web/-/merge_requests/7",
1150 source_branch: "feat",
1151 target_branch: "main",
1152 created_at: "2026-07-01T00:00:00Z",
1153 updated_at: "2026-07-01T00:00:00Z",
1154 diff_refs: { base_sha: "base", head_sha: "head", start_sha: "start" },
1155 }),
1156 ),
1157 ),
1158 );
1159 mockedExecute.mockImplementation((request) => {
1160 const body = JSON.parse(request.stdin ?? "{}") as {
1161 readonly variables: { readonly paths: ReadonlyArray<string> };
1162 };
1163 return Effect.succeed(
1164 output(
1165 JSON.stringify({
1166 data: {
1167 project: {
1168 repository: {
1169 blobs: {
1170 nodes: body.variables.paths.map((path) => ({ path, oid: `oid-${path}` })),
1171 },
1172 },
1173 },
1174 },
1175 }),
1176 ),
1177 );
1178 });
1179 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1180
1181 const revisions = yield* cli.getFileRevisions({
1182 cwd: "/w",
1183 repository: "acme/web",
1184 number: 7,
1185 paths,
1186 });
1187
1188 assert.strictEqual(revisions.size, 150);
1189 assert.strictEqual(revisions.get("src/149.ts"), "oid-src/149.ts");
1190 assert.strictEqual(mockedExecute.mock.calls.length, 3);
1191 }),
1192 );
1193});