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

GitLabPullRequestCli.test.ts

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