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

GitLabPullRequestCli.test.ts

1,136 lines36.4 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=100&page=1");
434 }),
435 );
436​
437 it.effect("refuses a cursor it never handed out rather than reading it into a query", () =>
438 Effect.gen(function* () {
439 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
440​
441 const error = yield* Effect.flip(
442 cli.getMergeRequestDiff({
443 cwd: "/w",
444 repository: "acme/web",
445 number: 7,
446 cursor: "1&per_page=1",
447 }),
448 );
449​
450 assert.strictEqual(error._tag, "GitLabDiffCursorError");
451 assert.strictEqual(mockedExecute.mock.calls.length, 0);
452 }),
453 );
454​
455 it.effect("reads a named commit from its own diff, and pages inside it", () =>
456 Effect.gen(function* () {
457 mockedExecute
458 .mockReturnValueOnce(Effect.succeed(output(diffPage(0))))
459 .mockReturnValueOnce(Effect.succeed(output(diffPage(100, 3))));
460 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
461 const target = {
462 cwd: "/w",
463 repository: "acme/web",
464 number: 7,
465 commit: "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0",
466 };
467​
468 const first = yield* cli.getMergeRequestDiff(target);
469 assert.isNotNull(first.nextCursor);
470 const second = yield* cli.getMergeRequestDiff({ ...target, cursor: first.nextCursor });
471​
472 const commitPath =
473 "projects/acme%2Fweb/repository/commits/a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0/diff";
474 expect(argsOfCall(0)[1]).toBe(`${commitPath}?per_page=100&page=1`);
475 expect(argsOfCall(1)[1]).toBe(`${commitPath}?per_page=100&page=2`);
476 assert.isNull(second.nextCursor);
477 }),
478 );
479​
480 it.effect("refuses a commit that is not a sha rather than reading it into a path", () =>
481 Effect.gen(function* () {
482 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
483​
484 const error = yield* Effect.flip(
485 cli.getMergeRequestDiff({
486 cwd: "/w",
487 repository: "acme/web",
488 number: 7,
489 commit: "../../merge_requests/8/diffs",
490 }),
491 );
492​
493 assert.strictEqual(error._tag, "GitLabDiffCommitError");
494 assert.strictEqual(mockedExecute.mock.calls.length, 0);
495 }),
496 );
497​
498 it.effect("reports a commit with no parent as a structured error", () =>
499 Effect.gen(function* () {
500 mockedExecute.mockReturnValueOnce(
501 Effect.succeed(output(JSON.stringify({ id: "a1b2c3d", parent_ids: [] }))),
502 );
503 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
504​
505 const error = yield* Effect.flip(
506 cli.getMergeRequestDiffFileContents({
507 cwd: "/w",
508 repository: "acme/web",
509 number: 7,
510 commit: "a1b2c3d",
511 changeType: "change",
512 oldPath: "src/a.ts",
513 newPath: "src/a.ts",
514 }),
515 );
516​
517 assert.strictEqual(error._tag, "GitLabDiffCommitParentUnavailableError");
518 if (error._tag === "GitLabDiffCommitParentUnavailableError") {
519 assert.strictEqual(error.commit, "a1b2c3d");
520 }
521 }),
522 );
523​
524 it.effect("expands a new file from a root commit without requiring a parent", () =>
525 Effect.gen(function* () {
526 mockedExecute.mockReturnValueOnce(
527 Effect.succeed(output(JSON.stringify({ id: "a1b2c3d", parent_ids: [] }))),
528 );
529 mockedExecute.mockReturnValueOnce(Effect.succeed(output("first contents\n")));
530 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
531​
532 const contents = yield* cli.getMergeRequestDiffFileContents({
533 cwd: "/w",
534 repository: "acme/web",
535 number: 7,
536 commit: "a1b2c3d",
537 changeType: "new",
538 oldPath: "src/first.ts",
539 newPath: "src/first.ts",
540 });
541​
542 expect(contents).toEqual({ oldContents: "", newContents: "first contents\n" });
543 expect(argsOfCall(1)[1]).toContain("raw?ref=a1b2c3d");
544 }),
545 );
546​
547 it.effect("reports undecodable diff file contents as binary", () =>
548 Effect.gen(function* () {
549 mockedExecute.mockReturnValueOnce(
550 Effect.succeed(
551 output(
552 JSON.stringify({
553 diff_refs: {
554 base_sha: "a1b2c3d",
555 head_sha: "b1c2d3e",
556 start_sha: "a1b2c3d",
557 },
558 }),
559 ),
560 ),
561 );
562 mockedExecute.mockReturnValueOnce(
563 Effect.succeed(output("binary\uFFFDcontents", false, true)),
564 );
565 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
566​
567 const error = yield* Effect.flip(
568 cli.getMergeRequestDiffFileContents({
569 cwd: "/w",
570 repository: "acme/web",
571 number: 7,
572 changeType: "deleted",
573 oldPath: "assets/logo.png",
574 newPath: "assets/logo.png",
575 }),
576 );
577​
578 assert.strictEqual(error._tag, "GitLabDiffFileContentsUnavailableError");
579 if (error._tag === "GitLabDiffFileContentsUnavailableError") {
580 assert.strictEqual(error.path, "assets/logo.png");
581 assert.strictEqual(error.reason, "binary");
582 }
583 }),
584 );
585​
586 it.effect("returns valid text containing a literal replacement character", () =>
587 Effect.gen(function* () {
588 mockedExecute.mockReturnValueOnce(
589 Effect.succeed(
590 output(
591 JSON.stringify({
592 diff_refs: {
593 base_sha: "a1b2c3d",
594 head_sha: "b1c2d3e",
595 start_sha: "a1b2c3d",
596 },
597 }),
598 ),
599 ),
600 );
601 mockedExecute.mockReturnValueOnce(Effect.succeed(output("before\uFFFDafter")));
602 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
603​
604 const contents = yield* cli.getMergeRequestDiffFileContents({
605 cwd: "/w",
606 repository: "acme/web",
607 number: 7,
608 changeType: "deleted",
609 oldPath: "docs/encoding.md",
610 newPath: "docs/encoding.md",
611 });
612​
613 assert.strictEqual(contents.oldContents, "before\uFFFDafter");
614 }),
615 );
616​
617 it.effect("ends the diff on a page with no files rather than asking for it again", () =>
618 Effect.gen(function* () {
619 mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
620 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
621​
622 const diff = yield* cli.getMergeRequestDiff({
623 cwd: "/w",
624 repository: "acme/web",
625 number: 7,
626 cursor: "4",
627 });
628​
629 assert.strictEqual(diff.patch, "");
630 assert.isNull(diff.nextCursor);
631 }),
632 );
633​
634 it.effect("fails a diff page cut off mid-JSON rather than calling the diff whole", () =>
635 Effect.gen(function* () {
636 mockedExecute.mockReturnValueOnce(
637 Effect.succeed({ ...output('[{"old_path":"src/x.ts","new_p'), stdoutTruncated: true }),
638 );
639 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
640​
641 const error = yield* Effect.flip(
642 cli.getMergeRequestDiff({ cwd: "/w", repository: "acme/web", number: 7 }),
643 );
644​
645 assert.strictEqual(error._tag, "GitLabMergeRequestReadError");
646 }),
647 );
648​
649 it.effect("offers no squash when the project does not say it allows one", () =>
650 Effect.gen(function* () {
651 mockedExecute.mockReturnValueOnce(
652 Effect.succeed(output(JSON.stringify({ merge_method: "merge" }))),
653 );
654 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
655​
656 const capabilities = yield* cli.getProjectMergeCapabilities({
657 cwd: "/w",
658 repository: "acme/web",
659 });
660​
661 assert.deepStrictEqual(capabilities, { merge: true, squash: false, rebase: false });
662 }),
663 );
664​
665 it.effect("reads the project's merge settings as its merge capabilities", () =>
666 Effect.gen(function* () {
667 mockedExecute.mockReturnValueOnce(
668 Effect.succeed(output(JSON.stringify({ merge_method: "ff", squash_option: "never" }))),
669 );
670 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
671​
672 const capabilities = yield* cli.getProjectMergeCapabilities({
673 cwd: "/w",
674 repository: "acme/web",
675 });
676​
677 assert.deepStrictEqual(capabilities, { merge: false, squash: false, rebase: true });
678 }),
679 );
680​
681 it.effect("fails when the authenticated account has no username", () =>
682 Effect.gen(function* () {
683 mockedExecute.mockReturnValueOnce(Effect.succeed(output(JSON.stringify({ username: "" }))));
684 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
685​
686 const error = yield* Effect.flip(cli.getViewerUsername({ cwd: "/w" }));
687​
688 assert.strictEqual(error._tag, "GitLabViewerUnavailableError");
689 }),
690 );
691​
692 it.effect("walks the notes until GitLab answers with a short page", () =>
693 Effect.gen(function* () {
694 mockedExecute.mockReturnValueOnce(Effect.succeed(output(notes(100, 1))));
695 mockedExecute.mockReturnValueOnce(Effect.succeed(output(notes(2, 101))));
696 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
697​
698 const { comments, truncated } = yield* cli.listNotes({
699 cwd: "/w",
700 repository: "acme/web",
701 number: 7,
702 });
703​
704 expect(argsOfCall(0).join(" ")).toContain("page=1");
705 expect(argsOfCall(1).join(" ")).toContain("page=2");
706 assert.strictEqual(comments.length, 102);
707 assert.isFalse(truncated);
708 }),
709 );
710​
711 it.effect("stops the note walk at its bound and says the conversation was cut short", () =>
712 Effect.gen(function* () {
713 mockedExecute.mockReturnValue(Effect.succeed(output(notes(100, 1))));
714 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
715​
716 const { truncated } = yield* cli.listNotes({
717 cwd: "/w",
718 repository: "acme/web",
719 number: 7,
720 });
721​
722 assert.strictEqual(mockedExecute.mock.calls.length, 10);
723 assert.isTrue(truncated);
724 }),
725 );
726​
727 it.effect("reads a positioned discussion as a thread anchored to its line", () =>
728 Effect.gen(function* () {
729 mockedExecute.mockReturnValueOnce(
730 Effect.succeed(
731 output(
732 JSON.stringify([
733 {
734 id: "abc123",
735 notes: [
736 {
737 id: 1,
738 body: "rename this",
739 author: { username: "bilal", avatar_url: "https://avatars/b.png" },
740 created_at: "2026-07-01T00:00:00Z",
741 resolvable: true,
742 resolved: true,
743 position: {
744 position_type: "text",
745 new_path: "src/a.ts",
746 old_path: "src/a.ts",
747 new_line: 12,
748 old_line: null,
749 },
750 },
751 {
752 id: 2,
753 body: "done",
754 author: { username: "julius" },
755 created_at: "2026-07-01T01:00:00Z",
756 },
757 ],
758 },
759 { id: "def456", notes: [{ id: 3, body: "ship it", created_at: "2026-07-01Z" }] },
760 ]),
761 ),
762 ),
763 );
764 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
765​
766 const { threads } = yield* cli.listDiscussions({
767 cwd: "/w",
768 repository: "acme/web",
769 number: 7,
770 });
771​
772 assert.strictEqual(threads.length, 1);
773 expect(threads[0]).toMatchObject({
774 id: "abc123",
775 path: "src/a.ts",
776 line: 12,
777 side: "right",
778 isResolved: true,
779 });
780 assert.strictEqual(threads[0]?.comments.length, 2);
781 }),
782 );
783​
784 it.effect("sends a review as its comments, then its summary, then the verdict", () =>
785 Effect.gen(function* () {
786 mockedExecute.mockReturnValueOnce(
787 Effect.succeed(
788 output(
789 JSON.stringify({
790 iid: 7,
791 title: "t",
792 web_url: "https://gitlab.com/acme/web/-/merge_requests/7",
793 source_branch: "feat",
794 target_branch: "main",
795 created_at: "2026-07-01T00:00:00Z",
796 updated_at: "2026-07-01T00:00:00Z",
797 diff_refs: { base_sha: "base", head_sha: "head", start_sha: "start" },
798 }),
799 ),
800 ),
801 );
802 mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
803 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
804​
805 yield* cli.submitReview({
806 cwd: "/w",
807 repository: "acme/web",
808 number: 7,
809 verdict: "approve",
810 body: "Looks right.",
811 comments: [
812 {
813 path: "src/b.ts",
814 oldPath: "src/a.ts",
815 position: { kind: "deleted", oldLine: 4 },
816 body: "why remove?",
817 },
818 ],
819 });
820​
821 expect(argsOfCall(0)[1]).toContain("merge_requests/7");
822 expect(argsOfCall(1)[1]).toContain("/discussions");
823 expect(JSON.parse(callAt(1).stdin ?? "")).toEqual({
824 body: "why remove?",
825 position: {
826 base_sha: "base",
827 head_sha: "head",
828 start_sha: "start",
829 position_type: "text",
830 // A renamed file is the only case the two differ, and GitLab cannot place a
831 // position that names the same path on both sides of the rename.
832 old_path: "src/a.ts",
833 new_path: "src/b.ts",
834 old_line: 4,
835 },
836 });
837 expect(argsOfCall(2)[1]).toContain("/notes");
838 expect(argsOfCall(3)[1]).toContain("/approve");
839 }),
840 );
841​
842 it.effect("removes an award by listing them and deleting the reader's own id", () =>
843 Effect.gen(function* () {
844 mockedExecute.mockReturnValueOnce(
845 Effect.succeed(output(JSON.stringify({ username: "bilal" }))),
846 );
847 mockedExecute.mockReturnValueOnce(
848 Effect.succeed(
849 output(
850 JSON.stringify([
851 { id: 5, name: "thumbsup", user: { username: "bilal" } },
852 { id: 6, name: "thumbsup", user: { username: "julius" } },
853 ]),
854 ),
855 ),
856 );
857 mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
858 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
859​
860 yield* cli.setReaction({
861 cwd: "/w",
862 repository: "acme/web",
863 number: 7,
864 content: "thumbs-up",
865 reacted: false,
866 });
867​
868 assert.strictEqual(mockedExecute.mock.calls.length, 3);
869 expect(argsOfCall(2)).toEqual([
870 "api",
871 "projects/acme%2Fweb/merge_requests/7/award_emoji/5",
872 "--method",
873 "DELETE",
874 ]);
875 }),
876 );
877​
878 it.effect("names a merge request with no diff revisions rather than calling it unreadable", () =>
879 Effect.gen(function* () {
880 mockedExecute.mockReturnValueOnce(
881 Effect.succeed(
882 output(
883 JSON.stringify({
884 iid: 7,
885 title: "t",
886 web_url: "https://gitlab.com/acme/web/-/merge_requests/7",
887 source_branch: "feat",
888 target_branch: "main",
889 created_at: "2026-07-01T00:00:00Z",
890 updated_at: "2026-07-01T00:00:00Z",
891 diff_refs: null,
892 }),
893 ),
894 ),
895 );
896 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
897​
898 const error = yield* Effect.flip(
899 cli.submitReview({
900 cwd: "/w",
901 repository: "acme/web",
902 number: 7,
903 verdict: "comment",
904 body: "",
905 comments: [{ path: "src/a.ts", position: { kind: "added", newLine: 4 }, body: "nit" }],
906 }),
907 );
908​
909 assert.strictEqual(error._tag, "GitLabDiffRefsUnavailableError");
910 }),
911 );
912​
913 it.effect("reads who has access to the project and who is already on the merge request", () =>
914 Effect.gen(function* () {
915 mockedExecute
916 .mockReturnValueOnce(Effect.succeed(output(mergeRequestJson({ reviewers: [reviewer] }))))
917 .mockReturnValueOnce(
918 Effect.succeed(output(JSON.stringify([author, reviewer, { id: 9, username: "hubot" }]))),
919 );
920 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
921​
922 const list = yield* cli.listReviewerCandidates({
923 cwd: "/w",
924 repository: "acme/web",
925 number: 7,
926 });
927​
928 expect(argsOfCall(1)[1]).toBe("projects/acme%2Fweb/users?per_page=100");
929 expect(list.candidates.map((candidate) => [candidate.id, candidate.isRequested])).toEqual([
930 ["5", true],
931 ["9", false],
932 ]);
933 assert.isFalse(list.truncated);
934 }),
935 );
936​
937 it.effect("writes the reviewer set back with the one being asked added to it", () =>
938 Effect.gen(function* () {
939 mockedExecute
940 .mockReturnValueOnce(Effect.succeed(output(mergeRequestJson({ reviewers: [reviewer] }))))
941 .mockReturnValueOnce(Effect.succeed(output("{}")));
942 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
943​
944 yield* cli.setReviewerRequest({
945 cwd: "/w",
946 repository: "acme/web",
947 number: 7,
948 reviewers: [{ id: "9" }],
949 requested: true,
950 });
951​
952 // GitLab replaces the whole set, so the reviewer already on the merge request has to be
953 // sent back with the new one or the request would take them off it.
954 expect(argsOfCall(1)).toContain("PUT");
955 expect(JSON.parse(callAt(1).stdin ?? "")).toEqual({ reviewer_ids: [5, 9] });
956 }),
957 );
958​
959 it.effect("takes a reviewer out of the set rather than clearing it", () =>
960 Effect.gen(function* () {
961 mockedExecute
962 .mockReturnValueOnce(
963 Effect.succeed(
964 output(mergeRequestJson({ reviewers: [reviewer, { id: 9, username: "hubot" }] })),
965 ),
966 )
967 .mockReturnValueOnce(Effect.succeed(output("{}")));
968 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
969​
970 yield* cli.setReviewerRequest({
971 cwd: "/w",
972 repository: "acme/web",
973 number: 7,
974 reviewers: [{ id: "9" }],
975 requested: false,
976 });
977​
978 expect(JSON.parse(callAt(1).stdin ?? "")).toEqual({ reviewer_ids: [5] });
979 }),
980 );
981​
982 it.effect("ignores an id GitLab could not have handed out, which names nobody", () =>
983 Effect.gen(function* () {
984 mockedExecute
985 .mockReturnValueOnce(Effect.succeed(output(mergeRequestJson({ reviewers: [reviewer] }))))
986 .mockReturnValueOnce(Effect.succeed(output("{}")));
987 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
988​
989 yield* cli.setReviewerRequest({
990 cwd: "/w",
991 repository: "acme/web",
992 number: 7,
993 reviewers: [{ id: "octocat" }],
994 requested: true,
995 });
996​
997 expect(JSON.parse(callAt(1).stdin ?? "")).toEqual({ reviewer_ids: [5] });
998 }),
999 );
1000 it.effect("reads blob ids for the marked paths at the merge request's head", () =>
1001 Effect.gen(function* () {
1002 mockedExecute.mockReturnValueOnce(
1003 Effect.succeed(
1004 output(
1005 JSON.stringify({
1006 iid: 7,
1007 title: "t",
1008 web_url: "https://gitlab.com/acme/web/-/merge_requests/7",
1009 source_branch: "feat",
1010 target_branch: "main",
1011 created_at: "2026-07-01T00:00:00Z",
1012 updated_at: "2026-07-01T00:00:00Z",
1013 diff_refs: { base_sha: "base", head_sha: "head", start_sha: "start" },
1014 }),
1015 ),
1016 ),
1017 );
1018 mockedExecute.mockReturnValueOnce(
1019 Effect.succeed(
1020 output(
1021 JSON.stringify({
1022 data: {
1023 project: { repository: { blobs: { nodes: [{ path: "src/a.ts", oid: "aaa" }] } } },
1024 },
1025 }),
1026 ),
1027 ),
1028 );
1029 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1030​
1031 const revisions = yield* cli.getFileRevisions({
1032 cwd: "/w",
1033 repository: "acme/web",
1034 number: 7,
1035 paths: ["src/a.ts", "src/gone.ts"],
1036 });
1037​
1038 expect([...revisions]).toEqual([
1039 ["src/a.ts", "aaa"],
1040 ["src/gone.ts", ""],
1041 ]);
1042 const body: unknown = JSON.parse(callAt(1).stdin ?? "{}");
1043 expect(body).toMatchObject({
1044 variables: { fullPath: "acme/web", ref: "head", paths: ["src/a.ts", "src/gone.ts"] },
1045 });
1046 }),
1047 );
1048​
1049 it.effect("leaves the paths out when GitLab did not answer the blobs query", () =>
1050 Effect.gen(function* () {
1051 mockedExecute.mockReturnValueOnce(
1052 Effect.succeed(
1053 output(
1054 JSON.stringify({
1055 iid: 7,
1056 title: "t",
1057 web_url: "https://gitlab.com/acme/web/-/merge_requests/7",
1058 source_branch: "feat",
1059 target_branch: "main",
1060 created_at: "2026-07-01T00:00:00Z",
1061 updated_at: "2026-07-01T00:00:00Z",
1062 diff_refs: { base_sha: "base", head_sha: "head", start_sha: "start" },
1063 }),
1064 ),
1065 ),
1066 );
1067 mockedExecute.mockReturnValueOnce(
1068 Effect.succeed(output(JSON.stringify({ data: { project: null } }))),
1069 );
1070 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1071​
1072 const revisions = yield* cli.getFileRevisions({
1073 cwd: "/w",
1074 repository: "acme/web",
1075 number: 7,
1076 paths: ["src/a.ts", "src/b.ts"],
1077 });
1078​
1079 expect([...revisions]).toEqual([]);
1080 }),
1081 );
1082​
1083 it.effect("splits the paths across requests, because GitLab charges the query by how many", () =>
1084 Effect.gen(function* () {
1085 const paths = Array.from({ length: 150 }, (_, index) => `src/${index}.ts`);
1086 mockedExecute.mockReturnValueOnce(
1087 Effect.succeed(
1088 output(
1089 JSON.stringify({
1090 iid: 7,
1091 title: "t",
1092 web_url: "https://gitlab.com/acme/web/-/merge_requests/7",
1093 source_branch: "feat",
1094 target_branch: "main",
1095 created_at: "2026-07-01T00:00:00Z",
1096 updated_at: "2026-07-01T00:00:00Z",
1097 diff_refs: { base_sha: "base", head_sha: "head", start_sha: "start" },
1098 }),
1099 ),
1100 ),
1101 );
1102 mockedExecute.mockImplementation((request) => {
1103 const body = JSON.parse(request.stdin ?? "{}") as {
1104 readonly variables: { readonly paths: ReadonlyArray<string> };
1105 };
1106 return Effect.succeed(
1107 output(
1108 JSON.stringify({
1109 data: {
1110 project: {
1111 repository: {
1112 blobs: {
1113 nodes: body.variables.paths.map((path) => ({ path, oid: `oid-${path}` })),
1114 },
1115 },
1116 },
1117 },
1118 }),
1119 ),
1120 );
1121 });
1122 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1123​
1124 const revisions = yield* cli.getFileRevisions({
1125 cwd: "/w",
1126 repository: "acme/web",
1127 number: 7,
1128 paths,
1129 });
1130​
1131 assert.strictEqual(revisions.size, 150);
1132 assert.strictEqual(revisions.get("src/149.ts"), "oid-src/149.ts");
1133 assert.strictEqual(mockedExecute.mock.calls.length, 3);
1134 }),
1135 );
1136});