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("batches approval reads at GitLab's page limit and skips an empty list", () =>
100 Effect.gen(function* () {
101 mockedExecute.mockImplementation(({ stdin }) => {
102 const { variables } = JSON.parse(stdin ?? "{}");
103 return Effect.succeed(
104 output(
105 JSON.stringify({
106 data: {
107 metadata: { enterprise: true },
108 project: {
109 mergeRequests: {
110 nodes: variables.iids.map((iid: string) => ({
111 iid,
112 approved: true,
113 approvedBy: { nodes: [{ username: "reviewer" }] },
114 })),
115 },
116 },
117 },
118 }),
119 ),
120 );
121 });
122 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
123 const reference = { cwd: "/w", repository: "acme/web", host: "gitlab.internal" };
124 expect(yield* cli.getReviewDecisions({ ...reference, numbers: [] })).toEqual(new Map());
125 expect(mockedExecute).not.toHaveBeenCalled();
126 const decisions = yield* cli.getReviewDecisions({
127 ...reference,
128 numbers: Array.from({ length: 101 }, (_, index) => index + 1),
129 });
130 expect(callAt(0).host).toBe(reference.host);
131 expect(callAt(1).host).toBe(reference.host);
132 expect(decisions.size).toBe(101);
133 expect(decisions.get(101)).toBe("approved");
134 expect(mockedExecute).toHaveBeenCalledTimes(2);
135 expect(
136 [0, 1].map((index) => JSON.parse(callAt(index).stdin ?? "{}").variables.iids.length),
137 ).toEqual([100, 1]);
138 expect(argsOfCall(0)).toEqual([
139 "api",
140 "graphql",
141 "--method",
142 "POST",
143 "--input",
144 "-",
145 "--header",
146 "Content-Type: application/json",
147 ]);
148 }),
149 );
150
151 it.effect("asks GitLab for one row more than the page, to probe for a next page", () =>
152 Effect.gen(function* () {
153 mockedExecute.mockReturnValueOnce(Effect.succeed(output(mergeRequests(3, 1))));
154 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
155
156 const batch = yield* cli.listMergeRequests({
157 cwd: "/w",
158 repository: "acme/web",
159 state: "open",
160 involvement: "all",
161 viewer: "bilal",
162 limit: 10,
163 });
164
165 assert.strictEqual(batch.items.length, 3);
166 assert.isFalse(batch.truncated);
167 assert.strictEqual(batch.cursorAdvance, 3);
168 const path = argsOfCall(0)[1] ?? "";
169 expect(path).toContain("projects/acme%2Fweb/merge_requests");
170 expect(path).toContain("per_page=11");
171 expect(path).toContain("state=opened");
172 }),
173 );
174
175 it.effect("walks pages at a fixed size, because GitLab pages by offset", () =>
176 Effect.gen(function* () {
177 mockedExecute
178 .mockReturnValueOnce(Effect.succeed(output(mergeRequests(100, 1))))
179 .mockReturnValueOnce(Effect.succeed(output(mergeRequests(100, 101))));
180 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
181
182 const batch = yield* cli.listMergeRequests({
183 cwd: "/w",
184 repository: "acme/web",
185 state: "open",
186 involvement: "all",
187 viewer: "bilal",
188 limit: 150,
189 });
190
191 assert.strictEqual(batch.items.length, 150);
192 assert.isTrue(batch.truncated);
193 for (const index of [0, 1]) {
194 expect(argsOfCall(index)[1]).toContain("per_page=100");
195 }
196 expect(argsOfCall(0)[1]).toContain("page=1");
197 expect(argsOfCall(1)[1]).toContain("page=2");
198 }),
199 );
200
201 it.effect("asks GitLab for the labels, author and draft state it can filter on", () =>
202 Effect.gen(function* () {
203 mockedExecute.mockReturnValueOnce(Effect.succeed(output(mergeRequests(1, 1))));
204 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
205
206 yield* cli.listMergeRequests({
207 cwd: "/w",
208 repository: "acme/web",
209 state: "open",
210 involvement: "all",
211 viewer: "bilal",
212 limit: 10,
213 filters: {
214 labels: [["bug"], ["size:S", "size:XS"], ["a,b"], ["None"]],
215 excludedLabels: ["wontfix", "stale", "any"],
216 author: "@me",
217 draft: "only",
218 },
219 });
220
221 const params = new URLSearchParams((argsOfCall(0)[1] ?? "").split("?")[1]);
222 expect(params.get("labels")).toBe("bug");
223 expect(params.get("not[labels]")).toBe("wontfix,stale");
224 expect(params.get("author_username")).toBe("bilal");
225 expect(params.get("wip")).toBe("yes");
226 }),
227 );
228
229 it.effect("carries on from the number of rows already delivered", () =>
230 Effect.gen(function* () {
231 mockedExecute.mockReturnValueOnce(Effect.succeed(output(mergeRequests(3, 1))));
232 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
233
234 yield* cli.listMergeRequests({
235 cwd: "/w",
236 repository: "acme/web",
237 state: "open",
238 involvement: "all",
239 viewer: "bilal",
240 limit: 10,
241 cursor: { updatedBefore: "2026-07-02T00:00:00Z", delivered: 10 },
242 });
243
244 const path = argsOfCall(0)[1] ?? "";
245 expect(path).not.toContain("updated_before=");
246 expect(path).toContain("order_by=updated_at");
247 expect(path).toContain("per_page=11");
248 expect(path).toContain("page=1");
249 }),
250 );
251
252 it.effect("advances beyond several pages sharing the cursor timestamp", () =>
253 Effect.gen(function* () {
254 mockedExecute
255 .mockReturnValueOnce(Effect.succeed(output(mergeRequests(11, 144))))
256 .mockReturnValueOnce(Effect.succeed(output(mergeRequests(11, 155))));
257 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
258
259 const batch = yield* cli.listMergeRequests({
260 cwd: "/w",
261 repository: "acme/web",
262 state: "open",
263 involvement: "all",
264 viewer: "bilal",
265 limit: 10,
266 cursor: { updatedBefore: "2026-07-02T00:00:00Z", delivered: 150 },
267 });
268
269 expect(argsOfCall(0)[1]).toContain("per_page=11");
270 expect(argsOfCall(0)[1]).toContain("page=14");
271 expect(argsOfCall(1)[1]).toContain("page=15");
272 expect(batch.items.map((item) => item.number)).toEqual([
273 151, 152, 153, 154, 155, 156, 157, 158, 159, 160,
274 ]);
275 assert.isTrue(batch.truncated);
276 }),
277 );
278
279 it.effect("advances the cursor through malformed raw rows", () =>
280 Effect.gen(function* () {
281 const rows = JSON.parse(mergeRequests(2, 1)) as ReadonlyArray<unknown>;
282 mockedExecute.mockReturnValueOnce(
283 Effect.succeed(output(JSON.stringify([{ iid: "malformed" }, ...rows]))),
284 );
285 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
286
287 const batch = yield* cli.listMergeRequests({
288 cwd: "/w",
289 repository: "acme/web",
290 state: "open",
291 involvement: "all",
292 viewer: "bilal",
293 limit: 2,
294 });
295
296 expect(batch.items.map((item) => item.number)).toEqual([1, 2]);
297 assert.strictEqual(batch.cursorAdvance, 3);
298 assert.isTrue(batch.truncated);
299 }),
300 );
301
302 it.effect("URL-encodes a search, so it cannot add a parameter of its own", () =>
303 Effect.gen(function* () {
304 mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
305 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
306
307 yield* cli.listMergeRequests({
308 cwd: "/w",
309 repository: "acme/web",
310 state: "open",
311 involvement: "all",
312 viewer: "bilal",
313 limit: 10,
314 query: '-a&per_page=1 "b"',
315 });
316
317 const path = argsOfCall(0)[1] ?? "";
318 expect(path).toContain("search=-a%26per_page%3D1%20%22b%22");
319 assert.strictEqual(path.match(/per_page=/g)?.length, 1);
320 }),
321 );
322
323 it.effect("stops walking on a short page", () =>
324 Effect.gen(function* () {
325 mockedExecute.mockReturnValueOnce(Effect.succeed(output(mergeRequests(40, 1))));
326 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
327
328 const batch = yield* cli.listMergeRequests({
329 cwd: "/w",
330 repository: "acme/web",
331 state: "open",
332 involvement: "all",
333 viewer: "bilal",
334 limit: 150,
335 });
336
337 assert.strictEqual(batch.items.length, 40);
338 assert.isFalse(batch.truncated);
339 assert.strictEqual(mockedExecute.mock.calls.length, 1);
340 }),
341 );
342
343 it.effect("stops walking when every row on a page fails to decode", () =>
344 Effect.gen(function* () {
345 const unusable = JSON.stringify(Array.from({ length: 100 }, () => ({ iid: "nope" })));
346 mockedExecute.mockReturnValue(Effect.succeed(output(unusable)));
347 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
348
349 const batch = yield* cli.listMergeRequests({
350 cwd: "/w",
351 repository: "acme/web",
352 state: "open",
353 involvement: "all",
354 viewer: "bilal",
355 limit: 150,
356 });
357
358 assert.strictEqual(batch.items.length, 0);
359 assert.strictEqual(mockedExecute.mock.calls.length, 2);
360 }),
361 );
362
363 it.effect.each([
364 { action: "merge", autoMerge: "false", mergeMethod: "squash" },
365 { action: "enable-auto-merge", autoMerge: "true", mergeMethod: "squash" },
366 { action: "merge", autoMerge: "false", mergeMethod: "rebase" },
367 ] as const)(
368 "$action with $mergeMethod succeeds on a project requiring the current source SHA",
369 ({ action, autoMerge, mergeMethod }) =>
370 Effect.gen(function* () {
371 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
372
373 for (const headSha of ["first-head", "updated-head"]) {
374 let currentHeadSha = headSha;
375 mockedExecute.mockImplementation(({ cwd, args }) => {
376 if (args[0] === "mr" && args[1] === "rebase") {
377 return Effect.sync(() => {
378 currentHeadSha = `${headSha}-rebased`;
379 return output("");
380 });
381 }
382 if (args[0] === "api") {
383 return Effect.succeed(
384 output(
385 mergeRequestJson({
386 diff_refs: { base_sha: "base", head_sha: currentHeadSha, start_sha: "start" },
387 }),
388 ),
389 );
390 }
391 if (args.includes("--rebase") || args[args.indexOf("--sha") + 1] !== currentHeadSha) {
392 return Effect.fail(
393 new GitLabCli.GitLabCliCommandError({
394 operation: "execute",
395 command: "glab",
396 cwd,
397 cause: new Error(
398 args.includes("--rebase")
399 ? "Merge must not combine --rebase with --sha: rebase changes the source HEAD"
400 : "SHA must match the current source branch HEAD",
401 ),
402 }),
403 );
404 }
405 return Effect.succeed(output(""));
406 });
407
408 yield* cli.runMergeRequestAction({
409 cwd: "/w",
410 repository: "acme/web",
411 number: 7,
412 action,
413 mergeMethod,
414 });
415
416 const callsPerAction = mergeMethod === "rebase" ? 3 : 2;
417 expect(
418 mockedExecute.mock.calls.slice(-callsPerAction).map(([input]) => input.args),
419 ).toEqual([
420 ...(mergeMethod === "rebase" ? [["mr", "rebase", "7", "--repo", "acme/web"]] : []),
421 ["api", "projects/acme%2Fweb/merge_requests/7"],
422 [
423 "mr",
424 "merge",
425 "7",
426 "--repo",
427 "acme/web",
428 `--auto-merge=${autoMerge}`,
429 "--yes",
430 ...(mergeMethod === "squash" ? ["--squash"] : []),
431 "--sha",
432 mergeMethod === "rebase" ? `${headSha}-rebased` : headSha,
433 ],
434 ]);
435 }
436 expect(mockedExecute).toHaveBeenCalledTimes(mergeMethod === "rebase" ? 6 : 4);
437 }),
438 );
439
440 it.effect.each(["merge", "enable-auto-merge"] as const)(
441 "does not run %s when GitLab has no diff revisions",
442 (action) =>
443 Effect.gen(function* () {
444 mockedExecute.mockReturnValue(
445 Effect.succeed(output(mergeRequestJson({ diff_refs: null }))),
446 );
447 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
448
449 const result = yield* Effect.result(
450 cli.runMergeRequestAction({
451 cwd: "/w",
452 repository: "acme/web",
453 number: 7,
454 action,
455 mergeMethod: "squash",
456 }),
457 );
458
459 expect(mockedExecute.mock.calls.map(([input]) => input.args)).toEqual([
460 ["api", "projects/acme%2Fweb/merge_requests/7"],
461 ]);
462 expect(result).toMatchObject({
463 _tag: "Failure",
464 failure: { _tag: "GitLabDiffRefsUnavailableError" },
465 });
466 }),
467 );
468
469 it.effect("sends a comment body over stdin, never in argv", () =>
470 Effect.gen(function* () {
471 mockedExecute.mockReturnValueOnce(Effect.succeed(output("")));
472 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
473
474 yield* cli.commentOnMergeRequest({
475 cwd: "/w",
476 repository: "acme/web",
477 number: 7,
478 body: "true",
479 });
480
481 const call = mockedExecute.mock.calls[0];
482 assert.isDefined(call);
483 expect(call[0].args).toEqual([
484 "api",
485 "projects/acme%2Fweb/merge_requests/7/notes",
486 "--method",
487 "POST",
488 "--input",
489 "-",
490 "--header",
491 "Content-Type: application/json",
492 ]);
493 expect(call[0].stdin).toBe('{"body":"true"}');
494 }),
495 );
496
497 it.effect("reads one diff page and hands back the cursor for the next", () =>
498 Effect.gen(function* () {
499 mockedExecute.mockReturnValueOnce(Effect.succeed(output(diffPage(0))));
500 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
501
502 const diff = yield* cli.getMergeRequestDiff({
503 cwd: "/w",
504 repository: "acme/web",
505 number: 7,
506 });
507
508 assert.strictEqual(mockedExecute.mock.calls.length, 1);
509 assert.isNotNull(diff.nextCursor);
510 assert.isFalse(diff.truncated);
511 expect(argsOfCall(0)[1]).toContain("merge_requests/7/diffs?per_page=30&page=1");
512 }),
513 );
514
515 it.effect(
516 "pages a merge request diff 30 files at a time, which GitLab 15.7 to 17.10 accept",
517 () =>
518 Effect.gen(function* () {
519 mockedExecute
520 .mockReturnValueOnce(Effect.succeed(output(diffPage(0, 30))))
521 .mockReturnValueOnce(Effect.succeed(output(diffPage(30, 30))))
522 .mockReturnValueOnce(Effect.succeed(output(diffPage(60, 5))));
523 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
524 const target = { cwd: "/w", repository: "acme/web", number: 7 };
525
526 let patch = "";
527 let cursor: string | undefined;
528 do {
529 const slice = yield* cli.getMergeRequestDiff({ ...target, cursor });
530 patch += slice.patch;
531 cursor = slice.nextCursor ?? undefined;
532 } while (cursor !== undefined);
533
534 expect(mockedExecute.mock.calls.map(([call]) => call.args[1])).toEqual([
535 "projects/acme%2Fweb/merge_requests/7/diffs?per_page=30&page=1",
536 "projects/acme%2Fweb/merge_requests/7/diffs?per_page=30&page=2",
537 "projects/acme%2Fweb/merge_requests/7/diffs?per_page=30&page=3",
538 ]);
539 assert.strictEqual(patch.match(/^diff --git /gm)?.length, 65);
540 expect(patch).toContain("diff --git a/src/64.ts b/src/64.ts");
541 }),
542 );
543
544 it.effect("refuses a cursor it never handed out rather than reading it into a query", () =>
545 Effect.gen(function* () {
546 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
547
548 const error = yield* Effect.flip(
549 cli.getMergeRequestDiff({
550 cwd: "/w",
551 repository: "acme/web",
552 number: 7,
553 cursor: "1&per_page=1",
554 }),
555 );
556
557 assert.strictEqual(error._tag, "GitLabDiffCursorError");
558 assert.strictEqual(mockedExecute.mock.calls.length, 0);
559 }),
560 );
561
562 it.effect("reads a named commit from its own diff, and pages inside it", () =>
563 Effect.gen(function* () {
564 mockedExecute
565 .mockReturnValueOnce(Effect.succeed(output(diffPage(0))))
566 .mockReturnValueOnce(Effect.succeed(output(diffPage(100, 3))));
567 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
568 const target = {
569 cwd: "/w",
570 repository: "acme/web",
571 number: 7,
572 commit: "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0",
573 };
574
575 const first = yield* cli.getMergeRequestDiff(target);
576 assert.isNotNull(first.nextCursor);
577 const second = yield* cli.getMergeRequestDiff({ ...target, cursor: first.nextCursor });
578
579 const commitPath =
580 "projects/acme%2Fweb/repository/commits/a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0/diff";
581 expect(argsOfCall(0)[1]).toBe(`${commitPath}?per_page=100&page=1`);
582 expect(argsOfCall(1)[1]).toBe(`${commitPath}?per_page=100&page=2`);
583 assert.isNull(second.nextCursor);
584 }),
585 );
586
587 it.effect("refuses a commit that is not a sha rather than reading it into a path", () =>
588 Effect.gen(function* () {
589 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
590
591 const error = yield* Effect.flip(
592 cli.getMergeRequestDiff({
593 cwd: "/w",
594 repository: "acme/web",
595 number: 7,
596 commit: "../../merge_requests/8/diffs",
597 }),
598 );
599
600 assert.strictEqual(error._tag, "GitLabDiffCommitError");
601 assert.strictEqual(mockedExecute.mock.calls.length, 0);
602 }),
603 );
604
605 it.effect("reports a commit with no parent as a structured error", () =>
606 Effect.gen(function* () {
607 mockedExecute.mockReturnValueOnce(
608 Effect.succeed(output(JSON.stringify({ id: "a1b2c3d", parent_ids: [] }))),
609 );
610 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
611
612 const error = yield* Effect.flip(
613 cli.getMergeRequestDiffFileContents({
614 cwd: "/w",
615 repository: "acme/web",
616 number: 7,
617 commit: "a1b2c3d",
618 changeType: "change",
619 oldPath: "src/a.ts",
620 newPath: "src/a.ts",
621 }),
622 );
623
624 assert.strictEqual(error._tag, "GitLabDiffCommitParentUnavailableError");
625 if (error._tag === "GitLabDiffCommitParentUnavailableError") {
626 assert.strictEqual(error.commit, "a1b2c3d");
627 }
628 }),
629 );
630
631 it.effect("expands a new file from a root commit without requiring a parent", () =>
632 Effect.gen(function* () {
633 mockedExecute.mockReturnValueOnce(
634 Effect.succeed(output(JSON.stringify({ id: "a1b2c3d", parent_ids: [] }))),
635 );
636 mockedExecute.mockReturnValueOnce(Effect.succeed(output("first contents\n")));
637 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
638
639 const contents = yield* cli.getMergeRequestDiffFileContents({
640 cwd: "/w",
641 repository: "acme/web",
642 number: 7,
643 commit: "a1b2c3d",
644 changeType: "new",
645 oldPath: "src/first.ts",
646 newPath: "src/first.ts",
647 });
648
649 expect(contents).toEqual({ oldContents: "", newContents: "first contents\n" });
650 expect(argsOfCall(1)[1]).toContain("raw?ref=a1b2c3d");
651 }),
652 );
653
654 it.effect("reports undecodable diff file contents as binary", () =>
655 Effect.gen(function* () {
656 mockedExecute.mockReturnValueOnce(
657 Effect.succeed(
658 output(
659 JSON.stringify({
660 diff_refs: {
661 base_sha: "a1b2c3d",
662 head_sha: "b1c2d3e",
663 start_sha: "a1b2c3d",
664 },
665 }),
666 ),
667 ),
668 );
669 mockedExecute.mockReturnValueOnce(
670 Effect.succeed(output("binary\uFFFDcontents", false, true)),
671 );
672 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
673
674 const error = yield* Effect.flip(
675 cli.getMergeRequestDiffFileContents({
676 cwd: "/w",
677 repository: "acme/web",
678 number: 7,
679 changeType: "deleted",
680 oldPath: "assets/logo.png",
681 newPath: "assets/logo.png",
682 }),
683 );
684
685 assert.strictEqual(error._tag, "GitLabDiffFileContentsUnavailableError");
686 if (error._tag === "GitLabDiffFileContentsUnavailableError") {
687 assert.strictEqual(error.path, "assets/logo.png");
688 assert.strictEqual(error.reason, "binary");
689 }
690 }),
691 );
692
693 it.effect("returns valid text containing a literal replacement character", () =>
694 Effect.gen(function* () {
695 mockedExecute.mockReturnValueOnce(
696 Effect.succeed(
697 output(
698 JSON.stringify({
699 diff_refs: {
700 base_sha: "a1b2c3d",
701 head_sha: "b1c2d3e",
702 start_sha: "a1b2c3d",
703 },
704 }),
705 ),
706 ),
707 );
708 mockedExecute.mockReturnValueOnce(Effect.succeed(output("before\uFFFDafter")));
709 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
710
711 const contents = yield* cli.getMergeRequestDiffFileContents({
712 cwd: "/w",
713 repository: "acme/web",
714 number: 7,
715 changeType: "deleted",
716 oldPath: "docs/encoding.md",
717 newPath: "docs/encoding.md",
718 });
719
720 assert.strictEqual(contents.oldContents, "before\uFFFDafter");
721 }),
722 );
723
724 it.effect("ends the diff on a page with no files rather than asking for it again", () =>
725 Effect.gen(function* () {
726 mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
727 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
728
729 const diff = yield* cli.getMergeRequestDiff({
730 cwd: "/w",
731 repository: "acme/web",
732 number: 7,
733 cursor: "4",
734 });
735
736 assert.strictEqual(diff.patch, "");
737 assert.isNull(diff.nextCursor);
738 }),
739 );
740
741 it.effect("fails a diff page cut off mid-JSON rather than calling the diff whole", () =>
742 Effect.gen(function* () {
743 mockedExecute.mockReturnValueOnce(
744 Effect.succeed({ ...output('[{"old_path":"src/x.ts","new_p'), stdoutTruncated: true }),
745 );
746 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
747
748 const error = yield* Effect.flip(
749 cli.getMergeRequestDiff({ cwd: "/w", repository: "acme/web", number: 7 }),
750 );
751
752 assert.strictEqual(error._tag, "GitLabMergeRequestReadError");
753 }),
754 );
755
756 it.effect("offers no squash when the project does not say it allows one", () =>
757 Effect.gen(function* () {
758 mockedExecute.mockReturnValueOnce(
759 Effect.succeed(output(JSON.stringify({ merge_method: "merge" }))),
760 );
761 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
762
763 const capabilities = yield* cli.getProjectMergeCapabilities({
764 cwd: "/w",
765 repository: "acme/web",
766 });
767
768 assert.deepStrictEqual(capabilities, { merge: true, squash: false, rebase: false });
769 }),
770 );
771
772 it.effect("reads the project's merge settings as its merge capabilities", () =>
773 Effect.gen(function* () {
774 mockedExecute.mockReturnValueOnce(
775 Effect.succeed(output(JSON.stringify({ merge_method: "ff", squash_option: "never" }))),
776 );
777 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
778
779 const capabilities = yield* cli.getProjectMergeCapabilities({
780 cwd: "/w",
781 repository: "acme/web",
782 });
783
784 assert.deepStrictEqual(capabilities, { merge: false, squash: false, rebase: true });
785 }),
786 );
787
788 it.effect("fails when the authenticated account has no username", () =>
789 Effect.gen(function* () {
790 mockedExecute.mockReturnValueOnce(Effect.succeed(output(JSON.stringify({ username: "" }))));
791 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
792
793 const error = yield* Effect.flip(cli.getViewerUsername({ cwd: "/w" }));
794
795 assert.strictEqual(error._tag, "GitLabViewerUnavailableError");
796 }),
797 );
798
799 it.effect("walks the notes until GitLab answers with a short page", () =>
800 Effect.gen(function* () {
801 mockedExecute.mockReturnValueOnce(Effect.succeed(output(notes(100, 1))));
802 mockedExecute.mockReturnValueOnce(Effect.succeed(output(notes(2, 101))));
803 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
804
805 const { comments, truncated } = yield* cli.listNotes({
806 cwd: "/w",
807 repository: "acme/web",
808 number: 7,
809 });
810
811 expect(argsOfCall(0).join(" ")).toContain("page=1");
812 expect(argsOfCall(1).join(" ")).toContain("page=2");
813 assert.strictEqual(comments.length, 102);
814 assert.isFalse(truncated);
815 }),
816 );
817
818 it.effect("stops the note walk at its bound and says the conversation was cut short", () =>
819 Effect.gen(function* () {
820 mockedExecute.mockReturnValue(Effect.succeed(output(notes(100, 1))));
821 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
822
823 const { truncated } = yield* cli.listNotes({
824 cwd: "/w",
825 repository: "acme/web",
826 number: 7,
827 });
828
829 assert.strictEqual(mockedExecute.mock.calls.length, 10);
830 assert.isTrue(truncated);
831 }),
832 );
833
834 it.effect("reads a positioned discussion as a thread anchored to its line", () =>
835 Effect.gen(function* () {
836 mockedExecute.mockReturnValueOnce(
837 Effect.succeed(
838 output(
839 JSON.stringify([
840 {
841 id: "abc123",
842 notes: [
843 {
844 id: 1,
845 body: "rename this",
846 author: { username: "bilal", avatar_url: "https://avatars/b.png" },
847 created_at: "2026-07-01T00:00:00Z",
848 resolvable: true,
849 resolved: true,
850 position: {
851 position_type: "text",
852 new_path: "src/a.ts",
853 old_path: "src/a.ts",
854 new_line: 12,
855 old_line: null,
856 },
857 },
858 {
859 id: 2,
860 body: "done",
861 author: { username: "julius" },
862 created_at: "2026-07-01T01:00:00Z",
863 },
864 ],
865 },
866 { id: "def456", notes: [{ id: 3, body: "ship it", created_at: "2026-07-01Z" }] },
867 ]),
868 ),
869 ),
870 );
871 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
872
873 const { threads } = yield* cli.listDiscussions({
874 cwd: "/w",
875 repository: "acme/web",
876 number: 7,
877 });
878
879 assert.strictEqual(threads.length, 1);
880 expect(threads[0]).toMatchObject({
881 id: "abc123",
882 path: "src/a.ts",
883 line: 12,
884 side: "right",
885 isResolved: true,
886 });
887 assert.strictEqual(threads[0]?.comments.length, 2);
888 }),
889 );
890
891 it.effect("sends a review as its comments, then its summary, then the verdict", () =>
892 Effect.gen(function* () {
893 mockedExecute.mockReturnValueOnce(
894 Effect.succeed(
895 output(
896 JSON.stringify({
897 iid: 7,
898 title: "t",
899 web_url: "https://gitlab.com/acme/web/-/merge_requests/7",
900 source_branch: "feat",
901 target_branch: "main",
902 created_at: "2026-07-01T00:00:00Z",
903 updated_at: "2026-07-01T00:00:00Z",
904 diff_refs: { base_sha: "base", head_sha: "head", start_sha: "start" },
905 }),
906 ),
907 ),
908 );
909 mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
910 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
911
912 yield* cli.submitReview({
913 cwd: "/w",
914 repository: "acme/web",
915 number: 7,
916 verdict: "approve",
917 body: "Looks right.",
918 comments: [
919 {
920 path: "src/b.ts",
921 oldPath: "src/a.ts",
922 position: { kind: "deleted", oldLine: 4 },
923 body: "why remove?",
924 },
925 ],
926 });
927
928 expect(argsOfCall(0)[1]).toContain("merge_requests/7");
929 expect(argsOfCall(1)[1]).toContain("/discussions");
930 expect(JSON.parse(callAt(1).stdin ?? "")).toEqual({
931 body: "why remove?",
932 position: {
933 base_sha: "base",
934 head_sha: "head",
935 start_sha: "start",
936 position_type: "text",
937 old_path: "src/a.ts",
938 new_path: "src/b.ts",
939 old_line: 4,
940 },
941 });
942 expect(argsOfCall(2)[1]).toContain("/notes");
943 expect(argsOfCall(3)[1]).toContain("/approve");
944 }),
945 );
946
947 it.effect("removes an award by listing them and deleting the reader's own id", () =>
948 Effect.gen(function* () {
949 mockedExecute.mockReturnValueOnce(
950 Effect.succeed(output(JSON.stringify({ username: "bilal" }))),
951 );
952 mockedExecute.mockReturnValueOnce(
953 Effect.succeed(
954 output(
955 JSON.stringify([
956 { id: 5, name: "thumbsup", user: { username: "bilal" } },
957 { id: 6, name: "thumbsup", user: { username: "julius" } },
958 ]),
959 ),
960 ),
961 );
962 mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
963 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
964
965 yield* cli.setReaction({
966 cwd: "/w",
967 repository: "acme/web",
968 number: 7,
969 content: "thumbs-up",
970 reacted: false,
971 });
972
973 assert.strictEqual(mockedExecute.mock.calls.length, 3);
974 expect(argsOfCall(2)).toEqual([
975 "api",
976 "projects/acme%2Fweb/merge_requests/7/award_emoji/5",
977 "--method",
978 "DELETE",
979 ]);
980 }),
981 );
982
983 it.effect("names a merge request with no diff revisions rather than calling it unreadable", () =>
984 Effect.gen(function* () {
985 mockedExecute.mockReturnValueOnce(
986 Effect.succeed(
987 output(
988 JSON.stringify({
989 iid: 7,
990 title: "t",
991 web_url: "https://gitlab.com/acme/web/-/merge_requests/7",
992 source_branch: "feat",
993 target_branch: "main",
994 created_at: "2026-07-01T00:00:00Z",
995 updated_at: "2026-07-01T00:00:00Z",
996 diff_refs: null,
997 }),
998 ),
999 ),
1000 );
1001 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1002
1003 const error = yield* Effect.flip(
1004 cli.submitReview({
1005 cwd: "/w",
1006 repository: "acme/web",
1007 number: 7,
1008 verdict: "comment",
1009 body: "",
1010 comments: [{ path: "src/a.ts", position: { kind: "added", newLine: 4 }, body: "nit" }],
1011 }),
1012 );
1013
1014 assert.strictEqual(error._tag, "GitLabDiffRefsUnavailableError");
1015 }),
1016 );
1017
1018 it.effect("shows a failed child pipeline that left the head pipeline green", () =>
1019 Effect.gen(function* () {
1020 mockedExecute
1021 .mockReturnValueOnce(
1022 Effect.succeed(
1023 output(
1024 mergeRequestJson({
1025 // A fork's pipeline runs in the source project, so its id is not the target's.
1026 head_pipeline: {
1027 id: 31,
1028 project_id: 12,
1029 status: "success",
1030 web_url: "https://gitlab.com/bilal/web/-/pipelines/31",
1031 },
1032 }),
1033 ),
1034 ),
1035 )
1036 .mockReturnValueOnce(
1037 Effect.succeed(
1038 output(
1039 JSON.stringify([
1040 {
1041 name: "deploy",
1042 status: "success",
1043 downstream_pipeline: {
1044 status: "failed",
1045 web_url: "https://gitlab.com/bilal/web/-/pipelines/32",
1046 },
1047 },
1048 { name: "docs", status: "created", downstream_pipeline: null },
1049 ]),
1050 ),
1051 ),
1052 );
1053 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1054
1055 const detail = yield* cli.getMergeRequestDetail({
1056 cwd: "/w",
1057 repository: "acme/web",
1058 number: 7,
1059 });
1060
1061 expect(detail.checks.map((check) => [check.name, check.status, check.url])).toEqual([
1062 ["Pipeline", "success", "https://gitlab.com/bilal/web/-/pipelines/31"],
1063 ["deploy", "failure", "https://gitlab.com/bilal/web/-/pipelines/32"],
1064 ]);
1065 expect(argsOfCall(1)[1]).toBe("projects/12/pipelines/31/bridges?per_page=100");
1066 }),
1067 );
1068
1069 it.effect("keeps the one pipeline check when the trigger jobs cannot be read whole", () =>
1070 Effect.gen(function* () {
1071 const detailOutput = output(
1072 mergeRequestJson({ head_pipeline: { id: 31, project_id: 12, status: "success" } }),
1073 );
1074 const failedChild = { name: "deploy", downstream_pipeline: { status: "failed" } };
1075 mockedExecute
1076 .mockReturnValueOnce(Effect.succeed(detailOutput))
1077 .mockReturnValueOnce(
1078 Effect.fail(
1079 new GitLabCli.GitLabCliCommandError({
1080 operation: "execute",
1081 command: "glab",
1082 cwd: "/w",
1083 cause: new Error("403 Forbidden"),
1084 }),
1085 ),
1086 )
1087 .mockReturnValueOnce(Effect.succeed(detailOutput))
1088 // A full page may have left out the trigger job whose pipeline failed.
1089 .mockReturnValueOnce(
1090 Effect.succeed(output(JSON.stringify(Array.from({ length: 100 }, () => failedChild)))),
1091 );
1092 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1093
1094 for (const scenario of ["read fails", "page is full"]) {
1095 const detail = yield* cli.getMergeRequestDetail({
1096 cwd: "/w",
1097 repository: "acme/web",
1098 number: 7,
1099 });
1100 expect(
1101 detail.checks.map((check) => [check.name, check.status]),
1102 scenario,
1103 ).toEqual([["Pipeline", "success"]]);
1104 }
1105 }),
1106 );
1107
1108 it.effect("reads merge permissions without reading the trigger jobs", () =>
1109 Effect.gen(function* () {
1110 mockedExecute.mockReturnValueOnce(
1111 Effect.succeed(
1112 output(
1113 mergeRequestJson({
1114 head_pipeline: { id: 31, project_id: 12, status: "success" },
1115 user: { can_merge: false },
1116 }),
1117 ),
1118 ),
1119 );
1120 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1121
1122 const detail = yield* cli.getMergeRequestDetail({
1123 cwd: "/w",
1124 repository: "acme/web",
1125 number: 7,
1126 downstreamChecks: false,
1127 });
1128
1129 expect(detail.viewerCanMerge).toBe(false);
1130 expect(mockedExecute).toHaveBeenCalledTimes(1);
1131 }),
1132 );
1133
1134 it.effect("reads who has access to the project and who is already on the merge request", () =>
1135 Effect.gen(function* () {
1136 mockedExecute
1137 .mockReturnValueOnce(Effect.succeed(output(mergeRequestJson({ reviewers: [reviewer] }))))
1138 .mockReturnValueOnce(
1139 Effect.succeed(output(JSON.stringify([author, reviewer, { id: 9, username: "hubot" }]))),
1140 );
1141 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1142
1143 const list = yield* cli.listReviewerCandidates({
1144 cwd: "/w",
1145 repository: "acme/web",
1146 number: 7,
1147 });
1148
1149 expect(argsOfCall(1)[1]).toBe("projects/acme%2Fweb/users?per_page=100");
1150 expect(list.candidates.map((candidate) => [candidate.id, candidate.isRequested])).toEqual([
1151 ["5", true],
1152 ["9", false],
1153 ]);
1154 assert.isFalse(list.truncated);
1155 }),
1156 );
1157
1158 it.effect("writes the reviewer set back with the one being asked added to it", () =>
1159 Effect.gen(function* () {
1160 mockedExecute
1161 .mockReturnValueOnce(Effect.succeed(output(mergeRequestJson({ reviewers: [reviewer] }))))
1162 .mockReturnValueOnce(Effect.succeed(output("{}")));
1163 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1164
1165 yield* cli.setReviewerRequest({
1166 cwd: "/w",
1167 repository: "acme/web",
1168 number: 7,
1169 reviewers: [{ id: "9" }],
1170 requested: true,
1171 });
1172
1173 expect(argsOfCall(1)).toContain("PUT");
1174 expect(JSON.parse(callAt(1).stdin ?? "")).toEqual({ reviewer_ids: [5, 9] });
1175 }),
1176 );
1177
1178 it.effect("takes a reviewer out of the set rather than clearing it", () =>
1179 Effect.gen(function* () {
1180 mockedExecute
1181 .mockReturnValueOnce(
1182 Effect.succeed(
1183 output(mergeRequestJson({ reviewers: [reviewer, { id: 9, username: "hubot" }] })),
1184 ),
1185 )
1186 .mockReturnValueOnce(Effect.succeed(output("{}")));
1187 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1188
1189 yield* cli.setReviewerRequest({
1190 cwd: "/w",
1191 repository: "acme/web",
1192 number: 7,
1193 reviewers: [{ id: "9" }],
1194 requested: false,
1195 });
1196
1197 expect(JSON.parse(callAt(1).stdin ?? "")).toEqual({ reviewer_ids: [5] });
1198 }),
1199 );
1200
1201 it.effect("ignores an id GitLab could not have handed out, which names nobody", () =>
1202 Effect.gen(function* () {
1203 mockedExecute
1204 .mockReturnValueOnce(Effect.succeed(output(mergeRequestJson({ reviewers: [reviewer] }))))
1205 .mockReturnValueOnce(Effect.succeed(output("{}")));
1206 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1207
1208 yield* cli.setReviewerRequest({
1209 cwd: "/w",
1210 repository: "acme/web",
1211 number: 7,
1212 reviewers: [{ id: "octocat" }],
1213 requested: true,
1214 });
1215
1216 expect(JSON.parse(callAt(1).stdin ?? "")).toEqual({ reviewer_ids: [5] });
1217 }),
1218 );
1219 it.effect("reads blob ids for the marked paths at the merge request's head", () =>
1220 Effect.gen(function* () {
1221 mockedExecute.mockReturnValueOnce(
1222 Effect.succeed(
1223 output(
1224 JSON.stringify({
1225 iid: 7,
1226 title: "t",
1227 web_url: "https://gitlab.com/acme/web/-/merge_requests/7",
1228 source_branch: "feat",
1229 target_branch: "main",
1230 created_at: "2026-07-01T00:00:00Z",
1231 updated_at: "2026-07-01T00:00:00Z",
1232 diff_refs: { base_sha: "base", head_sha: "head", start_sha: "start" },
1233 }),
1234 ),
1235 ),
1236 );
1237 mockedExecute.mockReturnValueOnce(
1238 Effect.succeed(
1239 output(
1240 JSON.stringify({
1241 data: {
1242 project: { repository: { blobs: { nodes: [{ path: "src/a.ts", oid: "aaa" }] } } },
1243 },
1244 }),
1245 ),
1246 ),
1247 );
1248 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1249
1250 const revisions = yield* cli.getFileRevisions({
1251 cwd: "/w",
1252 repository: "acme/web",
1253 number: 7,
1254 paths: ["src/a.ts", "src/gone.ts"],
1255 });
1256
1257 expect([...revisions]).toEqual([
1258 ["src/a.ts", "aaa"],
1259 ["src/gone.ts", ""],
1260 ]);
1261 const body: unknown = JSON.parse(callAt(1).stdin ?? "{}");
1262 expect(body).toMatchObject({
1263 variables: { fullPath: "acme/web", ref: "head", paths: ["src/a.ts", "src/gone.ts"] },
1264 });
1265 }),
1266 );
1267
1268 it.effect("leaves the paths out when GitLab did not answer the blobs query", () =>
1269 Effect.gen(function* () {
1270 mockedExecute.mockReturnValueOnce(
1271 Effect.succeed(
1272 output(
1273 JSON.stringify({
1274 iid: 7,
1275 title: "t",
1276 web_url: "https://gitlab.com/acme/web/-/merge_requests/7",
1277 source_branch: "feat",
1278 target_branch: "main",
1279 created_at: "2026-07-01T00:00:00Z",
1280 updated_at: "2026-07-01T00:00:00Z",
1281 diff_refs: { base_sha: "base", head_sha: "head", start_sha: "start" },
1282 }),
1283 ),
1284 ),
1285 );
1286 mockedExecute.mockReturnValueOnce(
1287 Effect.succeed(output(JSON.stringify({ data: { project: null } }))),
1288 );
1289 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1290
1291 const revisions = yield* cli.getFileRevisions({
1292 cwd: "/w",
1293 repository: "acme/web",
1294 number: 7,
1295 paths: ["src/a.ts", "src/b.ts"],
1296 });
1297
1298 expect([...revisions]).toEqual([]);
1299 }),
1300 );
1301
1302 it.effect("splits the paths across requests, because GitLab charges the query by how many", () =>
1303 Effect.gen(function* () {
1304 const paths = Array.from({ length: 150 }, (_, index) => `src/${index}.ts`);
1305 mockedExecute.mockReturnValueOnce(
1306 Effect.succeed(
1307 output(
1308 JSON.stringify({
1309 iid: 7,
1310 title: "t",
1311 web_url: "https://gitlab.com/acme/web/-/merge_requests/7",
1312 source_branch: "feat",
1313 target_branch: "main",
1314 created_at: "2026-07-01T00:00:00Z",
1315 updated_at: "2026-07-01T00:00:00Z",
1316 diff_refs: { base_sha: "base", head_sha: "head", start_sha: "start" },
1317 }),
1318 ),
1319 ),
1320 );
1321 mockedExecute.mockImplementation((request) => {
1322 const body = JSON.parse(request.stdin ?? "{}") as {
1323 readonly variables: { readonly paths: ReadonlyArray<string> };
1324 };
1325 return Effect.succeed(
1326 output(
1327 JSON.stringify({
1328 data: {
1329 project: {
1330 repository: {
1331 blobs: {
1332 nodes: body.variables.paths.map((path) => ({ path, oid: `oid-${path}` })),
1333 },
1334 },
1335 },
1336 },
1337 }),
1338 ),
1339 );
1340 });
1341 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1342
1343 const revisions = yield* cli.getFileRevisions({
1344 cwd: "/w",
1345 repository: "acme/web",
1346 number: 7,
1347 paths,
1348 });
1349
1350 assert.strictEqual(revisions.size, 150);
1351 assert.strictEqual(revisions.get("src/149.ts"), "oid-src/149.ts");
1352 assert.strictEqual(mockedExecute.mock.calls.length, 3);
1353 }),
1354 );
1355
1356 it.effect(
1357 "reads line counts a hundred at a time per project, keeping the reads that answered",
1358 () =>
1359 Effect.gen(function* () {
1360 const variablesOf = (stdin: string | undefined) =>
1361 (
1362 JSON.parse(stdin ?? "{}") as {
1363 readonly variables: {
1364 readonly fullPath: string;
1365 readonly iids: ReadonlyArray<string>;
1366 };
1367 }
1368 ).variables;
1369 mockedExecute.mockImplementation((request) => {
1370 const { fullPath, iids } = variablesOf(request.stdin);
1371 // GitLab answers only what it has (iid 3 is missing), and one project's read fails.
1372 const nodes = iids
1373 .filter((iid) => iid !== "3")
1374 .map((iid) => ({ iid, diffStatsSummary: { additions: Number(iid), deletions: 1 } }));
1375 return Effect.succeed(
1376 output(
1377 JSON.stringify(
1378 fullPath === "acme/api"
1379 ? { errors: [{ message: "Query timed out" }] }
1380 : { data: { project: { mergeRequests: { nodes } } } },
1381 ),
1382 ),
1383 );
1384 });
1385 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1386
1387 const stats = yield* cli.listMergeRequestStats({
1388 cwd: "/w",
1389 changeRequests: [
1390 ...Array.from({ length: 150 }, (_, index) => ({
1391 repository: "acme/web",
1392 number: index + 1,
1393 })),
1394 { repository: "acme/api", number: 9 },
1395 ],
1396 });
1397
1398 expect(stats).toHaveLength(149);
1399 expect(stats).toContainEqual({
1400 repository: "acme/web",
1401 number: 150,
1402 additions: 150,
1403 deletions: 1,
1404 });
1405 expect(stats.some((stat) => stat.number === 3 || stat.repository === "acme/api")).toBe(
1406 false,
1407 );
1408 expect(
1409 mockedExecute.mock.calls.map(([request]) => {
1410 const { fullPath, iids } = variablesOf(request.stdin);
1411 return [fullPath, iids.length];
1412 }),
1413 ).toEqual([
1414 ["acme/web", 100],
1415 ["acme/web", 50],
1416 ["acme/api", 1],
1417 ]);
1418 }),
1419 );
1420 it.effect.each([
1421 GitLabCli.GitLabCliUnavailableError,
1422 GitLabCli.GitLabCliAuthenticationError,
1423 GitLabCli.GitLabCliRateLimitError,
1424 ])("propagates unusable CLI and account failures from stats (%s)", (ErrorType) =>
1425 Effect.gen(function* () {
1426 const error = new ErrorType({
1427 operation: "execute",
1428 command: "glab",
1429 cwd: "/w",
1430 cause: null,
1431 });
1432 mockedExecute.mockReturnValueOnce(Effect.fail(error));
1433 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1434 const result = yield* Effect.result(
1435 cli.listMergeRequestStats({
1436 cwd: "/w",
1437 changeRequests: [{ repository: "acme/web", number: 7 }],
1438 }),
1439 );
1440 expect(result).toMatchObject({ _tag: "Failure", failure: error });
1441 }),
1442 );
1443});