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

GitLabPullRequestCli.test.ts

1,165 lines37.6 KB

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