Open History to see the last commit
1import { assert, describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as TestClock from "effect/testing/TestClock";
5
6import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
7
8import * as GitLabCli from "./GitLabCli.ts";
9import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
10import { gitLabViewerPermissions, make } from "./GitLabPullRequestProvider.ts";
11
12it.effect.each(["merge", "disable-auto-merge"] as const)(
13 "keeps reads and %s on the selected host when glab prefers another remote",
14 (action) =>
15 Effect.gen(function* () {
16 const selectedHost = "gitlab.example.test:8443";
17 const otherHost = "other.gitlab.example.test";
18 const readHosts: string[] = [];
19 const mergedHosts: string[] = [];
20 const native = yield* GitLabCli.make.pipe(
21 Effect.provide(
22 TestSourceControlHost.layer({
23 process: {
24 run: (input) => {
25 // glab prefers a remote named `gitlab` to `origin`. The checkout's
26 // selected repository must still own every request and mutation.
27 const host = input.env?.GITLAB_HOST ?? otherHost;
28 const path = input.args[1];
29 const mutation =
30 input.args[0] === "mr" || (input.args.includes("POST") && path !== "graphql");
31 if (mutation) mergedHosts.push(host);
32 else readHosts.push(host);
33 const response = mutation
34 ? {}
35 : path === "graphql"
36 ? {
37 data: {
38 project: {
39 mergeRequests: {
40 nodes: [
41 { iid: "7", diffStatsSummary: { additions: 2, deletions: 1 } },
42 ],
43 },
44 mergeRequest: {
45 diffStatsSummary: { fileCount: 1 },
46 diffStats: [{ path: "src/a.ts", additions: 2, deletions: 1 }],
47 },
48 },
49 },
50 }
51 : path?.includes("merge_requests/")
52 ? {
53 iid: 7,
54 title: "Merge request 7",
55 web_url: `https://${host}/acme/web/-/merge_requests/7`,
56 source_branch: "feature",
57 target_branch: "main",
58 created_at: "2026-07-01T00:00:00Z",
59 updated_at: "2026-07-02T00:00:00Z",
60 user: { can_merge: true },
61 diff_refs: {
62 head_sha: "a".repeat(40),
63 base_sha: "b".repeat(40),
64 start_sha: "b".repeat(40),
65 },
66 }
67 : path === "user"
68 ? { username: "reviewer" }
69 : path?.includes("/labels?") || path?.includes("/users?")
70 ? []
71 : { merge_method: "merge", squash_option: "default_off" };
72 return Effect.succeed(
73 TestSourceControlHost.processOutput(JSON.stringify(response)),
74 );
75 },
76 },
77 }),
78 ),
79 );
80 const cli = yield* GitLabPullRequestCli.make.pipe(
81 Effect.provideService(GitLabCli.GitLabCli, native),
82 );
83 const provider = yield* make.pipe(
84 Effect.provideService(GitLabPullRequestCli.GitLabPullRequestCli, cli),
85 );
86 const reference = {
87 cwd: "/repo",
88 repository: "acme/web",
89 host: selectedHost,
90 number: 7,
91 };
92 const detail = yield* provider.getChangeRequest(reference);
93 expect({ additions: detail.additions, deletions: detail.deletions }).toEqual({
94 additions: 2,
95 deletions: 1,
96 });
97 assert.isDefined(provider.getChangeRequestSummary);
98 expect((yield* provider.getChangeRequestSummary(reference)).additions).toBe(2);
99 assert.isDefined(provider.listChangeRequestStats);
100 expect(
101 yield* provider.listChangeRequestStats({ ...reference, changeRequests: [reference] }),
102 ).toEqual([{ repository: reference.repository, number: 7, additions: 2, deletions: 1 }]);
103 assert.isDefined(provider.getFileStats);
104 expect(yield* provider.getFileStats(reference)).toEqual({
105 files: [{ path: "src/a.ts", additions: 2, deletions: 1 }],
106 truncated: false,
107 });
108 expect(yield* provider.getViewer(reference)).toBe("reviewer");
109 assert.isDefined(provider.listRepositoryLabels);
110 yield* provider.listRepositoryLabels(reference);
111 assert.isDefined(provider.searchRepositoryAuthors);
112 yield* provider.searchRepositoryAuthors(reference);
113 yield* provider.runAction({ ...reference, action });
114
115 expect(readHosts).toEqual(Array(action === "merge" ? 12 : 11).fill(selectedHost));
116 expect({ url: detail.url, mutatedHosts: mergedHosts }).toEqual({
117 url: `https://${selectedHost}/acme/web/-/merge_requests/7`,
118 mutatedHosts: [selectedHost],
119 });
120 }),
121);
122
123describe("gitLabViewerPermissions", () => {
124 it("offers everything to a viewer GitLab says can merge", () => {
125 expect(gitLabViewerPermissions({ viewerCanMerge: true })).toEqual({
126 actions: [
127 "merge",
128 "ready",
129 "draft",
130 "close",
131 "reopen",
132 "update-branch",
133 "enable-auto-merge",
134 "disable-auto-merge",
135 ],
136 comment: true,
137 resolve: true,
138 verdicts: ["comment", "approve"],
139 requestReviewers: true,
140 updateMethods: ["rebase"],
141 });
142 });
143
144 it("keeps merge, now and later, from a viewer GitLab says cannot", () => {
145 expect(gitLabViewerPermissions({ viewerCanMerge: false })).toEqual({
146 actions: ["ready", "draft", "close", "reopen"],
147 comment: true,
148 resolve: true,
149 verdicts: ["comment", "approve"],
150 requestReviewers: true,
151 });
152 });
153});
154
155describe("getChangeRequest base freshness", () => {
156 const detail = {
157 number: 7,
158 title: "Merge request 7",
159 url: "https://gitlab.com/acme/web/-/merge_requests/7",
160 author: null,
161 headBranch: "feat/page",
162 baseBranch: "main",
163 state: "open" as const,
164 isDraft: false,
165 mergeability: "mergeable" as const,
166 additions: 0,
167 deletions: 0,
168 createdAt: "2026-07-01T00:00:00Z",
169 updatedAt: "2026-07-02T00:00:00Z",
170 reviewRequestLogins: [],
171 labels: [],
172 body: "",
173 changedFiles: 1,
174 mergedAt: null,
175 closedAt: null,
176 reviewers: [],
177 checks: [],
178 viewerCanMerge: true,
179 reviewerIds: [],
180 };
181
182 it.effect.each(["getChangeRequestPreview", "getChangeRequestSummary"] as const)(
183 "%s preserves merge request fields without fetching project settings",
184 (operation) =>
185 Effect.gen(function* () {
186 const provider = yield* make.pipe(
187 Effect.provide(
188 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
189 getMergeRequestDetail: () => Effect.succeed(detail),
190 getReviewDecisions: () => Effect.succeed(new Map()),
191
192 listMergeRequestStats: () => Effect.succeed([]),
193 }),
194 ),
195 );
196 const read = provider[operation];
197 assert.isDefined(read);
198 expect(
199 yield* read({ cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 }),
200 ).toEqual(detail);
201 }),
202 );
203
204 const readWith = (
205 divergence: { readonly divergedCommits?: number },
206 stats: GitLabPullRequestCli.GitLabPullRequestCli["Service"]["listMergeRequestStats"] = () =>
207 Effect.succeed([]),
208 ) =>
209 Effect.gen(function* () {
210 const provider = yield* make;
211 return yield* provider.getChangeRequest({
212 cwd: "/w",
213 repository: "acme/web",
214 host: "gitlab.com",
215 number: 7,
216 });
217 }).pipe(
218 Effect.provide(
219 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
220 getMergeRequestDetail: () => Effect.succeed({ ...detail, ...divergence }),
221 getProjectMergeCapabilities: () =>
222 Effect.succeed({ merge: true, squash: true, rebase: true }),
223 listMergeRequestStats: stats,
224 }),
225 ),
226 );
227
228 it.effect("reads a counted divergence as a branch that has fallen behind", () =>
229 Effect.gen(function* () {
230 const changeRequest = yield* readWith({ divergedCommits: 3 });
231
232 expect(changeRequest.baseComparison).toBe("behind");
233 expect(changeRequest.behindBy).toBe(3);
234 }),
235 );
236
237 it.effect("says nothing at all where GitLab counted nothing", () =>
238 Effect.gen(function* () {
239 const changeRequest = yield* readWith({});
240
241 expect(changeRequest.baseComparison).toBe("unknown");
242 expect(changeRequest.behindBy).toBeUndefined();
243 }),
244 );
245
246 it.effect("fills in the line counts the REST detail leaves out", () =>
247 Effect.gen(function* () {
248 const changeRequest = yield* readWith({}, () =>
249 Effect.succeed([{ repository: "acme/web", number: 7, additions: 40, deletions: 2 }]),
250 );
251
252 expect(changeRequest.additions).toBe(40);
253 expect(changeRequest.deletions).toBe(2);
254 }),
255 );
256
257 it.effect("reports an unauthenticated line count read instead of a detail without counts", () =>
258 Effect.gen(function* () {
259 const result = yield* Effect.result(
260 readWith({}, () =>
261 Effect.fail(
262 new GitLabCli.GitLabCliAuthenticationError({
263 operation: "execute",
264 command: "glab",
265 cwd: "/w",
266 cause: null,
267 }),
268 ),
269 ),
270 );
271
272 expect(result).toMatchObject({
273 _tag: "Failure",
274 failure: { _tag: "PullRequestProviderError", reason: "unauthenticated" },
275 });
276 }),
277 );
278
279 it.effect("gives linked threads line counts without reading the merge settings", () =>
280 Effect.gen(function* () {
281 const summary = yield* Effect.gen(function* () {
282 const provider = yield* make;
283 const read = provider.getChangeRequestSummary;
284 if (read === undefined) return yield* Effect.die("summary read missing");
285 return yield* read({ cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 });
286 }).pipe(
287 Effect.provide(
288 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
289 getMergeRequestDetail: () => Effect.succeed(detail),
290 getProjectMergeCapabilities: () => Effect.die("linked threads skip merge settings"),
291 getReviewDecisions: () => Effect.succeed(new Map()),
292 listMergeRequestStats: () =>
293 Effect.succeed([{ repository: "acme/web", number: 7, additions: 40, deletions: 2 }]),
294 }),
295 ),
296 );
297
298 expect(summary.additions).toBe(40);
299 expect(summary.deletions).toBe(2);
300 }),
301 );
302});
303
304describe("merge request reads", () => {
305 const reference = { cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 };
306 const detail = {
307 number: 7,
308 title: "Merge request 7",
309 url: "https://gitlab.com/acme/web/-/merge_requests/7",
310 author: null,
311 headBranch: "feat/page",
312 baseBranch: "main",
313 state: "open" as const,
314 isDraft: false,
315 mergeability: "mergeable" as const,
316 additions: 0,
317 deletions: 0,
318 createdAt: "2026-07-01T00:00:00Z",
319 updatedAt: "2026-07-02T00:00:00Z",
320 reviewRequestLogins: [],
321 labels: [],
322 body: "",
323 changedFiles: 1,
324 mergedAt: null,
325 closedAt: null,
326 reviewers: [],
327 checks: [],
328 viewerCanMerge: true,
329 reviewerIds: [],
330 };
331
332 const countingProvider = Effect.gen(function* () {
333 const calls = { detail: 0, mergeCapabilities: 0 };
334 const host = { viewerCanMerge: true };
335 const provider = yield* make.pipe(
336 Effect.provide(
337 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
338 listMergeRequestStats: () => Effect.succeed([]),
339 getReviewDecisions: () => Effect.succeed(new Map()),
340 getMergeRequestDetail: (input) =>
341 Effect.sync(() => {
342 calls.detail += 1;
343 return { ...detail, number: input.number, viewerCanMerge: host.viewerCanMerge };
344 }),
345 getProjectMergeCapabilities: () =>
346 Effect.sync(() => {
347 calls.mergeCapabilities += 1;
348 return { merge: true, squash: true, rebase: true };
349 }),
350 runMergeRequestAction: () => Effect.void,
351 }),
352 ),
353 );
354 const checks = provider.getChangeRequestChecks;
355 const forget = provider.forgetChangeRequestReads;
356 if (checks === undefined || forget === undefined) {
357 return yield* Effect.die("GitLab answers checks and forgets its reads");
358 }
359 return { provider, checks, forget, calls, host };
360 });
361
362 it.effect("asks for a project's merge methods once across its merge requests", () =>
363 Effect.gen(function* () {
364 const { provider, calls } = yield* countingProvider;
365
366 yield* provider.getChangeRequest(reference);
367 yield* provider.getChangeRequest(reference);
368 yield* provider.getChangeRequest({ ...reference, number: 8 });
369
370 expect(calls.mergeCapabilities).toBe(1);
371 }),
372 );
373
374 it.effect("answers checks from the merge request the detail just read", () =>
375 Effect.gen(function* () {
376 const { provider, checks, calls } = yield* countingProvider;
377
378 yield* provider.getChangeRequest(reference);
379 yield* checks(reference);
380
381 expect(calls.detail).toBe(1);
382
383 const summary = provider.getChangeRequestSummary;
384 assert.isDefined(summary);
385 yield* summary(reference);
386 expect(calls.detail).toBe(2);
387 }),
388 );
389
390 it.effect("reads a merge request again after a write to it", () =>
391 Effect.gen(function* () {
392 const { provider, checks, calls } = yield* countingProvider;
393
394 yield* provider.getChangeRequest(reference);
395 yield* provider.runAction({ ...reference, action: "ready" });
396 yield* checks(reference);
397
398 expect(calls.detail).toBe(2);
399 }),
400 );
401
402 it.effect.each([{ cwd: "/other" }, { host: "other.gitlab.test" }])(
403 "does not share reads with %j",
404 (other) =>
405 Effect.gen(function* () {
406 const { provider, calls } = yield* countingProvider;
407
408 yield* provider.getChangeRequest(reference);
409 yield* provider.getChangeRequest({ ...reference, ...other });
410 yield* provider.getChangeRequest(reference);
411 yield* provider.getChangeRequest({ ...reference, ...other });
412
413 expect(calls).toEqual({ detail: 2, mergeCapabilities: 2 });
414 }),
415 );
416
417 it.effect("reads a merge request again once a minute has passed", () =>
418 Effect.gen(function* () {
419 const { provider, calls } = yield* countingProvider;
420
421 yield* provider.getChangeRequest(reference);
422 yield* TestClock.adjust("61 seconds");
423 yield* provider.getChangeRequest(reference);
424
425 expect(calls.detail).toBe(2);
426 }),
427 );
428
429 it.effect("answers viewer permissions from the host, not the page's read", () =>
430 Effect.gen(function* () {
431 const { provider, host } = yield* countingProvider;
432
433 host.viewerCanMerge = false;
434 yield* provider.getChangeRequest(reference);
435 host.viewerCanMerge = true;
436 const granted = yield* provider.getViewerPermissions(reference);
437 host.viewerCanMerge = false;
438 const revoked = yield* provider.getViewerPermissions(reference);
439
440 expect(granted.actions).toContain("merge");
441 expect(revoked.actions).not.toContain("merge");
442 }),
443 );
444
445 it.effect("reads a merge request again once its reads are forgotten", () =>
446 Effect.gen(function* () {
447 const { provider, checks, forget, calls } = yield* countingProvider;
448 const other = { ...reference, repository: "acme/api" };
449
450 yield* provider.getChangeRequest(reference);
451 yield* provider.getChangeRequest(other);
452 yield* forget({ repository: "ACME/web", number: 7 });
453 yield* checks(reference);
454 yield* checks(other);
455 expect(calls.detail).toBe(3);
456
457 yield* forget({ repository: "acme/web" });
458 yield* checks(reference);
459 yield* forget();
460 yield* checks(other);
461 expect(calls.detail).toBe(5);
462 }),
463 );
464});
465
466describe("optional activity reads", () => {
467 const reference = { cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 };
468 const comment = {
469 id: "42",
470 kind: "issue-comment" as const,
471 author: null,
472 body: "Keep this comment",
473 createdAt: "2026-07-01T00:00:00Z",
474 url: null,
475 path: null,
476 reviewState: null,
477 };
478 const commit = {
479 oid: "abc",
480 messageHeadline: "Keep this commit",
481 committedDate: "2026-07-01T00:00:00Z",
482 };
483 const reads = {
484 listNotes: () => Effect.succeed({ comments: [comment], truncated: false }),
485 listCommits: () => Effect.succeed([commit]),
486 listDiscussions: () => Effect.succeed({ threads: [], truncated: false }),
487 listReactions: () => Effect.succeed({ reactions: [], reactionsByNoteId: new Map() }),
488 };
489 const context = {
490 operation: "execute" as const,
491 command: "glab" as const,
492 cwd: "/w",
493 cause: null,
494 };
495
496 it.effect.each([
497 {
498 operation: "listNotes",
499 error: new GitLabCli.GitLabCliAuthenticationError(context),
500 reason: "unauthenticated",
501 },
502 {
503 operation: "listCommits",
504 error: new GitLabCli.GitLabCliUnavailableError(context),
505 reason: "missing-tool",
506 },
507 ] as const)(
508 "reports $reason instead of successful partial activity",
509 ({ operation, error, reason }) =>
510 Effect.gen(function* () {
511 const provider = yield* make.pipe(
512 Effect.provide(
513 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
514 ...reads,
515 [operation]: () => Effect.fail(error),
516 }),
517 ),
518 );
519
520 expect(yield* Effect.result(provider.getChangeRequestActivity(reference))).toMatchObject({
521 _tag: "Failure",
522 failure: {
523 _tag: "PullRequestProviderError",
524 provider: "gitlab",
525 operation: "getChangeRequestActivity",
526 reason,
527 detail: error.detail,
528 cause: error,
529 },
530 });
531 }),
532 );
533
534 it.effect("keeps comments and commits when optional discussions and reactions fail", () =>
535 Effect.gen(function* () {
536 const provider = yield* make.pipe(
537 Effect.provide(
538 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
539 ...reads,
540 listDiscussions: () =>
541 Effect.fail(
542 new GitLabPullRequestCli.GitLabMergeRequestReadError({
543 command: "glab",
544 cwd: "/w",
545 operation: "listDiscussions",
546 cause: null,
547 }),
548 ),
549 listReactions: () => Effect.fail(new GitLabCli.GitLabCliCommandError(context)),
550 }),
551 ),
552 );
553
554 expect(yield* provider.getChangeRequestActivity(reference)).toEqual({
555 comments: [{ ...comment, reactions: [] }],
556 commentCount: 1,
557 commentsTruncated: true,
558 reviewThreads: [],
559 reactions: [],
560 commits: [commit],
561 });
562 }),
563 );
564});
565
566describe("review decisions", () => {
567 const reference = { cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 };
568 const item = {
569 number: 7,
570 title: "Merge request 7",
571 url: "https://gitlab.com/acme/web/-/merge_requests/7",
572 author: null,
573 headBranch: "feat/page",
574 baseBranch: "main",
575 state: "open" as const,
576 isDraft: false,
577 mergeability: "mergeable" as const,
578 additions: 0,
579 deletions: 0,
580 createdAt: "2026-07-01T00:00:00Z",
581 updatedAt: "2026-07-02T00:00:00Z",
582 reviewRequestLogins: [],
583 labels: [],
584 };
585 const detail = {
586 ...item,
587 body: "",
588 changedFiles: 1,
589 mergedAt: null,
590 closedAt: null,
591 reviewers: [],
592 checks: [],
593 viewerCanMerge: true,
594 reviewerIds: [],
595 };
596 const providerWith = (
597 getReviewDecisions: GitLabPullRequestCli.GitLabPullRequestCli["Service"]["getReviewDecisions"],
598 ) =>
599 make.pipe(
600 Effect.provide(
601 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
602 listMergeRequests: () =>
603 Effect.succeed({
604 items: [item, { ...item, number: 8 }],
605 truncated: false,
606 cursorAdvance: 2,
607 }),
608 getMergeRequestDetail: () => Effect.succeed(detail),
609 getReviewDecisions,
610 listMergeRequestStats: () =>
611 Effect.succeed([{ repository: "acme/web", number: 7, additions: 40, deletions: 2 }]),
612 }),
613 ),
614 );
615 const listing = {
616 cwd: "/w",
617 repository: "acme/web",
618 host: "gitlab.com",
619 state: "open" as const,
620 involvement: "all" as const,
621 viewer: "julius",
622 limit: 2,
623 };
624
625 it.effect("puts GitLab's approval state on listed and summarized merge requests", () =>
626 Effect.gen(function* () {
627 const provider = yield* providerWith((input) => {
628 expect(input.host).toBe(reference.host);
629 return Effect.succeed(
630 new Map([
631 [7, "approved" as const],
632 [8, null],
633 ]),
634 );
635 });
636 const listed = yield* provider.listChangeRequests(listing);
637 assert.isDefined(provider.getChangeRequestSummary);
638 const summary = yield* provider.getChangeRequestSummary(reference);
639
640 expect(listed.items.map(({ reviewDecision }) => reviewDecision)).toEqual(["approved", null]);
641 expect(summary.reviewDecision).toBe("approved");
642 expect(summary.additions).toBe(40);
643 expect(summary.deletions).toBe(2);
644 }),
645 );
646
647 it.effect.each([
648 {
649 failure: "a failed read",
650 error: new GitLabPullRequestCli.GitLabMergeRequestReadError({
651 command: "glab",
652 cwd: "/w",
653 operation: "getReviewDecisions",
654 cause: null,
655 }),
656 },
657 {
658 failure: "a rate limit",
659 error: new GitLabCli.GitLabCliRateLimitError({
660 operation: "execute",
661 command: "glab",
662 cwd: "/w",
663 cause: null,
664 }),
665 },
666 ])("keeps rows and summaries with an unknown decision after $failure", ({ error }) =>
667 Effect.gen(function* () {
668 const provider = yield* providerWith(() => Effect.fail(error));
669 const listed = yield* provider.listChangeRequests(listing);
670 assert.isDefined(provider.getChangeRequestSummary);
671 const summary = yield* provider.getChangeRequestSummary(reference);
672
673 expect(listed.items.map(({ reviewDecision }) => reviewDecision)).toEqual([
674 undefined,
675 undefined,
676 ]);
677 expect(summary.reviewDecision).toBeUndefined();
678 }),
679 );
680});