Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Schema from "effect/Schema";
5import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
6
7import * as ForgejoCli from "./ForgejoCli.ts";
8import * as ForgejoIssueTracker from "./ForgejoIssueTracker.ts";
9
10const encode = (value: unknown) => JSON.stringify(value);
11const isForgejoCliError = Schema.is(ForgejoCli.ForgejoCliError);
12
13const ISSUE = {
14 number: 42,
15 title: "Composer loses focus",
16 body: "Typing drops focus.",
17 html_url: "https://forgejo.test:3000/acme/web/issues/42",
18 user: { login: "octocat", full_name: "Octo Cat", avatar_url: "" },
19 state: "open",
20 created_at: "2026-07-01T00:00:00+02:00",
21 updated_at: "2026-07-03T00:00:00Z",
22 closed_at: null,
23 assignees: [{ login: "theo" }],
24 labels: [{ id: 3, name: "bug", color: "d73a4a" }],
25 comments: 1,
26 is_locked: true,
27};
28
29/** Every endpoint the detail read touches, answered by path; stderr carries the `Link` header. */
30function answer(path: string): { readonly stdout: string; readonly stderr?: string } {
31 const [route] = path.split("?");
32 switch (route) {
33 case "user":
34 return { stdout: encode({ login: "julius" }) };
35 case "repos/acme/web":
36 return {
37 stdout: encode({ full_name: "acme/web", permissions: { push: false, admin: false } }),
38 };
39 case "repos/acme/web/issues/42":
40 return { stdout: encode(ISSUE) };
41 case "repos/acme/web/issues/42/timeline":
42 // A second page, as an issue with a long history has: a reference from another repository.
43 if (path.endsWith("page=2")) {
44 return {
45 stdout: encode([
46 {
47 id: 5,
48 type: "pull_ref",
49 user: { login: "theo" },
50 created_at: "2026-07-02T03:00:00Z",
51 ref_issue: {
52 number: 50,
53 html_url: "https://forgejo.test:3000/acme/api/pulls/50",
54 repository: { full_name: "acme/api" },
55 pull_request: { merged: true },
56 },
57 },
58 ]),
59 };
60 }
61 if (!path.endsWith("page=1")) return { stdout: "[]" };
62 return {
63 stderr: "HTTP/1.1 200\nx-total-count: 4\n",
64 stdout: encode([
65 {
66 id: 1,
67 type: "label",
68 body: "1",
69 user: { login: "theo" },
70 created_at: "2026-07-01T01:00:00Z",
71 label: { id: 3, name: "bug" },
72 },
73 {
74 id: 2,
75 type: "comment",
76 body: "Repro attached.",
77 user: { login: "julius" },
78 created_at: "2026-07-02T00:00:00Z",
79 },
80 {
81 id: 3,
82 type: "pull_ref",
83 user: { login: "theo" },
84 created_at: "2026-07-02T01:00:00Z",
85 ref_issue: {
86 number: 50,
87 html_url: "https://forgejo.test:3000/acme/web/pulls/50",
88 pull_request: { merged: false },
89 },
90 },
91 { id: 4, type: "milestone", user: { login: "theo" }, created_at: "2026-07-02T02:00:00Z" },
92 ]),
93 };
94 case "repos/acme/web/issues/42/reactions":
95 return { stdout: encode([{ content: "eyes", user: { login: "theo" } }]) };
96 case "repos/acme/web/issues/42/comments":
97 return {
98 stdout: encode([
99 {
100 id: 7,
101 body: "Repro attached.",
102 user: { login: "julius" },
103 created_at: "2026-07-02T00:00:00Z",
104 html_url: "https://forgejo.test:3000/acme/web/issues/42#issuecomment-7",
105 },
106 ]),
107 };
108 case "repos/acme/web/issues/comments/7/reactions":
109 return {
110 stdout: encode([
111 { content: "+1", user: { login: "julius" } },
112 { content: "+1", user: { login: "theo" } },
113 ]),
114 };
115 case "repos/acme/api/pulls/50":
116 return {
117 stdout: encode({
118 number: 50,
119 title: "fix(api): accept the pasted payload",
120 html_url: "https://forgejo.test:3000/acme/api/pulls/50",
121 state: "closed",
122 merged: true,
123 }),
124 };
125 case "repos/acme/web/pulls/50":
126 return {
127 stdout: encode({
128 number: 50,
129 title: "fix(web): keep composer focus",
130 html_url: "https://forgejo.test:3000/acme/web/pulls/50",
131 state: "open",
132 merged: false,
133 draft: true,
134 }),
135 };
136 default:
137 throw new Error(`unexpected path ${path}`);
138 }
139}
140
141function tracker(
142 onApi: (input: ForgejoCli.ForgejoApiInput) =>
143 | {
144 readonly stdout: string;
145 readonly stderr?: string;
146 }
147 | ForgejoCli.ForgejoCliError,
148) {
149 return ForgejoIssueTracker.make.pipe(
150 Effect.provide(
151 Layer.mock(ForgejoCli.ForgejoCli)({
152 api: (input) => {
153 const result = onApi(input);
154 return isForgejoCliError(result)
155 ? Effect.fail(result)
156 : Effect.succeed(
157 TestSourceControlHost.processOutput(result.stdout, {
158 stderr: result.stderr ?? "",
159 }),
160 );
161 },
162 }),
163 ),
164 );
165}
166
167/** A comment as `/comments` answers it; ids are minutes apart unless a time is given. */
168function forgejoComment(id: number, minutes = (id - 1) * 7) {
169 const pad = (value: number) => String(value).padStart(2, "0");
170 return {
171 id,
172 body: `Comment ${id}`,
173 user: { login: id % 2 === 0 ? "julius" : "theo" },
174 created_at: `2026-07-02T${pad(Math.floor(minutes / 60))}:${pad(minutes % 60)}:00Z`,
175 html_url: `https://forgejo.test:3000/acme/web/issues/42#issuecomment-${id}`,
176 };
177}
178
179/** Forgejo and Gitea answer `/comments` with every comment, oldest first. */
180const forgejoComments = (count: number) =>
181 Array.from({ length: count }, (_, index) => forgejoComment(index + 1));
182
183const ids = (comments: ReadonlyArray<{ readonly id: string }>) =>
184 comments.map((comment) => comment.id);
185
186const range = (from: number, to: number) =>
187 Array.from({ length: to - from + 1 }, (_, index) => String(from + index));
188
189const TARGET = { cwd: "/w", host: "forgejo.test:3000", scope: "acme/web", key: "42" };
190
191/**
192 * An open, unlocked issue the viewer can push to. Its comments are read from `rows` on every
193 * request, so a test can change them between reads.
194 */
195function forge(rows: Array<ReturnType<typeof forgejoComment>>) {
196 const reactionIds: string[] = [];
197 let reads = 0;
198 return tracker((input) => {
199 const [route = ""] = input.path.split("?");
200 if (route === "repos/acme/web") {
201 return {
202 stdout: encode({ full_name: "acme/web", permissions: { push: true, admin: false } }),
203 };
204 }
205 if (route === "repos/acme/web/issues/42") {
206 return { stdout: encode({ ...ISSUE, comments: rows.length, is_locked: false }) };
207 }
208 if (route === "repos/acme/web/issues/42/comments") {
209 if (input.method === "POST") {
210 const comment = forgejoComment(rows.length + 1);
211 rows.push(comment);
212 return { stdout: encode(comment) };
213 }
214 reads += 1;
215 return { stdout: encode(rows) };
216 }
217 const reaction = /^repos\/acme\/web\/issues\/comments\/(\d+)\/reactions$/.exec(route);
218 if (reaction?.[1] !== undefined) {
219 reactionIds.push(reaction[1]);
220 return { stdout: "[]" };
221 }
222 return answer(input.path);
223 }).pipe(
224 Effect.map((api) => ({
225 api,
226 /** The comments whose reactions were read since the last call, in id order. */
227 takeReactionIds: () =>
228 reactionIds.splice(0).sort((left, right) => Number(left) - Number(right)),
229 commentReads: () => reads,
230 })),
231 );
232}
233
234describe("ForgejoIssueTracker", () => {
235 it.effect("joins the issue, timeline and conversation into the neutral issue shape", () =>
236 Effect.gen(function* () {
237 const hosts = new Set<string | undefined>();
238 const api = yield* tracker((input) => {
239 hosts.add(input.host);
240 return answer(input.path);
241 });
242 const issue = yield* api.getIssue({
243 cwd: "/w",
244 host: "forgejo.test:3000",
245 scope: "acme/web",
246 key: "42",
247 });
248 // The custom host and port reach the CLI, which resolves the login for them.
249 expect([...hosts]).toEqual(["forgejo.test:3000"]);
250 expect(issue).toMatchObject({
251 key: "42",
252 displayKey: "#42",
253 state: { category: "open", name: "Open" },
254 states: [
255 { category: "open", name: "Open" },
256 { category: "closed", name: "Closed" },
257 ],
258 author: { login: "octocat", name: "Octo Cat", avatarUrl: null },
259 createdAt: "2026-06-30T22:00:00.000Z",
260 labels: [{ name: "bug", color: "d73a4a" }],
261 viewer: "julius",
262 // No push and not the author: nothing but reading. Locked, so not even a comment.
263 viewerPermissions: {
264 setState: false,
265 comment: false,
266 edit: false,
267 labels: false,
268 assignees: false,
269 },
270 reactions: [{ content: "eyes", count: 1, actors: ["theo"], viewerHasReacted: false }],
271 // `/comments` answered with everything it has, so nothing is left to page.
272 commentsCursor: null,
273 });
274 expect(issue.comments).toEqual([
275 {
276 id: "7",
277 author: { login: "julius", name: null, avatarUrl: null },
278 body: "Repro attached.",
279 createdAt: "2026-07-02T00:00:00.000Z",
280 url: "https://forgejo.test:3000/acme/web/issues/42#issuecomment-7",
281 reactions: [{ content: "thumbs-up", count: 2, actors: ["theo"], viewerHasReacted: true }],
282 },
283 ]);
284 // Comments and milestones on the timeline are not events in the shared vocabulary.
285 expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([
286 ["labeled", "bug"],
287 ["referenced", "#50"],
288 ["referenced", "#50"],
289 ]);
290 // The same number in another repository is its own pull request, read from there.
291 expect(issue.linkedPullRequests).toEqual([
292 {
293 repository: "acme/web",
294 number: 50,
295 title: "fix(web): keep composer focus",
296 url: "https://forgejo.test:3000/acme/web/pulls/50",
297 state: "open",
298 isDraft: true,
299 closesIssue: false,
300 },
301 {
302 repository: "acme/api",
303 number: 50,
304 title: "fix(api): accept the pasted payload",
305 url: "https://forgejo.test:3000/acme/api/pulls/50",
306 state: "merged",
307 isDraft: false,
308 closesIssue: false,
309 },
310 ]);
311 }),
312 );
313
314 it.effect("cuts the unpaged comments into pages and resolves labels past the first page", () =>
315 Effect.gen(function* () {
316 const calls: Array<readonly [string, string, unknown]> = [];
317 const api = yield* tracker((input) => {
318 calls.push([input.method ?? "GET", input.path, input.body]);
319 const [route] = input.path.split("?");
320 if (route === "user") return { stdout: encode({ login: "julius" }) };
321 if (route === "repos/acme/web/issues/42/comments") {
322 return { stdout: encode(forgejoComments(51)) };
323 }
324 if (route === "repos/acme/web/labels") {
325 return input.path.endsWith("page=1")
326 ? {
327 stdout: encode([{ id: 3, name: "bug" }]),
328 stderr: 'link: <https://forgejo.test:3000/api/v1/x?page=2>; rel="next"\n',
329 }
330 : { stdout: encode([{ id: 9, name: "urgent" }]), stderr: "link: \n" };
331 }
332 return { stdout: "[]" };
333 });
334 const target = { cwd: "/w", host: "forgejo.test:3000", scope: "acme/web", key: "42" };
335 // The cursor names comment 2, created at 00:07.
336 const page = yield* api.getComments({ ...target, cursor: "1782950820000.2" });
337 expect(page.comments.map((comment) => comment.id)).toEqual(["1"]);
338 expect(page.nextCursor).toBeNull();
339 expect(calls[1]?.[1]).toBe("repos/acme/web/issues/42/comments");
340
341 calls.length = 0;
342 yield* api.update!({ ...target, labels: ["bug", "urgent"] });
343 expect(calls.at(-1)).toEqual(["PUT", "repos/acme/web/issues/42/labels", { labels: [3, 9] }]);
344 expect(calls.some(([, path]) => path.startsWith("orgs/"))).toBe(false);
345 // A name neither the repository nor its org owns refuses the save before anything is written.
346 calls.length = 0;
347 const error = yield* Effect.flip(
348 api.update!({ ...target, title: "Renamed", labels: ["bug", "missing"] }),
349 );
350 expect(error.reason).toBe("failed");
351 expect(calls.map(([method]) => method)).toEqual(["GET", "GET", "GET"]);
352 }),
353 );
354
355 it.effect("opens on the newest comments and walks older pages back to the first", () =>
356 Effect.gen(function* () {
357 for (const [count, sizes] of [
358 [0, [0]],
359 [1, [1]],
360 [50, [50]],
361 [51, [1, 50]],
362 [120, [20, 50, 50]],
363 ] as const) {
364 const { api, takeReactionIds } = yield* forge(forgejoComments(count));
365 const issue = yield* api.getIssue(TARGET);
366 // Each page reads reactions for exactly the comments on that page.
367 expect(takeReactionIds()).toEqual(ids(issue.comments));
368 // Older pages go in front, as the client pager prepends them.
369 const pages = [ids(issue.comments)];
370 let cursor = issue.commentsCursor;
371 while (cursor !== null) {
372 const page = yield* api.getComments({ ...TARGET, cursor });
373 expect(takeReactionIds()).toEqual(ids(page.comments));
374 pages.unshift(ids(page.comments));
375 cursor = page.nextCursor;
376 }
377 expect(pages.map((page) => page.length)).toEqual(sizes);
378 expect(pages.flat()).toEqual(range(1, count));
379 }
380 }),
381 );
382
383 it.effect("shows a new reply on the first page while older comments stay behind the cursor", () =>
384 Effect.gen(function* () {
385 const { api } = yield* forge(forgejoComments(51));
386 const before = yield* api.getIssue(TARGET);
387 expect(before.viewerPermissions.comment).toBe(true);
388 expect(ids(before.comments)).toEqual(range(2, 51));
389
390 yield* api.comment!({ ...TARGET, body: "Comment 52" });
391 const after = yield* api.getIssue(TARGET);
392 expect(ids(after.comments)).toEqual(range(3, 52));
393 const older = yield* api.getComments({ ...TARGET, cursor: after.commentsCursor! });
394 expect(ids(older.comments)).toEqual(["1", "2"]);
395 expect(older.nextCursor).toBeNull();
396 }),
397 );
398
399 it.effect("continues before the oldest comment shown when comments change between reads", () =>
400 Effect.gen(function* () {
401 const changes: ReadonlyArray<
402 readonly [(rows: Array<ReturnType<typeof forgejoComment>>) => unknown, string[]]
403 > = [
404 // The newest comment, then the oldest one shown, is deleted.
405 [(rows) => rows.splice(50, 1), ["1"]],
406 [(rows) => rows.splice(1, 1), ["1"]],
407 // The only comment not yet shown is deleted.
408 [(rows) => rows.splice(0, 1), []],
409 // Someone else replies.
410 [(rows) => rows.push(forgejoComment(52)), ["1"]],
411 ];
412 for (const [change, expected] of changes) {
413 const rows = forgejoComments(51);
414 const { api } = yield* forge(rows);
415 const issue = yield* api.getIssue(TARGET);
416 expect(ids(issue.comments)).toEqual(range(2, 51));
417 change(rows);
418 const older = yield* api.getComments({ ...TARGET, cursor: issue.commentsCursor! });
419 expect(ids(older.comments)).toEqual(expected);
420 expect(older.nextCursor).toBeNull();
421 }
422 }),
423 );
424
425 it.effect("orders comments created in the same second by id across a page boundary", () =>
426 Effect.gen(function* () {
427 // Forgejo stores seconds, so neighbours can share a time; it orders them by id.
428 const rows = [forgejoComment(1, 0), forgejoComment(2, 0), ...forgejoComments(51).slice(2)];
429 const { api } = yield* forge(rows);
430 const issue = yield* api.getIssue(TARGET);
431 expect(ids(issue.comments)).toEqual(range(2, 51));
432 rows.splice(1, 1);
433 const older = yield* api.getComments({ ...TARGET, cursor: issue.commentsCursor! });
434 expect(ids(older.comments)).toEqual(["1"]);
435 }),
436 );
437
438 it.effect("refuses malformed comments cursors", () =>
439 Effect.gen(function* () {
440 const { api, commentReads } = yield* forge(forgejoComments(51));
441 // "2" is the page-number cursor a client may still hold from before.
442 for (const cursor of ["2", "abc", "1782950820000", "1782950820000.0"]) {
443 const error = yield* Effect.flip(api.getComments({ ...TARGET, cursor }));
444 expect(error.reason).toBe("failed");
445 }
446 expect(commentReads()).toBe(0);
447 }),
448 );
449
450 it.effect("moves an issue to a state by its name and refuses any other name", () =>
451 Effect.gen(function* () {
452 const writes: unknown[] = [];
453 const api = yield* tracker((input) => {
454 writes.push([input.method, input.path, input.body]);
455 return { stdout: "{}" };
456 });
457 const target = { cwd: "/w", host: "forgejo.test:3000", scope: "acme/web", key: "42" };
458 yield* api.setState!({ ...target, state: "Closed" });
459 yield* api.setState!({ ...target, state: "Open" });
460 // The category is not a state name: nothing is sent for it.
461 const error = yield* Effect.flip(api.setState!({ ...target, state: "closed" }));
462 expect(error).toMatchObject({ operation: "setState", reason: "failed" });
463 expect(writes).toEqual([
464 ["PATCH", "repos/acme/web/issues/42", { state: "closed" }],
465 ["PATCH", "repos/acme/web/issues/42", { state: "open" }],
466 ]);
467 }),
468 );
469
470 it.effect("lists issues by page and leaves pull requests out of the rows", () =>
471 Effect.gen(function* () {
472 const paths: string[] = [];
473 const api = yield* tracker((input) => {
474 paths.push(input.path);
475 return {
476 stdout: encode([ISSUE, { ...ISSUE, number: 43, pull_request: { merged: false } }]),
477 };
478 });
479 const page = yield* api.listIssues({
480 cwd: "/w",
481 host: "forgejo.test:3000",
482 scope: "acme/web",
483 state: "open",
484 involvement: "authored",
485 viewer: "julius",
486 sort: "updated",
487 limit: 50,
488 cursor: "2",
489 });
490 // Forgejo matches any of the labels it is sent, so a row missing one is dropped here.
491 const filtered = yield* api.listIssues({
492 cwd: "/w",
493 host: "forgejo.test:3000",
494 scope: "acme/web",
495 state: "open",
496 involvement: "all",
497 labels: ["bug", "p1"],
498 assignee: "theo",
499 sort: "created",
500 limit: 50,
501 });
502 expect(filtered.items).toEqual([]);
503 // One `assigned_by` cannot name two people: "assigned to me" is kept by dropping rows here.
504 const mine = {
505 cwd: "/w",
506 host: "forgejo.test:3000",
507 scope: "acme/web",
508 state: "open",
509 involvement: "assigned",
510 assignee: "theo",
511 sort: "created",
512 limit: 50,
513 } as const;
514 expect((yield* api.listIssues({ ...mine, viewer: "julius" })).items).toEqual([]);
515 expect(
516 (yield* api.listIssues({ ...mine, viewer: "Theo" })).items.map((item) => item.key),
517 ).toEqual(["42"]);
518 expect(paths).toEqual([
519 "repos/acme/web/issues?type=issues&state=open&sort=recentupdate&created_by=julius&limit=50&page=2",
520 "repos/acme/web/issues?type=issues&state=open&sort=latest&labels=bug%2Cp1&assigned_by=theo&limit=50&page=1",
521 "repos/acme/web/issues?type=issues&state=open&sort=latest&assigned_by=theo&limit=50&page=1",
522 "repos/acme/web/issues?type=issues&state=open&sort=latest&assigned_by=theo&limit=50&page=1",
523 ]);
524 expect(page.items.map((item) => item.key)).toEqual(["42"]);
525 expect(page.nextCursor).toBeNull();
526 const pagedApi = yield* tracker((input) => ({
527 stdout: encode([ISSUE]),
528 stderr: input.path.includes("page=2")
529 ? 'HTTP/1.1 200\nlink: <https://forgejo.test/api/v1/repos/acme/web/issues?page=1>; rel="prev", <https://forgejo.test/api/v1/repos/acme/web/issues?page=1>; rel="first"\nx-total-count: 51\n'
530 : 'HTTP/1.1 200\nlink: <https://forgejo.test/api/v1/repos/acme/web/issues?page=2>; rel="next"\nx-total-count: 51\n',
531 }));
532 const pagedBase = { ...mine, involvement: "all", viewer: "alice", sort: "updated" } as const;
533 expect((yield* pagedApi.listIssues(pagedBase)).nextCursor).toBe("2:1");
534 expect((yield* pagedApi.listIssues({ ...pagedBase, cursor: "2" })).nextCursor).toBeNull();
535 const shortLastPage = yield* tracker(() => ({
536 stdout: encode([ISSUE, { ...ISSUE, id: 2, number: 43 }]),
537 stderr: "HTTP/1.1 200\nx-total-count: 52\n",
538 }));
539 expect(
540 (yield* shortLastPage.listIssues({ ...pagedBase, cursor: "2" })).nextCursor,
541 ).toBeNull();
542 }),
543 );
544
545 it.effect("does not call a repository with an external issue tracker missing", () =>
546 Effect.gen(function* () {
547 // Forgejo answers the issue listing with 404 while the repository itself answers 200.
548 const api = yield* tracker((input) => {
549 const [route] = input.path.split("?");
550 if (route === "repos/acme/web") {
551 return {
552 stdout: encode({
553 full_name: "acme/web",
554 has_issues: true,
555 external_tracker: {
556 external_tracker_url: "https://linear.app/acme",
557 external_tracker_format: "https://linear.app/acme/issue/{index}",
558 external_tracker_style: "alphanumeric",
559 },
560 }),
561 };
562 }
563 return new ForgejoCli.ForgejoCliError({
564 command: "fj",
565 cwd: "/w",
566 reason: "not-found",
567 httpStatus: 404,
568 detail: "Forgejo repository or pull request was not found.",
569 });
570 });
571 const result = yield* Effect.result(
572 api.listIssues({
573 cwd: "/w",
574 host: "forgejo.test:3000",
575 scope: "acme/web",
576 state: "open",
577 involvement: "all",
578 sort: "updated",
579 limit: 50,
580 }),
581 );
582 if (result._tag === "Failure") {
583 expect(result.failure.detail).not.toBe("Forgejo repository or pull request was not found.");
584 expect(result.failure.reason).not.toBe("not-found");
585 } else {
586 expect(result.success.items).toEqual([]);
587 }
588 }),
589 );
590
591 it.effect("keeps paging issues when the server caps a page below the requested limit", () =>
592 Effect.gen(function* () {
593 const pages: Array<number> = [];
594 const api = yield* tracker((input) => {
595 const page = Number(/page=(\d+)/.exec(input.path)?.[1]);
596 pages.push(page);
597 const rows = Array.from({ length: 20 }, (_, index) => {
598 const number = (page - 1) * 20 + index + 1;
599 return {
600 ...ISSUE,
601 id: number,
602 number,
603 html_url: `https://forgejo.test:3000/acme/web/issues/${number}`,
604 };
605 });
606 return { stdout: encode(rows), stderr: "HTTP/1.1 200\nx-total-count: 60\n" };
607 });
608 const base = {
609 cwd: "/w",
610 host: "forgejo.test:3000",
611 scope: "acme/web",
612 state: "open",
613 involvement: "all",
614 viewer: "alice",
615 sort: "updated",
616 limit: 50,
617 } as const;
618 const urls: Array<string> = [];
619 let cursor: string | null | undefined;
620 do {
621 const page = yield* api.listIssues({ ...base, ...(cursor ? { cursor } : {}) });
622 urls.push(...page.items.map((item) => item.url));
623 cursor = page.nextCursor;
624 } while (cursor !== null && pages.length < 4);
625 expect(pages).toEqual([1, 2, 3]);
626 expect(cursor).toBeNull();
627 expect(new Set(urls).size).toBe(60);
628 }),
629 );
630
631 it.effect("offers organization labels as candidates after the repository's own", () =>
632 Effect.gen(function* () {
633 const api = yield* tracker((input) => {
634 const [route] = input.path.split("?");
635 if (route === "repos/acme/web/labels") {
636 return {
637 stdout: encode([{ id: 3, name: "bug", color: "d73a4a" }]),
638 stderr: "x-total-count: 1\n",
639 };
640 }
641 if (route === "orgs/acme/labels") {
642 return {
643 stdout: encode([
644 { id: 99, name: "bug", color: "000000" },
645 { id: 101, name: "security", color: "ff0000" },
646 ]),
647 stderr: 'link: <https://forgejo.test/api/v1/orgs/acme/labels?page=2>; rel="next"\n',
648 };
649 }
650 return { stdout: "[]" };
651 });
652 const candidates = yield* api.listCandidates!({
653 cwd: "/w",
654 host: "forgejo.test",
655 scope: "acme/web",
656 });
657 expect(candidates.labels).toEqual([
658 { name: "bug", color: "d73a4a", description: null },
659 { name: "security", color: "ff0000", description: null },
660 ]);
661 expect(candidates.truncated).toBe(true);
662 const totalTruncatedApi = yield* tracker((input) => {
663 if (input.path.startsWith("repos/acme/web/labels")) {
664 return { stdout: encode([{ id: 3, name: "bug" }]), stderr: "x-total-count: 2\n" };
665 }
666 if (input.path === "repos/acme/web/assignees") {
667 return { stdout: encode([{ login: "alice" }]) };
668 }
669 return { stdout: "[]", stderr: "x-total-count: 0\n" };
670 });
671 const totalTruncated = yield* totalTruncatedApi.listCandidates!({
672 cwd: "/w",
673 host: "forgejo.test",
674 scope: "acme/web",
675 });
676 expect(totalTruncated.truncated).toBe(true);
677 expect(totalTruncated.assignees.map((user) => user.login)).toEqual(["alice"]);
678 }),
679 );
680
681 it.effect("writes organization labels by id, preferring the repository's label of a name", () =>
682 Effect.gen(function* () {
683 const writes: Array<readonly [string, string, unknown]> = [];
684 const api = yield* tracker((input) => {
685 const [route] = input.path.split("?");
686 if (route === "repos/acme/web/labels") {
687 // Simulates a server with [api] MAX_RESPONSE_ITEMS below PAGE_SIZE (2 per page, 5 total, no Link).
688 const pages: Record<string, ReadonlyArray<{ id: number; name: string }>> = {
689 "page=1": [
690 { id: 1, name: "a" },
691 { id: 2, name: "b" },
692 ],
693 "page=2": [
694 { id: 3, name: "shared" },
695 { id: 4, name: "d" },
696 ],
697 "page=3": [{ id: 5, name: "repo-p3" }],
698 };
699 const key = /page=\d+/.exec(input.path)?.[0] ?? "";
700 return { stdout: encode(pages[key] ?? []), stderr: "x-total-count: 5\n" };
701 }
702 if (route === "orgs/acme/labels") {
703 return input.path.endsWith("page=1")
704 ? {
705 stdout: encode([{ id: 99, name: "shared" }]),
706 stderr: 'link: <https://forgejo.test/api/v1/orgs/acme/labels?page=2>; rel="next"\n',
707 }
708 : { stdout: encode([{ id: 102, name: "org-b" }]), stderr: "x-total-count: 2\n" };
709 }
710 writes.push([input.method ?? "GET", input.path, input.body]);
711 return { stdout: "{}" };
712 });
713 yield* api.update!({
714 cwd: "/w",
715 host: "forgejo.test",
716 scope: "acme/web",
717 key: "42",
718 labels: ["shared", "repo-p3", "org-b"],
719 });
720 expect(writes).toEqual([["PUT", "repos/acme/web/issues/42/labels", { labels: [3, 5, 102] }]]);
721 }),
722 );
723
724 it.effect("reads organization labels from the owner when the scope carries a mount path", () =>
725 Effect.gen(function* () {
726 const writes: Array<readonly [string, string, unknown]> = [];
727 const api = yield* tracker((input) => {
728 const [route] = input.path.split("?");
729 if (route === "orgs/acme/labels") {
730 return { stdout: encode([{ id: 101, name: "org-only" }]) };
731 }
732 if (route === "repos/forgejo/acme/web/labels") return { stdout: "[]" };
733 writes.push([input.method ?? "GET", input.path, input.body]);
734 return { stdout: "{}" };
735 });
736 yield* api.update!({
737 cwd: "/w",
738 host: "forgejo.test",
739 scope: "forgejo/acme/web",
740 key: "42",
741 labels: ["org-only"],
742 });
743 expect(writes).toEqual([
744 ["PUT", "repos/forgejo/acme/web/issues/42/labels", { labels: [101] }],
745 ]);
746 }),
747 );
748
749 it.effect(
750 "treats a personal owner (404) or a token without org scope (403) as no org labels",
751 () =>
752 Effect.gen(function* () {
753 for (const [reason, httpStatus] of [
754 ["not-found", 404],
755 ["forbidden", 403],
756 ] as const) {
757 const api = yield* tracker((input) => {
758 const [route] = input.path.split("?");
759 if (route === "orgs/alice/labels") {
760 return new ForgejoCli.ForgejoCliError({
761 command: "fj",
762 cwd: "/w",
763 detail: String(httpStatus),
764 reason,
765 httpStatus,
766 });
767 }
768 if (route === "repos/alice/web/labels") {
769 return { stdout: encode([{ id: 3, name: "bug" }]), stderr: "x-total-count: 1\n" };
770 }
771 if (input.path === "repos/alice/web/assignees") {
772 return { stdout: encode([{ login: "alice" }]) };
773 }
774 return { stdout: "[]" };
775 });
776 const candidates = yield* api.listCandidates!({
777 cwd: "/w",
778 host: "forgejo.test",
779 scope: "alice/web",
780 });
781 expect(candidates.labels.map((label) => label.name)).toEqual(["bug"]);
782 expect(candidates.assignees.map((user) => user.login)).toEqual(["alice"]);
783 expect(candidates.truncated).toBe(false);
784 const error = yield* Effect.flip(
785 api.update!({
786 cwd: "/w",
787 host: "forgejo.test",
788 scope: "alice/web",
789 key: "42",
790 labels: ["missing"],
791 }),
792 );
793 expect(error.detail).toBe("Forgejo found no label by one of the names given.");
794 }
795 }),
796 );
797});