Open History to see the last commit
1import * as Result from "effect/Result";
2import { describe, expect, it } from "vite-plus/test";
3
4import {
5 decodeAwardEmojiJson,
6 decodeRepositoryBlobsJson,
7 decodeCommitsJson,
8 decodeMergeRequestDetailJson,
9 decodeMergeRequestDiffsJson,
10 decodeMergeRequestListJson,
11 decodeMergeRequestFileStatsJson,
12 decodeMergeRequestStatsJson,
13 decodeNotesJson,
14 decodeOwnAwardIdJson,
15} from "./gitLabMergeRequestJson.ts";
16
17function listJson(entries: ReadonlyArray<Record<string, unknown>>): string {
18 return JSON.stringify(
19 entries.map((entry) => ({
20 iid: 1,
21 title: "Add the merge requests page",
22 web_url: "https://gitlab.com/acme/web/-/merge_requests/1",
23 source_branch: "feat/page",
24 target_branch: "main",
25 created_at: "2026-07-01T00:00:00Z",
26 updated_at: "2026-07-02T00:00:00Z",
27 ...entry,
28 })),
29 );
30}
31
32function detailJson(entry: Record<string, unknown>): string {
33 return JSON.stringify({
34 iid: 1,
35 title: "Add the merge requests page",
36 web_url: "https://gitlab.com/acme/web/-/merge_requests/1",
37 source_branch: "feat/page",
38 target_branch: "main",
39 created_at: "2026-07-01T00:00:00Z",
40 updated_at: "2026-07-02T00:00:00Z",
41 ...entry,
42 });
43}
44
45function expectSuccess<A>(result: Result.Result<A, unknown>): A {
46 expect(Result.isSuccess(result)).toBe(true);
47 if (!Result.isSuccess(result)) throw new Error("expected a successful decode");
48 return result.success;
49}
50
51describe("decodeMergeRequestListJson", () => {
52 it("reads a merge request as a change request", () => {
53 const batch = expectSuccess(
54 decodeMergeRequestListJson(
55 listJson([
56 {
57 iid: 42,
58 author: { username: "bilal", name: "Bilal" },
59 state: "opened",
60 merge_status: "can_be_merged",
61 draft: false,
62 reviewers: [{ username: "julius" }],
63 labels: ["backend", " "],
64 },
65 ]),
66 ),
67 );
68
69 expect(batch.items).toHaveLength(1);
70 expect(batch.items[0]).toMatchObject({
71 number: 42,
72 author: { login: "bilal", name: "Bilal" },
73 headBranch: "feat/page",
74 baseBranch: "main",
75 state: "open",
76 isDraft: false,
77 mergeability: "mergeable",
78 reviewRequestLogins: ["julius"],
79 labels: [{ name: "backend", color: null }],
80 });
81 });
82
83 it("treats a merged timestamp as merged whatever the state says", () => {
84 const batch = expectSuccess(
85 decodeMergeRequestListJson(
86 listJson([{ state: "opened", merged_at: "2026-07-03T00:00:00Z" }]),
87 ),
88 );
89
90 expect(batch.items[0]?.state).toBe("merged");
91 });
92
93 it("reads the legacy draft flag", () => {
94 const batch = expectSuccess(decodeMergeRequestListJson(listJson([{ work_in_progress: true }])));
95
96 expect(batch.items[0]?.isDraft).toBe(true);
97 });
98
99 it("calls a conflicted merge request conflicting even while the merge check is pending", () => {
100 const batch = expectSuccess(
101 decodeMergeRequestListJson(listJson([{ merge_status: "checking", has_conflicts: true }])),
102 );
103
104 expect(batch.items[0]?.mergeability).toBe("conflicting");
105 });
106
107 it("skips a malformed row but still counts it, so paging does not stop early", () => {
108 const batch = expectSuccess(
109 decodeMergeRequestListJson(
110 JSON.stringify([{ iid: "not a number" }, ...JSON.parse(listJson([{}]))]),
111 ),
112 );
113
114 expect(batch.items).toHaveLength(1);
115 expect(batch.rawIndexes).toEqual([1]);
116 expect(batch.rawCount).toBe(2);
117 });
118});
119
120describe("decodeMergeRequestDetailJson", () => {
121 it("reads the description, file count and pipeline", () => {
122 const detail = expectSuccess(
123 decodeMergeRequestDetailJson(
124 detailJson({
125 description: "Ships the page.",
126 changes_count: "3",
127 reviewers: [{ username: "julius", name: "Julius" }],
128 head_pipeline: {
129 status: "success",
130 web_url: "https://gitlab.com/acme/web/-/pipelines/9",
131 source: "merge_request_event",
132 },
133 }),
134 ),
135 );
136
137 expect(detail.body).toBe("Ships the page.");
138 expect(detail.changedFiles).toBe(3);
139 expect(detail.reviewers).toEqual([{ login: "julius", name: "Julius", avatarUrl: null }]);
140 expect(detail.checks).toEqual([
141 {
142 name: "Pipeline",
143 status: "success",
144 description: "merge_request_event",
145 url: "https://gitlab.com/acme/web/-/pipelines/9",
146 },
147 ]);
148 });
149
150 it("reads an uncounted change set as its floor", () => {
151 const detail = expectSuccess(
152 decodeMergeRequestDetailJson(detailJson({ changes_count: "1000+" })),
153 );
154
155 expect(detail.changedFiles).toBe(1000);
156 });
157
158 it("reads the head commit, and says nothing where GitLab omitted it", () => {
159 const headSha = (entry: Record<string, unknown>) =>
160 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).headSha;
161 const sha = "afce4da4d5fe7d2fd0647b5b864526ea0a2827cb";
162
163 expect(headSha({ sha })).toBe(sha);
164 expect(headSha({ sha, diff_refs: null })).toBe(sha);
165 expect(headSha({ sha, merge_commit_sha: "0".repeat(40) })).toBe(sha);
166 expect(headSha({})).toBeUndefined();
167 expect(headSha({ sha: null })).toBeUndefined();
168 expect(headSha({ sha: " " })).toBeUndefined();
169 });
170
171 it("reads either auto-merge field, and says nothing where GitLab named neither", () => {
172 const armed = (entry: Record<string, unknown>) =>
173 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).autoMergeEnabled;
174
175 expect(armed({ merge_when_pipeline_succeeds: true })).toBe(true);
176 expect(armed({ auto_merge_enabled: true })).toBe(true);
177 expect(armed({ merge_when_pipeline_succeeds: false })).toBe(false);
178 expect(armed({})).toBeUndefined();
179 });
180
181 it("keeps the squash choice stored with auto-merge", () => {
182 expect(
183 expectSuccess(
184 decodeMergeRequestDetailJson(
185 detailJson({ auto_merge_enabled: true, squash_on_merge: true }),
186 ),
187 ),
188 ).toMatchObject({ autoMergeEnabled: true, autoMergeMethod: "squash" });
189
190 expect(
191 expectSuccess(
192 decodeMergeRequestDetailJson(
193 detailJson({
194 auto_merge_enabled: true,
195 squash: true,
196 squash_on_merge: false,
197 }),
198 ),
199 ).autoMergeMethod,
200 ).toBeUndefined();
201 });
202
203 it("keeps a divergence GitLab did not count apart from a divergence of none", () => {
204 const behind = (entry: Record<string, unknown>) =>
205 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).divergedCommits;
206
207 expect(behind({ diverged_commits_count: 3 })).toBe(3);
208 expect(behind({ diverged_commits_count: 0 })).toBe(0);
209 expect(behind({})).toBeUndefined();
210 expect(behind({ diverged_commits_count: null })).toBeUndefined();
211 });
212
213 it("maps a pipeline waiting on a person to neutral, not failure", () => {
214 const detail = expectSuccess(
215 decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status: "manual" } })),
216 );
217
218 expect(detail.checks[0]?.status).toBe("neutral");
219 });
220});
221
222describe("decodeNotesJson", () => {
223 it("keeps comments and drops GitLab's own activity notes", () => {
224 const notes = expectSuccess(
225 decodeNotesJson(
226 JSON.stringify([
227 {
228 id: 1,
229 body: "assigned to @bilal",
230 system: true,
231 created_at: "2026-07-01T00:00:00Z",
232 },
233 {
234 id: 2,
235 body: "Looks good.",
236 author: { username: "julius" },
237 created_at: "2026-07-02T00:00:00Z",
238 },
239 { id: 3, body: " ", created_at: "2026-07-03T00:00:00Z" },
240 ]),
241 ),
242 );
243
244 expect(notes.comments).toHaveLength(1);
245 expect(notes.comments[0]).toMatchObject({
246 id: "2",
247 kind: "issue-comment",
248 body: "Looks good.",
249 });
250 expect(notes.rawCount).toBe(3);
251 });
252
253 it("reads a line note as a review comment on its file", () => {
254 const notes = expectSuccess(
255 decodeNotesJson(
256 JSON.stringify([
257 {
258 id: 7,
259 type: "DiffNote",
260 body: "Rename this.",
261 created_at: "2026-07-02T00:00:00Z",
262 position: { new_path: "src/app.ts", old_path: "src/old.ts" },
263 },
264 ]),
265 ),
266 );
267
268 expect(notes.comments[0]).toMatchObject({ kind: "review-comment", path: "src/app.ts" });
269 });
270
271 it("falls back to the old path for a note on a deleted line", () => {
272 const notes = expectSuccess(
273 decodeNotesJson(
274 JSON.stringify([
275 {
276 id: 8,
277 type: "DiffNote",
278 body: "Gone.",
279 created_at: "2026-07-02T00:00:00Z",
280 position: { new_path: null, old_path: "src/old.ts" },
281 },
282 ]),
283 ),
284 );
285
286 expect(notes.comments[0]?.path).toBe("src/old.ts");
287 });
288});
289
290describe("decodeCommitsJson", () => {
291 it("falls back to the creation timestamp when there is no commit date", () => {
292 const commits = expectSuccess(
293 decodeCommitsJson(
294 JSON.stringify([
295 {
296 id: "aaa",
297 created_at: "2026-07-01T00:00:00+08:00",
298 author_name: "Ada Lovelace",
299 author_email: "ada@example.com",
300 },
301 ]),
302 ),
303 );
304
305 expect(commits[0]).toMatchObject({
306 oid: "aaa",
307 committedDate: "2026-07-01T00:00:00+08:00",
308 authors: [{ login: "Ada Lovelace", name: "Ada Lovelace", avatarUrl: null }],
309 });
310 });
311});
312
313describe("decodeMergeRequestDiffsJson", () => {
314 it("quotes literal backslashes without interpreting them as escapes", () => {
315 const result = expectSuccess(
316 decodeMergeRequestDiffsJson(
317 JSON.stringify([
318 {
319 old_path: String.raw`src\notes.ts`,
320 new_path: String.raw`src\notes.ts`,
321 diff: "@@ -1 +1 @@\n-old\n+new",
322 },
323 ]),
324 ),
325 );
326
327 expect(result.patch).toBe(
328 [
329 String.raw`diff --git "a/src\\notes.ts" "b/src\\notes.ts"`,
330 String.raw`--- "a/src\\notes.ts"`,
331 String.raw`+++ "b/src\\notes.ts"`,
332 "@@ -1 +1 @@",
333 "-old",
334 "+new",
335 "",
336 ].join("\n"),
337 );
338 });
339
340 it("preserves spaces and literal backslashes in both rename paths", () => {
341 const result = expectSuccess(
342 decodeMergeRequestDiffsJson(
343 JSON.stringify([
344 {
345 old_path: String.raw` old\name.ts `,
346 new_path: String.raw` new\name.ts `,
347 renamed_file: true,
348 diff: "",
349 },
350 ]),
351 ),
352 );
353
354 expect(result.patch).toBe(
355 [
356 String.raw`diff --git "a/ old\\name.ts " "b/ new\\name.ts "`,
357 String.raw`rename from " old\\name.ts "`,
358 String.raw`rename to " new\\name.ts "`,
359 String.raw`--- "a/ old\\name.ts "`,
360 String.raw`+++ "b/ new\\name.ts "`,
361 ].join("\n"),
362 );
363 });
364
365 it("assembles a unified patch GitLab does not return", () => {
366 const result = expectSuccess(
367 decodeMergeRequestDiffsJson(
368 JSON.stringify([
369 {
370 old_path: "src/app.ts",
371 new_path: "src/app.ts",
372 diff: "@@ -1 +1 @@\n-old\n+new\n",
373 },
374 ]),
375 ),
376 );
377
378 expect(result.patch).toBe(
379 [
380 "diff --git a/src/app.ts b/src/app.ts",
381 "--- a/src/app.ts",
382 "+++ b/src/app.ts",
383 "@@ -1 +1 @@",
384 "-old",
385 "+new",
386 "",
387 ].join("\n"),
388 );
389 expect(result.truncated).toBe(false);
390 });
391
392 it("points a new file at /dev/null on the left and a deleted file on the right", () => {
393 const result = expectSuccess(
394 decodeMergeRequestDiffsJson(
395 JSON.stringify([
396 {
397 old_path: "src/new.ts",
398 new_path: "src/new.ts",
399 new_file: true,
400 b_mode: "100755",
401 diff: "@@ -0,0 +1 @@\n+hello\n",
402 },
403 {
404 old_path: "src/gone.ts",
405 new_path: "src/gone.ts",
406 deleted_file: true,
407 diff: "@@ -1 +0,0 @@\n-bye\n",
408 },
409 ]),
410 ),
411 );
412
413 expect(result.patch).toContain("new file mode 100755");
414 expect(result.patch).toContain("--- /dev/null");
415 expect(result.patch).toContain("deleted file mode 100644");
416 expect(result.patch).toContain("+++ /dev/null");
417 });
418
419 it("reports truncation for a file GitLab refused to inline", () => {
420 const result = expectSuccess(
421 decodeMergeRequestDiffsJson(
422 JSON.stringify([{ old_path: "big.bin", new_path: "big.bin", diff: "", too_large: true }]),
423 ),
424 );
425
426 expect(result.truncated).toBe(true);
427 expect(result.patch).toContain("diff --git a/big.bin b/big.bin");
428 });
429
430 it("reports how many files GitLab returned, so the caller can page", () => {
431 const result = expectSuccess(
432 decodeMergeRequestDiffsJson(
433 JSON.stringify(
434 Array.from({ length: 3 }, (_, index) => ({
435 old_path: `src/${index}.ts`,
436 new_path: `src/${index}.ts`,
437 diff: "@@ -1 +1 @@\n-a\n+b\n",
438 })),
439 ),
440 ),
441 );
442
443 expect(result.rawCount).toBe(3);
444 expect(result.truncated).toBe(false);
445 expect(result.patch).toContain("src/2.ts");
446 });
447});
448
449describe("merge request viewer fields", () => {
450 it("leaves merging permitted where GitLab answered without the field", () => {
451 expect(expectSuccess(decodeMergeRequestDetailJson(detailJson({}))).viewerCanMerge).toBe(true);
452 expect(
453 expectSuccess(decodeMergeRequestDetailJson(detailJson({ user: null }))).viewerCanMerge,
454 ).toBe(true);
455 });
456});
457
458describe("decodeAwardEmojiJson", () => {
459 it("reads MR-level awards, keys per-note awards by the REST id inside their gid, and ignores an award outside the eight", () => {
460 const result = expectSuccess(
461 decodeAwardEmojiJson(
462 JSON.stringify({
463 data: {
464 currentUser: { username: "bilal" },
465 project: {
466 mergeRequest: {
467 awardEmoji: {
468 nodes: [
469 { name: "thumbsup", user: { username: "bilal" } },
470 { name: "thumbsup", user: { username: "julius" } },
471 ],
472 },
473 notes: {
474 pageInfo: { hasNextPage: false, endCursor: null },
475 nodes: [
476 {
477 id: "gid://gitlab/DiffNote/42",
478 awardEmoji: { nodes: [{ name: "heart", user: { username: "julius" } }] },
479 },
480 {
481 id: "gid://gitlab/Note/7",
482 awardEmoji: {
483 nodes: [{ name: "partyparrot", user: { username: "bilal" } }],
484 },
485 },
486 ],
487 },
488 },
489 },
490 },
491 }),
492 ),
493 );
494
495 expect(result.reactions).toEqual([
496 { content: "thumbs-up", count: 2, actors: ["julius"], viewerHasReacted: true },
497 ]);
498 expect([...result.reactionsByNoteId]).toEqual([
499 ["42", [{ content: "heart", count: 1, actors: ["julius"], viewerHasReacted: false }]],
500 ]);
501 expect(result.nextCursor).toBeNull();
502 });
503
504 it("matches the viewer's username case-insensitively, since GitLab is not consistent about case", () => {
505 const result = expectSuccess(
506 decodeAwardEmojiJson(
507 JSON.stringify({
508 data: {
509 currentUser: { username: "Bilal" },
510 project: {
511 mergeRequest: {
512 awardEmoji: {
513 nodes: [
514 { name: "heart", user: { username: "bilal" } },
515 { name: "heart", user: { username: "julius" } },
516 ],
517 },
518 notes: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] },
519 },
520 },
521 },
522 }),
523 ),
524 );
525
526 expect(result.reactions).toEqual([
527 { content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
528 ]);
529 });
530});
531
532describe("decodeOwnAwardIdJson", () => {
533 const awards = JSON.stringify([
534 { id: 101, name: "thumbsup", user: { username: "julius" } },
535 { id: 102, name: "thumbsup", user: { username: "bilal" } },
536 ]);
537
538 it("finds the reader's own award of that name, which is the one a removal deletes", () => {
539 expect(
540 expectSuccess(decodeOwnAwardIdJson(awards, { content: "thumbs-up", viewer: "bilal" })),
541 ).toBe(102);
542 });
543});
544
545describe("decodeRepositoryBlobsJson", () => {
546 function expectBlobs(result: Result.Result<ReadonlyMap<string, string> | null, unknown>) {
547 const blobs = expectSuccess(result);
548 expect(blobs).not.toBe(null);
549 if (blobs === null) throw new Error("expected an answered blobs query");
550 return blobs;
551 }
552
553 it("leaves out a node missing either half, which names no version", () => {
554 const blobs = expectBlobs(
555 decodeRepositoryBlobsJson(
556 JSON.stringify({
557 data: {
558 project: {
559 repository: {
560 blobs: {
561 nodes: [
562 { path: "src/a.ts", oid: null },
563 { path: null, oid: "bbb222" },
564 null,
565 { path: "src/c.ts", oid: "ccc333" },
566 ],
567 },
568 },
569 },
570 },
571 }),
572 ),
573 );
574
575 expect([...blobs]).toEqual([["src/c.ts", "ccc333"]]);
576 });
577
578 it("keys a blob by the path the host spelled, spaces and all", () => {
579 const blobs = expectBlobs(
580 decodeRepositoryBlobsJson(
581 JSON.stringify({
582 data: {
583 project: {
584 repository: {
585 blobs: {
586 nodes: [
587 { path: " leading.ts", oid: "aaa111" },
588 { path: "trailing.ts ", oid: "bbb222" },
589 { path: " ", oid: "ccc333" },
590 { path: "", oid: "ddd444" },
591 ],
592 },
593 },
594 },
595 },
596 }),
597 ),
598 );
599
600 expect([...blobs]).toEqual([
601 [" leading.ts", "aaa111"],
602 ["trailing.ts ", "bbb222"],
603 [" ", "ccc333"],
604 ]);
605 });
606
607 it("tells a project the reader cannot see from a revision with none of the files", () => {
608 expect(
609 expectSuccess(decodeRepositoryBlobsJson(JSON.stringify({ data: { project: null } }))),
610 ).toBe(null);
611 expect(
612 expectSuccess(
613 decodeRepositoryBlobsJson(JSON.stringify({ data: { project: { repository: null } } })),
614 ),
615 ).toBe(null);
616 expect(
617 expectSuccess(
618 decodeRepositoryBlobsJson(
619 JSON.stringify({ data: { project: { repository: { blobs: { nodes: [] } } } } }),
620 ),
621 ),
622 ).toEqual(new Map());
623 });
624});
625
626describe("decodeMergeRequestStatsJson", () => {
627 it("keys the counts by merge request number", () => {
628 const stats = expectSuccess(
629 decodeMergeRequestStatsJson(
630 JSON.stringify({
631 data: {
632 project: {
633 mergeRequests: {
634 nodes: [
635 { iid: "7", diffStatsSummary: { additions: 12, deletions: 3 } },
636 { iid: "8", diffStatsSummary: null },
637 ],
638 },
639 },
640 },
641 }),
642 ),
643 );
644
645 // A merge request without a summary is left out rather than shown as zero lines changed.
646 expect([...stats]).toEqual([[7, { additions: 12, deletions: 3 }]]);
647 });
648
649 it("answers nothing for a project the token cannot see", () => {
650 const stats = expectSuccess(
651 decodeMergeRequestStatsJson(JSON.stringify({ data: { project: null } })),
652 );
653
654 expect(stats.size).toBe(0);
655 });
656
657 it("reports a file list shorter than the summary as truncated", () => {
658 const read = (fileCount: number) =>
659 expectSuccess(
660 decodeMergeRequestFileStatsJson(
661 JSON.stringify({
662 data: {
663 project: {
664 mergeRequest: {
665 diffStatsSummary: { fileCount },
666 diffStats: [{ path: "src/a.ts", additions: 2, deletions: 1 }],
667 },
668 },
669 },
670 }),
671 ),
672 );
673
674 expect(read(1)).toEqual({
675 files: [{ path: "src/a.ts", additions: 2, deletions: 1 }],
676 truncated: false,
677 });
678 expect(read(2).truncated).toBe(true);
679 });
680});