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

ForgejoIssueTracker.test.ts

751 lines28.1 KB

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 }
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 );
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 };
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 );
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("keeps paging issues when the server caps a page below the requested limit", () =>
546 Effect.gen(function* () {
547 const pages: Array<number> = [];
548 const api = yield* tracker((input) => {
549 const page = Number(/page=(\d+)/.exec(input.path)?.[1]);
550 pages.push(page);
551 const rows = Array.from({ length: 20 }, (_, index) => {
552 const number = (page - 1) * 20 + index + 1;
553 return {
554 ...ISSUE,
555 id: number,
556 number,
557 html_url: `https://forgejo.test:3000/acme/web/issues/${number}`,
558 };
559 });
560 return { stdout: encode(rows), stderr: "HTTP/1.1 200\nx-total-count: 60\n" };
561 });
562 const base = {
563 cwd: "/w",
564 host: "forgejo.test:3000",
565 scope: "acme/web",
566 state: "open",
567 involvement: "all",
568 viewer: "alice",
569 sort: "updated",
570 limit: 50,
571 } as const;
572 const urls: Array<string> = [];
573 let cursor: string | null | undefined;
574 do {
575 const page = yield* api.listIssues({ ...base, ...(cursor ? { cursor } : {}) });
576 urls.push(...page.items.map((item) => item.url));
577 cursor = page.nextCursor;
578 } while (cursor !== null && pages.length < 4);
579 expect(pages).toEqual([1, 2, 3]);
580 expect(cursor).toBeNull();
581 expect(new Set(urls).size).toBe(60);
582 }),
583 );
584​
585 it.effect("offers organization labels as candidates after the repository's own", () =>
586 Effect.gen(function* () {
587 const api = yield* tracker((input) => {
588 const [route] = input.path.split("?");
589 if (route === "repos/acme/web/labels") {
590 return {
591 stdout: encode([{ id: 3, name: "bug", color: "d73a4a" }]),
592 stderr: "x-total-count: 1\n",
593 };
594 }
595 if (route === "orgs/acme/labels") {
596 return {
597 stdout: encode([
598 { id: 99, name: "bug", color: "000000" },
599 { id: 101, name: "security", color: "ff0000" },
600 ]),
601 stderr: 'link: <https://forgejo.test/api/v1/orgs/acme/labels?page=2>; rel="next"\n',
602 };
603 }
604 return { stdout: "[]" };
605 });
606 const candidates = yield* api.listCandidates!({
607 cwd: "/w",
608 host: "forgejo.test",
609 scope: "acme/web",
610 });
611 expect(candidates.labels).toEqual([
612 { name: "bug", color: "d73a4a", description: null },
613 { name: "security", color: "ff0000", description: null },
614 ]);
615 expect(candidates.truncated).toBe(true);
616 const totalTruncatedApi = yield* tracker((input) => {
617 if (input.path.startsWith("repos/acme/web/labels")) {
618 return { stdout: encode([{ id: 3, name: "bug" }]), stderr: "x-total-count: 2\n" };
619 }
620 if (input.path === "repos/acme/web/assignees") {
621 return { stdout: encode([{ login: "alice" }]) };
622 }
623 return { stdout: "[]", stderr: "x-total-count: 0\n" };
624 });
625 const totalTruncated = yield* totalTruncatedApi.listCandidates!({
626 cwd: "/w",
627 host: "forgejo.test",
628 scope: "acme/web",
629 });
630 expect(totalTruncated.truncated).toBe(true);
631 expect(totalTruncated.assignees.map((user) => user.login)).toEqual(["alice"]);
632 }),
633 );
634​
635 it.effect("writes organization labels by id, preferring the repository's label of a name", () =>
636 Effect.gen(function* () {
637 const writes: Array<readonly [string, string, unknown]> = [];
638 const api = yield* tracker((input) => {
639 const [route] = input.path.split("?");
640 if (route === "repos/acme/web/labels") {
641 // Simulates a server with [api] MAX_RESPONSE_ITEMS below PAGE_SIZE (2 per page, 5 total, no Link).
642 const pages: Record<string, ReadonlyArray<{ id: number; name: string }>> = {
643 "page=1": [
644 { id: 1, name: "a" },
645 { id: 2, name: "b" },
646 ],
647 "page=2": [
648 { id: 3, name: "shared" },
649 { id: 4, name: "d" },
650 ],
651 "page=3": [{ id: 5, name: "repo-p3" }],
652 };
653 const key = /page=\d+/.exec(input.path)?.[0] ?? "";
654 return { stdout: encode(pages[key] ?? []), stderr: "x-total-count: 5\n" };
655 }
656 if (route === "orgs/acme/labels") {
657 return input.path.endsWith("page=1")
658 ? {
659 stdout: encode([{ id: 99, name: "shared" }]),
660 stderr: 'link: <https://forgejo.test/api/v1/orgs/acme/labels?page=2>; rel="next"\n',
661 }
662 : { stdout: encode([{ id: 102, name: "org-b" }]), stderr: "x-total-count: 2\n" };
663 }
664 writes.push([input.method ?? "GET", input.path, input.body]);
665 return { stdout: "{}" };
666 });
667 yield* api.update!({
668 cwd: "/w",
669 host: "forgejo.test",
670 scope: "acme/web",
671 key: "42",
672 labels: ["shared", "repo-p3", "org-b"],
673 });
674 expect(writes).toEqual([["PUT", "repos/acme/web/issues/42/labels", { labels: [3, 5, 102] }]]);
675 }),
676 );
677​
678 it.effect("reads organization labels from the owner when the scope carries a mount path", () =>
679 Effect.gen(function* () {
680 const writes: Array<readonly [string, string, unknown]> = [];
681 const api = yield* tracker((input) => {
682 const [route] = input.path.split("?");
683 if (route === "orgs/acme/labels") {
684 return { stdout: encode([{ id: 101, name: "org-only" }]) };
685 }
686 if (route === "repos/forgejo/acme/web/labels") return { stdout: "[]" };
687 writes.push([input.method ?? "GET", input.path, input.body]);
688 return { stdout: "{}" };
689 });
690 yield* api.update!({
691 cwd: "/w",
692 host: "forgejo.test",
693 scope: "forgejo/acme/web",
694 key: "42",
695 labels: ["org-only"],
696 });
697 expect(writes).toEqual([
698 ["PUT", "repos/forgejo/acme/web/issues/42/labels", { labels: [101] }],
699 ]);
700 }),
701 );
702​
703 it.effect(
704 "treats a personal owner (404) or a token without org scope (403) as no org labels",
705 () =>
706 Effect.gen(function* () {
707 for (const [reason, httpStatus] of [
708 ["not-found", 404],
709 ["forbidden", 403],
710 ] as const) {
711 const api = yield* tracker((input) => {
712 const [route] = input.path.split("?");
713 if (route === "orgs/alice/labels") {
714 return new ForgejoCli.ForgejoCliError({
715 command: "fj",
716 cwd: "/w",
717 detail: String(httpStatus),
718 reason,
719 httpStatus,
720 });
721 }
722 if (route === "repos/alice/web/labels") {
723 return { stdout: encode([{ id: 3, name: "bug" }]), stderr: "x-total-count: 1\n" };
724 }
725 if (input.path === "repos/alice/web/assignees") {
726 return { stdout: encode([{ login: "alice" }]) };
727 }
728 return { stdout: "[]" };
729 });
730 const candidates = yield* api.listCandidates!({
731 cwd: "/w",
732 host: "forgejo.test",
733 scope: "alice/web",
734 });
735 expect(candidates.labels.map((label) => label.name)).toEqual(["bug"]);
736 expect(candidates.assignees.map((user) => user.login)).toEqual(["alice"]);
737 expect(candidates.truncated).toBe(false);
738 const error = yield* Effect.flip(
739 api.update!({
740 cwd: "/w",
741 host: "forgejo.test",
742 scope: "alice/web",
743 key: "42",
744 labels: ["missing"],
745 }),
746 );
747 expect(error.detail).toBe("Forgejo found no label by one of the names given.");
748 }
749 }),
750 );
751});