Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
5
6import * as ForgejoCli from "./ForgejoCli.ts";
7import * as ForgejoPullRequestProvider from "./ForgejoPullRequestProvider.ts";
8
9it.effect("reads file revisions from the pull request diff and refuses a truncated one", () =>
10 Effect.gen(function* () {
11 let truncated = false;
12 const diff = [
13 "diff --git a/alpha.ts b/alpha.ts",
14 "index eb2d7c5..b485fe5 100644",
15 "diff --git a/beta.ts b/beta.ts",
16 "index b39e8b3..5851425 100644",
17 'diff --git "a/caf\\303\\251 notes.txt" "b/caf\\303\\251 notes.txt"',
18 "index ffd99ce..6dd9855 100644",
19 "diff --git a/deleted.txt b/deleted.txt",
20 "deleted file mode 100644",
21 "index 233f5c6..0000000",
22 "diff --git a/old.txt b/renamed.txt",
23 "similarity index 100%",
24 "rename from old.txt",
25 "rename to renamed.txt",
26 "",
27 ].join("\n");
28 const provider = yield* ForgejoPullRequestProvider.make.pipe(
29 Effect.provide(
30 Layer.mock(ForgejoCli.ForgejoCli)({
31 api: (input) => {
32 assert.strictEqual(input.host, "forge.example:3000");
33 assert.strictEqual(input.repository, "reviewer/project");
34 assert.strictEqual(input.path, "repos/reviewer/project/pulls/1.diff");
35 return Effect.succeed({
36 ...TestSourceControlHost.processOutput(diff),
37 stdoutTruncated: truncated,
38 });
39 },
40 }),
41 ),
42 );
43 const reference = {
44 cwd: "/forgejo",
45 repository: "reviewer/project",
46 host: "forge.example:3000",
47 number: 1,
48 };
49 const paths = ["alpha.ts", "beta.ts", "café notes.txt", "deleted.txt", "renamed.txt"];
50 assert.isDefined(provider.getFileRevisions);
51 const answer = yield* provider.getFileRevisions!({ ...reference, paths });
52 assert.isTrue(answer.complete);
53 assert.deepStrictEqual(
54 paths.map((path) => [path, answer.revisions.get(path)]),
55 [
56 ["alpha.ts", "b485fe5"],
57 ["beta.ts", "5851425"],
58 ["café notes.txt", "6dd9855"],
59 ["deleted.txt", "0000000"],
60 ["renamed.txt", ""],
61 ],
62 );
63
64 truncated = true;
65 const refused = yield* Effect.flip(provider.getFileRevisions!({ ...reference, paths }));
66 assert.strictEqual(refused._tag, "PullRequestProviderError");
67 }),
68);
69
70it.effect("filters listed pull requests by the requested state", () =>
71 Effect.gen(function* () {
72 // Forgejo answers a `state=closed` query with merged and closed-unmerged rows alike.
73 const rows = [true, false].map((merged) => ({
74 number: merged ? 1 : 2,
75 title: `Pull request ${merged ? 1 : 2}`,
76 body: "",
77 html_url: `https://forge.example:3000/maria/project/pulls/${merged ? 1 : 2}`,
78 user: { login: "maria" },
79 state: "closed",
80 merged,
81 head: { ref: "feature", sha: "head-sha", repo: null },
82 base: { ref: "main", sha: "base-sha", repo: null },
83 created_at: "2026-10-12T00:00:00Z",
84 updated_at: "2026-10-12T00:00:00Z",
85 closed_at: "2026-10-13T00:00:00Z",
86 merged_at: merged ? "2026-10-13T00:00:00Z" : null,
87 labels: [],
88 }));
89 const provider = yield* ForgejoPullRequestProvider.make.pipe(
90 Effect.provide(
91 Layer.mock(ForgejoCli.ForgejoCli)({
92 api: (input) => {
93 const [path, query] = input.path.split("?");
94 assert.strictEqual(path, "repos/maria/project/pulls");
95 const params = new URLSearchParams(query);
96 // A merged list asks Forgejo for closed rows and separates them itself.
97 const state = params.get("state");
98 assert.ok(state === "closed" || state === "open" || state === "all");
99 const page = params.get("page") === "1" && state !== "open" ? rows : [];
100 return Effect.succeed(TestSourceControlHost.processOutput(JSON.stringify(page)));
101 },
102 }),
103 ),
104 );
105 const input = {
106 cwd: "/forgejo",
107 repository: "maria/project",
108 host: "forge.example:3000",
109 involvement: "all" as const,
110 viewer: "maria",
111 limit: 10,
112 };
113 const numbers = (state: "open" | "closed" | "merged" | "all") =>
114 provider
115 .listChangeRequests({ ...input, state })
116 .pipe(Effect.map((page) => page.items.map((item) => item.number)));
117
118 assert.deepStrictEqual(yield* numbers("merged"), [1]);
119 assert.deepStrictEqual(yield* numbers("closed"), [2]);
120 assert.deepStrictEqual(yield* numbers("all"), [1, 2]);
121 assert.deepStrictEqual(yield* numbers("open"), []);
122 }),
123);
124
125const fastForwardOnly = {
126 cwd: "/forgejo",
127 repository: "maria/project",
128 host: "forge.example:3000",
129 number: 3,
130};
131const fastForwardOnlySettings = {
132 allow_merge_commits: false,
133 allow_squash_merge: false,
134 allow_rebase: false,
135 allow_rebase_explicit: false,
136 allow_fast_forward_only_merge: true,
137 default_merge_style: "fast-forward-only",
138};
139const fastForwardOnlyProvider = (
140 writes: Array<{ path: string; body: unknown; method?: string }>,
141 mergeSettings: object = fastForwardOnlySettings,
142 timeline: ReadonlyArray<{ type: string }> = [],
143) =>
144 ForgejoPullRequestProvider.make.pipe(
145 Effect.provide(
146 Layer.mock(ForgejoCli.ForgejoCli)({
147 api: (input) => {
148 const [path, query] = input.path.split("?");
149 const reply = (value: unknown) =>
150 Effect.succeed(TestSourceControlHost.processOutput(JSON.stringify(value)));
151 if (input.method === "POST") {
152 writes.push({ path: input.path, body: input.body });
153 return reply("");
154 }
155 if (input.method === "DELETE") {
156 writes.push({ path: input.path, body: input.body, method: "DELETE" });
157 return reply("");
158 }
159 switch (path) {
160 case "user":
161 return reply({ login: "maria" });
162 case "repos/maria/project":
163 return reply({
164 full_name: "maria/project",
165 permissions: { push: true, admin: true },
166 ...mergeSettings,
167 });
168 case "repos/maria/project/pulls/3":
169 return reply({
170 number: 3,
171 title: "Fast-forward me",
172 body: "",
173 html_url: "https://forge.example:3000/maria/project/pulls/3",
174 user: { login: "maria" },
175 state: "open",
176 merged: false,
177 mergeable: true,
178 head: { ref: "feature", sha: "head-sha", repo: null },
179 base: { ref: "main", sha: "base-sha", repo: null },
180 merge_base: "base-sha",
181 created_at: "2026-10-12T00:00:00Z",
182 updated_at: "2026-10-12T00:00:00Z",
183 closed_at: null,
184 merged_at: null,
185 labels: [],
186 });
187 case "repos/maria/project/branches/main":
188 return reply({});
189 case "repos/maria/project/issues/3/timeline":
190 // Without a `link` header the provider pages until one comes back empty.
191 return reply(new URLSearchParams(query).get("page") === "1" ? timeline : []);
192 default:
193 return reply([]);
194 }
195 },
196 }),
197 ),
198 );
199
200it.effect("offers a fast-forward merge on a repository that only allows fast-forward", () =>
201 Effect.gen(function* () {
202 const provider = yield* fastForwardOnlyProvider([]);
203 const detail = yield* provider.getChangeRequest(fastForwardOnly);
204 const allowed = provider.capabilities.mergeMethods.filter(
205 (method) => detail.mergeCapabilities[method],
206 );
207 assert.deepStrictEqual(allowed, ["fast-forward"]);
208 }),
209);
210
211it.effect("does not offer fast-forward when Forgejo omits the setting", () =>
212 Effect.gen(function* () {
213 const provider = yield* fastForwardOnlyProvider([], {});
214 const detail = yield* provider.getChangeRequest(fastForwardOnly);
215 const allowed = provider.capabilities.mergeMethods.filter(
216 (method) => detail.mergeCapabilities[method],
217 );
218 assert.deepStrictEqual(allowed, ["merge", "squash", "rebase"]);
219 }),
220);
221
222it.effect("merges with Forgejo's fast-forward-only style", () =>
223 Effect.gen(function* () {
224 const writes: Array<{ path: string; body: unknown }> = [];
225 const provider = yield* fastForwardOnlyProvider(writes);
226 yield* provider.runAction({ ...fastForwardOnly, action: "merge", mergeMethod: "fast-forward" });
227 assert.deepStrictEqual(writes, [
228 {
229 path: "repos/maria/project/pulls/3/merge",
230 body: { Do: "fast-forward-only", delete_branch_after_merge: false },
231 },
232 ]);
233 }),
234);
235
236it.effect("schedules a squash merge for when checks succeed", () =>
237 Effect.gen(function* () {
238 const writes: Array<{ path: string; body: unknown }> = [];
239 const provider = yield* fastForwardOnlyProvider(writes, {});
240 yield* provider.runAction({
241 ...fastForwardOnly,
242 action: "enable-auto-merge",
243 mergeMethod: "squash",
244 });
245 assert.deepStrictEqual(writes, [
246 {
247 path: "repos/maria/project/pulls/3/merge",
248 body: { Do: "squash", delete_branch_after_merge: false, merge_when_checks_succeed: true },
249 },
250 ]);
251 }),
252);
253
254it.effect("cancels a scheduled merge", () =>
255 Effect.gen(function* () {
256 const writes: Array<{ path: string; body: unknown; method?: string }> = [];
257 const provider = yield* fastForwardOnlyProvider(writes, {});
258 yield* provider.runAction({ ...fastForwardOnly, action: "disable-auto-merge" });
259 assert.deepStrictEqual(writes, [
260 { path: "repos/maria/project/pulls/3/merge", body: undefined, method: "DELETE" },
261 ]);
262 }),
263);
264
265it.effect("reads auto-merge state from the latest timeline schedule event", () =>
266 Effect.gen(function* () {
267 const autoMerge = (timeline: ReadonlyArray<{ type: string }>) =>
268 fastForwardOnlyProvider([], {}, timeline).pipe(
269 Effect.flatMap((provider) => provider.getChangeRequest(fastForwardOnly)),
270 Effect.map((detail) => detail.autoMergeEnabled),
271 );
272 assert.strictEqual(yield* autoMerge([]), false);
273 assert.strictEqual(
274 yield* autoMerge([{ type: "comment" }, { type: "pull_scheduled_merge" }, { type: "label" }]),
275 true,
276 );
277 assert.strictEqual(
278 yield* autoMerge([{ type: "pull_scheduled_merge" }, { type: "pull_cancel_scheduled_merge" }]),
279 false,
280 );
281 }),
282);
283
284it.effect("offers auto-merge only to viewers who can merge", () =>
285 Effect.gen(function* () {
286 const provider = yield* fastForwardOnlyProvider([], {});
287 assert.includeMembers(
288 [...provider.capabilities.actions],
289 ["enable-auto-merge", "disable-auto-merge"],
290 );
291 const detail = yield* provider.getChangeRequest(fastForwardOnly);
292 assert.includeMembers(
293 [...detail.viewerPermissions.actions],
294 ["enable-auto-merge", "disable-auto-merge"],
295 );
296 // The author without push access can still close their pull request but not merge it.
297 const author = yield* fastForwardOnlyProvider([], {
298 permissions: { push: false, admin: false },
299 });
300 const authorActions = (yield* author.getChangeRequest(fastForwardOnly)).viewerPermissions
301 .actions;
302 assert.include([...authorActions], "close");
303 assert.notInclude([...authorActions], "enable-auto-merge");
304 assert.notInclude([...authorActions], "disable-auto-merge");
305 }),
306);
307
308// An empty `link` header marks the last page.
309const labelPage = (value: unknown) =>
310 Effect.succeed({
311 ...TestSourceControlHost.processOutput(JSON.stringify(value)),
312 stderr: "link: \n",
313 });
314
315it.effect("lists organization labels after repository labels, tolerating a personal owner", () =>
316 Effect.gen(function* () {
317 // A stateful pull request: org labels refuse a DELETE by id as Forgejo 17 does, and
318 // `afterRead` lands another user's edit right after the next read is answered.
319 const catalog = [
320 { id: 3, name: "bug", color: "d73a4a" },
321 { id: 4, name: "wip", color: "cccccc" },
322 { id: 101, name: "security", color: "ff0000" },
323 ];
324 let applied: Array<number> = [];
325 let afterRead: (() => void) | undefined;
326 const respond = (
327 input: ForgejoCli.ForgejoApiInput,
328 orgLabels: ReturnType<typeof labelPage> | Effect.Effect<never, ForgejoCli.ForgejoCliError>,
329 ) => {
330 const [route] = input.path.split("?");
331 const body = input.body as { labels: Array<number> } | undefined;
332 if (route === "repos/forgejo/acme/web/issues/3/labels") {
333 if (input.method === "POST")
334 applied = [...applied, ...body!.labels.filter((id) => !applied.includes(id))];
335 if (input.method === "PUT") applied = [...body!.labels];
336 return labelPage("");
337 }
338 const deleted = /^repos\/forgejo\/acme\/web\/issues\/3\/labels\/(\d+)$/.exec(route ?? "");
339 if (deleted && input.method === "DELETE") {
340 const id = Number(deleted[1]);
341 if (id === 101)
342 return Effect.fail(
343 new ForgejoCli.ForgejoCliError({
344 command: "fj",
345 cwd: "/forgejo",
346 detail: "label does not exist",
347 httpStatus: 422,
348 }),
349 );
350 applied = applied.filter((other) => other !== id);
351 return labelPage("");
352 }
353 if (route === "repos/forgejo/acme/web/labels") {
354 return labelPage(catalog.filter((label) => label.id < 100));
355 }
356 if (route === "orgs/acme/labels") return orgLabels;
357 if (route === "repos/forgejo/acme/web/pulls/3") {
358 return labelPage({
359 number: 3,
360 title: "Tighten auth",
361 body: "",
362 html_url: "https://forge.example:3000/forgejo/acme/web/pulls/3",
363 user: { login: "maria" },
364 state: "open",
365 merged: false,
366 head: { ref: "feature", sha: "head-sha", repo: null },
367 base: { ref: "main", sha: "base-sha", repo: null },
368 created_at: "2026-10-12T00:00:00Z",
369 updated_at: "2026-10-12T00:00:00Z",
370 closed_at: null,
371 merged_at: null,
372 labels: catalog.filter((label) => applied.includes(label.id)),
373 });
374 }
375 return Effect.die(`unexpected route ${route}`);
376 };
377 const make = (
378 orgLabels: ReturnType<typeof labelPage> | Effect.Effect<never, ForgejoCli.ForgejoCliError>,
379 ) =>
380 ForgejoPullRequestProvider.make.pipe(
381 Effect.provide(
382 Layer.mock(ForgejoCli.ForgejoCli)({
383 api: (input) =>
384 Effect.suspend(() => {
385 const response = respond(input, orgLabels);
386 const edit = input.method === undefined ? afterRead : undefined;
387 if (!edit) return response;
388 afterRead = undefined;
389 edit();
390 return response;
391 }),
392 }),
393 ),
394 );
395 const input = { cwd: "/forgejo", repository: "forgejo/acme/web", host: "forge.example:3000" };
396
397 const org = yield* make(
398 labelPage([
399 { id: 99, name: "bug", color: "000000" },
400 { id: 101, name: "security", color: "ff0000" },
401 ]),
402 );
403 assert.deepStrictEqual(yield* org.listRepositoryLabels!(input), {
404 items: [
405 { name: "bug", color: "d73a4a" },
406 { name: "wip", color: "cccccc" },
407 { name: "security", color: "ff0000" },
408 ],
409 truncated: false,
410 });
411 const pull = { ...input, number: 3 };
412 yield* org.setLabels!({ ...pull, labels: ["bug", "security"], applied: true });
413 assert.deepStrictEqual(applied, [3, 101]);
414 assert.deepStrictEqual(yield* org.listLabelCandidates!(pull), {
415 candidates: [
416 { name: "bug", color: "d73a4a", description: null, isApplied: true },
417 { name: "wip", color: "cccccc", description: null, isApplied: false },
418 { name: "security", color: "ff0000", description: null, isApplied: true },
419 ],
420 truncated: false,
421 });
422
423 afterRead = () => {
424 applied = [...applied, 4];
425 };
426 yield* org.setLabels!({ ...pull, labels: ["bug"], applied: false });
427 assert.deepStrictEqual(applied, [101, 4]);
428 yield* org.setLabels!({ ...pull, labels: ["security"], applied: false });
429 assert.deepStrictEqual(applied, [4]);
430
431 const personal = yield* make(
432 Effect.fail(
433 new ForgejoCli.ForgejoCliError({
434 command: "fj",
435 cwd: "/forgejo",
436 detail: "404",
437 reason: "not-found",
438 httpStatus: 404,
439 }),
440 ),
441 );
442 assert.deepStrictEqual(yield* personal.listRepositoryLabels!(input), {
443 items: [
444 { name: "bug", color: "d73a4a" },
445 { name: "wip", color: "cccccc" },
446 ],
447 truncated: false,
448 });
449 }),
450);
451
452it.effect("filters by a unique organization label id and skips an ambiguous name", () =>
453 Effect.gen(function* () {
454 const pullLabelParams: Array<string | null> = [];
455 const provider = yield* ForgejoPullRequestProvider.make.pipe(
456 Effect.provide(
457 Layer.mock(ForgejoCli.ForgejoCli)({
458 api: (input) => {
459 const [route, query] = input.path.split("?");
460 if (route === "repos/acme/web/labels") {
461 return labelPage([{ id: 2, name: "shared", color: "0000ff" }]);
462 }
463 if (route === "orgs/acme/labels") {
464 return labelPage([
465 { id: 5, name: "shared", color: "00ff00" },
466 { id: 101, name: "Needs-Review", color: "ff0000" },
467 ]);
468 }
469 if (route === "repos/acme/web/pulls") {
470 pullLabelParams.push(new URLSearchParams(query).get("labels"));
471 }
472 return labelPage([]);
473 },
474 }),
475 ),
476 );
477
478 const base = {
479 cwd: "/forgejo",
480 repository: "acme/web",
481 host: "forge.example:3000",
482 state: "open" as const,
483 involvement: "all" as const,
484 viewer: "maria",
485 limit: 10,
486 };
487 yield* provider.listChangeRequests({ ...base, filters: { labels: [["needs-review"]] } });
488 yield* provider.listChangeRequests({ ...base, filters: { labels: [["shared"]] } });
489 assert.deepStrictEqual(pullLabelParams, ["101", null]);
490 }),
491);