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

GitLabPullRequestProvider.test.ts

560 lines18.9 KB

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" ? 11 : 10).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 listMergeRequestStats: () => Effect.succeed([]),
191 }),
192 ),
193 );
194 const read = provider[operation];
195 assert.isDefined(read);
196 expect(
197 yield* read({ cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 }),
198 ).toEqual(detail);
199 }),
200 );
201​
202 const readWith = (
203 divergence: { readonly divergedCommits?: number },
204 stats: GitLabPullRequestCli.GitLabPullRequestCli["Service"]["listMergeRequestStats"] = () =>
205 Effect.succeed([]),
206 ) =>
207 Effect.gen(function* () {
208 const provider = yield* make;
209 return yield* provider.getChangeRequest({
210 cwd: "/w",
211 repository: "acme/web",
212 host: "gitlab.com",
213 number: 7,
214 });
215 }).pipe(
216 Effect.provide(
217 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
218 getMergeRequestDetail: () => Effect.succeed({ ...detail, ...divergence }),
219 getProjectMergeCapabilities: () =>
220 Effect.succeed({ merge: true, squash: true, rebase: true }),
221 listMergeRequestStats: stats,
222 }),
223 ),
224 );
225​
226 it.effect("reads a counted divergence as a branch that has fallen behind", () =>
227 Effect.gen(function* () {
228 const changeRequest = yield* readWith({ divergedCommits: 3 });
229​
230 expect(changeRequest.baseComparison).toBe("behind");
231 expect(changeRequest.behindBy).toBe(3);
232 }),
233 );
234​
235 it.effect("says nothing at all where GitLab counted nothing", () =>
236 Effect.gen(function* () {
237 const changeRequest = yield* readWith({});
238​
239 expect(changeRequest.baseComparison).toBe("unknown");
240 expect(changeRequest.behindBy).toBeUndefined();
241 }),
242 );
243​
244 it.effect("fills in the line counts the REST detail leaves out", () =>
245 Effect.gen(function* () {
246 const changeRequest = yield* readWith({}, () =>
247 Effect.succeed([{ repository: "acme/web", number: 7, additions: 40, deletions: 2 }]),
248 );
249​
250 expect(changeRequest.additions).toBe(40);
251 expect(changeRequest.deletions).toBe(2);
252 }),
253 );
254​
255 it.effect("reports an unauthenticated line count read instead of a detail without counts", () =>
256 Effect.gen(function* () {
257 const result = yield* Effect.result(
258 readWith({}, () =>
259 Effect.fail(
260 new GitLabCli.GitLabCliAuthenticationError({
261 operation: "execute",
262 command: "glab",
263 cwd: "/w",
264 cause: null,
265 }),
266 ),
267 ),
268 );
269​
270 expect(result).toMatchObject({
271 _tag: "Failure",
272 failure: { _tag: "PullRequestProviderError", reason: "unauthenticated" },
273 });
274 }),
275 );
276​
277 it.effect("gives linked threads line counts without reading the merge settings", () =>
278 Effect.gen(function* () {
279 const summary = yield* Effect.gen(function* () {
280 const provider = yield* make;
281 const read = provider.getChangeRequestSummary;
282 if (read === undefined) return yield* Effect.die("summary read missing");
283 return yield* read({ cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 });
284 }).pipe(
285 Effect.provide(
286 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
287 getMergeRequestDetail: () => Effect.succeed(detail),
288 getProjectMergeCapabilities: () => Effect.die("linked threads skip merge settings"),
289 listMergeRequestStats: () =>
290 Effect.succeed([{ repository: "acme/web", number: 7, additions: 40, deletions: 2 }]),
291 }),
292 ),
293 );
294​
295 expect(summary.additions).toBe(40);
296 expect(summary.deletions).toBe(2);
297 }),
298 );
299});
300​
301describe("merge request reads", () => {
302 const reference = { cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 };
303 const detail = {
304 number: 7,
305 title: "Merge request 7",
306 url: "https://gitlab.com/acme/web/-/merge_requests/7",
307 author: null,
308 headBranch: "feat/page",
309 baseBranch: "main",
310 state: "open" as const,
311 isDraft: false,
312 mergeability: "mergeable" as const,
313 additions: 0,
314 deletions: 0,
315 createdAt: "2026-07-01T00:00:00Z",
316 updatedAt: "2026-07-02T00:00:00Z",
317 reviewRequestLogins: [],
318 labels: [],
319 body: "",
320 changedFiles: 1,
321 mergedAt: null,
322 closedAt: null,
323 reviewers: [],
324 checks: [],
325 viewerCanMerge: true,
326 reviewerIds: [],
327 };
328​
329 const countingProvider = Effect.gen(function* () {
330 const calls = { detail: 0, mergeCapabilities: 0 };
331 const host = { viewerCanMerge: true };
332 const provider = yield* make.pipe(
333 Effect.provide(
334 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
335 listMergeRequestStats: () => Effect.succeed([]),
336 getMergeRequestDetail: (input) =>
337 Effect.sync(() => {
338 calls.detail += 1;
339 return { ...detail, number: input.number, viewerCanMerge: host.viewerCanMerge };
340 }),
341 getProjectMergeCapabilities: () =>
342 Effect.sync(() => {
343 calls.mergeCapabilities += 1;
344 return { merge: true, squash: true, rebase: true };
345 }),
346 runMergeRequestAction: () => Effect.void,
347 }),
348 ),
349 );
350 const checks = provider.getChangeRequestChecks;
351 const forget = provider.forgetChangeRequestReads;
352 if (checks === undefined || forget === undefined) {
353 return yield* Effect.die("GitLab answers checks and forgets its reads");
354 }
355 return { provider, checks, forget, calls, host };
356 });
357​
358 it.effect("asks for a project's merge methods once across its merge requests", () =>
359 Effect.gen(function* () {
360 const { provider, calls } = yield* countingProvider;
361​
362 yield* provider.getChangeRequest(reference);
363 yield* provider.getChangeRequest(reference);
364 yield* provider.getChangeRequest({ ...reference, number: 8 });
365​
366 expect(calls.mergeCapabilities).toBe(1);
367 }),
368 );
369​
370 it.effect("answers checks from the merge request the detail just read", () =>
371 Effect.gen(function* () {
372 const { provider, checks, calls } = yield* countingProvider;
373​
374 yield* provider.getChangeRequest(reference);
375 yield* checks(reference);
376​
377 expect(calls.detail).toBe(1);
378​
379 const summary = provider.getChangeRequestSummary;
380 assert.isDefined(summary);
381 yield* summary(reference);
382 expect(calls.detail).toBe(2);
383 }),
384 );
385​
386 it.effect("reads a merge request again after a write to it", () =>
387 Effect.gen(function* () {
388 const { provider, checks, calls } = yield* countingProvider;
389​
390 yield* provider.getChangeRequest(reference);
391 yield* provider.runAction({ ...reference, action: "ready" });
392 yield* checks(reference);
393​
394 expect(calls.detail).toBe(2);
395 }),
396 );
397​
398 it.effect.each([{ cwd: "/other" }, { host: "other.gitlab.test" }])(
399 "does not share reads with %j",
400 (other) =>
401 Effect.gen(function* () {
402 const { provider, calls } = yield* countingProvider;
403​
404 yield* provider.getChangeRequest(reference);
405 yield* provider.getChangeRequest({ ...reference, ...other });
406 yield* provider.getChangeRequest(reference);
407 yield* provider.getChangeRequest({ ...reference, ...other });
408​
409 expect(calls).toEqual({ detail: 2, mergeCapabilities: 2 });
410 }),
411 );
412​
413 it.effect("reads a merge request again once a minute has passed", () =>
414 Effect.gen(function* () {
415 const { provider, calls } = yield* countingProvider;
416​
417 yield* provider.getChangeRequest(reference);
418 yield* TestClock.adjust("61 seconds");
419 yield* provider.getChangeRequest(reference);
420​
421 expect(calls.detail).toBe(2);
422 }),
423 );
424​
425 it.effect("answers viewer permissions from the host, not the page's read", () =>
426 Effect.gen(function* () {
427 const { provider, host } = yield* countingProvider;
428​
429 host.viewerCanMerge = false;
430 yield* provider.getChangeRequest(reference);
431 host.viewerCanMerge = true;
432 const granted = yield* provider.getViewerPermissions(reference);
433 host.viewerCanMerge = false;
434 const revoked = yield* provider.getViewerPermissions(reference);
435​
436 expect(granted.actions).toContain("merge");
437 expect(revoked.actions).not.toContain("merge");
438 }),
439 );
440​
441 it.effect("reads a merge request again once its reads are forgotten", () =>
442 Effect.gen(function* () {
443 const { provider, checks, forget, calls } = yield* countingProvider;
444 const other = { ...reference, repository: "acme/api" };
445​
446 yield* provider.getChangeRequest(reference);
447 yield* provider.getChangeRequest(other);
448 yield* forget({ repository: "ACME/web", number: 7 });
449 yield* checks(reference);
450 yield* checks(other);
451 expect(calls.detail).toBe(3);
452​
453 yield* forget({ repository: "acme/web" });
454 yield* checks(reference);
455 yield* forget();
456 yield* checks(other);
457 expect(calls.detail).toBe(5);
458 }),
459 );
460});
461​
462describe("optional activity reads", () => {
463 const reference = { cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 };
464 const comment = {
465 id: "42",
466 kind: "issue-comment" as const,
467 author: null,
468 body: "Keep this comment",
469 createdAt: "2026-07-01T00:00:00Z",
470 url: null,
471 path: null,
472 reviewState: null,
473 };
474 const commit = {
475 oid: "abc",
476 messageHeadline: "Keep this commit",
477 committedDate: "2026-07-01T00:00:00Z",
478 };
479 const reads = {
480 listNotes: () => Effect.succeed({ comments: [comment], truncated: false }),
481 listCommits: () => Effect.succeed([commit]),
482 listDiscussions: () => Effect.succeed({ threads: [], truncated: false }),
483 listReactions: () => Effect.succeed({ reactions: [], reactionsByNoteId: new Map() }),
484 };
485 const context = {
486 operation: "execute" as const,
487 command: "glab" as const,
488 cwd: "/w",
489 cause: null,
490 };
491​
492 it.effect.each([
493 {
494 operation: "listNotes",
495 error: new GitLabCli.GitLabCliAuthenticationError(context),
496 reason: "unauthenticated",
497 },
498 {
499 operation: "listCommits",
500 error: new GitLabCli.GitLabCliUnavailableError(context),
501 reason: "missing-tool",
502 },
503 ] as const)(
504 "reports $reason instead of successful partial activity",
505 ({ operation, error, reason }) =>
506 Effect.gen(function* () {
507 const provider = yield* make.pipe(
508 Effect.provide(
509 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
510 ...reads,
511 [operation]: () => Effect.fail(error),
512 }),
513 ),
514 );
515​
516 expect(yield* Effect.result(provider.getChangeRequestActivity(reference))).toMatchObject({
517 _tag: "Failure",
518 failure: {
519 _tag: "PullRequestProviderError",
520 provider: "gitlab",
521 operation: "getChangeRequestActivity",
522 reason,
523 detail: error.detail,
524 cause: error,
525 },
526 });
527 }),
528 );
529​
530 it.effect("keeps comments and commits when optional discussions and reactions fail", () =>
531 Effect.gen(function* () {
532 const provider = yield* make.pipe(
533 Effect.provide(
534 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
535 ...reads,
536 listDiscussions: () =>
537 Effect.fail(
538 new GitLabPullRequestCli.GitLabMergeRequestReadError({
539 command: "glab",
540 cwd: "/w",
541 operation: "listDiscussions",
542 cause: null,
543 }),
544 ),
545 listReactions: () => Effect.fail(new GitLabCli.GitLabCliCommandError(context)),
546 }),
547 ),
548 );
549​
550 expect(yield* provider.getChangeRequestActivity(reference)).toEqual({
551 comments: [{ ...comment, reactions: [] }],
552 commentCount: 1,
553 commentsTruncated: true,
554 reviewThreads: [],
555 reactions: [],
556 commits: [commit],
557 });
558 }),
559 );
560});