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