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

ForgejoPullRequestProvider.ts

748 lines29.3 KB

1import { resolvePullRequestAuthorFilter, SourceControlProviderKind } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Schema from "effect/Schema";
4import * as Result from "effect/Result";
5import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
6import { decodeJsonResult } from "@t3tools/shared/schemaJson";
7import * as ForgejoCli from "./ForgejoCli.ts";
8import { parseDiffFileRevisions } from "@t3tools/source-control-core/server/diffFileRevisions";
9import {
10 PullRequestProviderError,
11 type ProviderChangeRequestDetail,
12 type ProviderRepositoryRef,
13 type PullRequestProviderApi,
14} from "@t3tools/source-control-core/server/PullRequestProvider";
15import {
16 ForgejoPullRequest,
17 ForgejoRepository,
18 ForgejoUser,
19 ForgejoComment,
20 ForgejoReview,
21 ForgejoReviewComment,
22 ForgejoCommit,
23 ForgejoStatus,
24 ForgejoLabel,
25 ForgejoReaction,
26 FORGEJO_REACTIONS,
27 forgejoChangeRequest,
28 forgejoActor,
29 forgejoComment,
30 forgejoReview,
31 forgejoReviewThread,
32 forgejoCommit,
33 forgejoChecks,
34 forgejoReactions,
35} from "./forgejoPullRequestJson.ts";
36import { ForgejoBranchStatusChecks, markRequiredForgejoChecks } from "./forgejoRequiredChecks.ts";
37import { definition } from "../shared/definition.ts";
38​
39const isForgejoCliError = Schema.is(ForgejoCli.ForgejoCliError);
40​
41const CAPABILITIES: PullRequestCapabilities = {
42 diff: true,
43 viewedFiles: "environment",
44 comment: true,
45 actions: [...definition.changeRequestActions],
46 mergeMethods: ["merge", "squash", "rebase"],
47 updateMethods: ["merge", "rebase"],
48 search: false,
49 reactions: true,
50 labels: true,
51 // Forgejo's public API has no thread replies/resolution or draft conversion endpoint.
52 review: {
53 inlineComment: true,
54 reply: false,
55 resolve: false,
56 verdicts: ["comment", "approve", "request-changes"],
57 },
58 reviewers: { request: true, listCandidates: true },
59 edit: { changeRequest: true, comment: true },
60};
61const USER_SEARCH_LIMIT = 50;
62const ForgejoUserSearch = Schema.Struct({
63 data: Schema.optional(Schema.NullOr(Schema.Array(ForgejoUser))),
64});
65​
66const UNAVAILABLE_REQUIREMENT = {
67 missing:
68 "Install Forgejo CLI (`fj` 0.6 or later) from https://codeberg.org/forgejo-contrib/forgejo-cli or Gitea CLI (`tea` 0.16 or later) from https://gitea.com/gitea/tea to browse Forgejo pull requests.",
69 unauthenticated:
70 "Authenticate your Forgejo or Gitea server with `fj --host <server-url> auth add-token` on the T3 Code server. If fj is missing or unconfigured for that server, use `tea login add`. A configured fj account must be repaired with fj.",
71};
72​
73const repoPath = (input: ProviderRepositoryRef) =>
74 `repos/${input.repository.split("/").map(encodeURIComponent).join("/")}`;
75const pullPath = (input: ProviderRepositoryRef & { readonly number: number }) =>
76 `${repoPath(input)}/pulls/${input.number}`;
77const issuePath = (input: ProviderRepositoryRef & { readonly number: number }) =>
78 `${repoPath(input)}/issues/${input.number}`;
79// Review IDs differ from the issue-comment IDs used by Forgejo's reactions API.
80const reviewCommentId = (review: typeof ForgejoReview.Type) =>
81 /#issuecomment-([1-9]\d*)$/.exec(review.html_url ?? "")?.[1];
82​
83export const make = Effect.gen(function* () {
84 const cli = yield* ForgejoCli.ForgejoCli;
85 const failure = (operation: string, detail: string, cause?: unknown) =>
86 new PullRequestProviderError({
87 provider: SourceControlProviderKind.make("forgejo"),
88 operation,
89 reason: "failed",
90 detail,
91 ...(cause === undefined ? {} : { cause }),
92 });
93 const request = (input: ForgejoCli.ForgejoApiInput) =>
94 cli.api(input).pipe(
95 Effect.mapError(
96 (error) =>
97 new PullRequestProviderError({
98 provider: SourceControlProviderKind.make("forgejo"),
99 operation: input.path,
100 detail: error.detail,
101 cause: error,
102 reason:
103 error.reason === "missing-cli"
104 ? "missing-tool"
105 : error.reason === "authentication"
106 ? "unauthenticated"
107 : error.reason === "rate-limit"
108 ? "rate-limited"
109 : error.reason === "not-found"
110 ? "not-found"
111 : "failed",
112 }),
113 ),
114 );
115 /** A response, and whether its `link` header points at a further page. */
116 const readLinked = Effect.fn("ForgejoPullRequestProvider.readLinked")(function* <A>(
117 input: ForgejoCli.ForgejoApiInput,
118 schema: Schema.Codec<A, unknown, never, never>,
119 ) {
120 const result = yield* request(input);
121 if (result.stdoutTruncated)
122 return yield* failure(input.path, "Forgejo response exceeded the output limit.");
123 const decoded = decodeJsonResult(schema)(result.stdout);
124 if (Result.isFailure(decoded))
125 return yield* failure(input.path, "Forgejo returned an invalid response.", decoded.failure);
126 const links = /^link:\s*(.*)$/im.exec(result.stderr)?.[1];
127 return { value: decoded.success, next: links !== undefined && /rel="?next"?/i.test(links) };
128 });
129 const read = <A>(
130 input: ForgejoCli.ForgejoApiInput,
131 schema: Schema.Codec<A, unknown, never, never>,
132 ) => readLinked(input, schema).pipe(Effect.map(({ value }) => value));
133 const readArray = <A>(
134 input: ForgejoCli.ForgejoApiInput,
135 schema: Schema.Codec<A, unknown, never, never>,
136 ) => read(input, Schema.NullOr(Schema.Array(schema))).pipe(Effect.map((rows) => rows ?? []));
137 const readPage = Effect.fn("ForgejoPullRequestProvider.readPage")(function* <A>(
138 input: ForgejoCli.ForgejoApiInput,
139 schema: Schema.Codec<A, unknown, never, never>,
140 index: number,
141 ) {
142 const result = yield* request({
143 ...input,
144 path: `${input.path}${input.path.includes("?") ? "&" : "?"}limit=50&page=${index}`,
145 });
146 if (result.stdoutTruncated)
147 return yield* failure(input.path, "Forgejo response exceeded the output limit.");
148 const decoded = decodeJsonResult(Schema.NullOr(Schema.Array(schema)))(result.stdout);
149 if (Result.isFailure(decoded))
150 return yield* failure(input.path, "Forgejo returned an invalid response.", decoded.failure);
151 const rows = decoded.success ?? [];
152 const links = /^link:\s*(.*)$/im.exec(result.stderr)?.[1];
153 return {
154 rows,
155 more: rows.length > 0 && (links === undefined || /rel="?next"?/i.test(links)),
156 };
157 });
158 // Forgejo's default page limit is 50.
159 const page = Effect.fn("ForgejoPullRequestProvider.page")(function* <A>(
160 input: ForgejoCli.ForgejoApiInput,
161 schema: Schema.Codec<A, unknown, never, never>,
162 limit = 500,
163 ) {
164 const items: A[] = [];
165 for (let index = 1; items.length < limit; index++) {
166 const { rows, more } = yield* readPage(input, schema, index);
167 items.push(...rows);
168 if (!more) return { items, truncated: false };
169 }
170 return { items, truncated: true };
171 });
172 const write = (input: ForgejoCli.ForgejoApiInput) => request(input).pipe(Effect.asVoid);
173 const getPull = (input: ProviderRepositoryRef & { readonly number: number }) =>
174 read(
175 {
176 cwd: input.cwd,
177 repository: input.repository,
178 host: input.host,
179 path: pullPath(input),
180 },
181 ForgejoPullRequest,
182 );
183 const getRepo = (input: ProviderRepositoryRef) =>
184 read({ ...input, path: repoPath(input) }, ForgejoRepository);
185 const getViewer = (input: {
186 readonly cwd: string;
187 readonly repository?: string;
188 readonly host?: string;
189 }) => read({ ...input, path: "user" }, ForgejoUser).pipe(Effect.map((user) => user.login));
190 const permissions = (
191 repo: typeof ForgejoRepository.Type,
192 pr: typeof ForgejoPullRequest.Type,
193 viewer: string,
194 ): PullRequestViewerPermissions => {
195 const canWrite = repo.permissions?.push ?? false;
196 const canEdit = canWrite || pr.user?.login === viewer;
197 const active = !repo.archived;
198 return {
199 actions: active
200 ? CAPABILITIES.actions.filter((action) =>
201 action === "merge" || action === "update-branch" ? canWrite : canEdit,
202 )
203 : [],
204 comment: active && (!pr.is_locked || canWrite),
205 resolve: false,
206 verdicts: active
207 ? pr.user?.login === viewer
208 ? ["comment"]
209 : CAPABILITIES.review.verdicts
210 : [],
211 requestReviewers: active && canEdit,
212 labels: active && canWrite,
213 updateMethods:
214 active && canWrite ? (repo.allow_rebase_update ? ["merge", "rebase"] : ["merge"]) : [],
215 };
216 };
217 const getPermissions = Effect.fn("ForgejoPullRequestProvider.getPermissions")(function* (
218 input: ProviderRepositoryRef & { readonly number: number },
219 ) {
220 const [repo, pr, viewer] = yield* Effect.all(
221 [getRepo(input), getPull(input), getViewer(input)],
222 { concurrency: 3 },
223 );
224 return permissions(repo, pr, viewer);
225 });
226 const readChecks = Effect.fn("ForgejoPullRequestProvider.readChecks")(function* (
227 input: ProviderRepositoryRef,
228 pr: typeof ForgejoPullRequest.Type,
229 ) {
230 const branch = read(
231 {
232 ...input,
233 path: `${repoPath(input)}/branches/${pr.base.ref.split("/").map(encodeURIComponent).join("/")}`,
234 },
235 ForgejoBranchStatusChecks,
236 ).pipe(
237 Effect.catchTags({
238 PullRequestProviderError: (error) => {
239 if (
240 isForgejoCliError(error.cause) &&
241 (error.cause.reason === "forbidden" || error.cause.reason === "not-found")
242 ) {
243 return Effect.succeed({});
244 }
245 return Effect.fail(error);
246 },
247 }),
248 );
249 const [statuses, policy] = yield* Effect.all(
250 [
251 page(
252 {
253 ...input,
254 path: `${repoPath(input)}/statuses/${encodeURIComponent(pr.head.sha)}?sort=recentupdate`,
255 },
256 ForgejoStatus,
257 ),
258 branch,
259 ],
260 { concurrency: 2 },
261 );
262 return markRequiredForgejoChecks(forgejoChecks(statuses.items, pr.html_url), policy);
263 });
264 const unsupported = (operation: string) =>
265 Effect.fail(failure(operation, `Forgejo does not expose ${operation} through its API.`));
266 const provider: PullRequestProviderApi = {
267 kind: SourceControlProviderKind.make("forgejo"),
268 capabilities: CAPABILITIES,
269 unavailableRequirement: UNAVAILABLE_REQUIREMENT,
270 readsPublicHostWithoutCheckout: true,
271 getViewer,
272 listChangeRequests: Effect.fn("ForgejoPullRequestProvider.listChangeRequests")(
273 function* (input) {
274 const offset = input.cursor?.delivered ?? 0;
275 const items: ReturnType<typeof forgejoChangeRequest>[] = [];
276 const state = input.state === "merged" ? "closed" : input.state;
277 const params = new URLSearchParams({ state, sort: "recentupdate" });
278 const filters = input.filters;
279 // Several `labels` match a pull request holding any of them but list it once per label it
280 // holds, which would throw the row offset off, so one required label is all Forgejo is
281 // asked for. The service narrows the rest.
282 const single = filters?.labels?.find((group) => group.length === 1)?.[0];
283 if (single !== undefined) {
284 const labels = yield* page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel);
285 const label = labels.items.find(
286 (candidate) => candidate.name.toLowerCase() === single.trim().toLowerCase(),
287 );
288 if (label !== undefined) params.set("labels", String(label.id));
289 }
290 if (filters?.author !== undefined)
291 params.set("poster", resolvePullRequestAuthorFilter(filters.author, input.viewer));
292 const query = { ...input, path: `${repoPath(input)}/pulls?${params}` };
293 // Self-hosted servers may cap pages below 50. Establish their actual page size before
294 // translating the service's row offset into an API page number.
295 const first = yield* readPage(query, Schema.NullOr(ForgejoPullRequest), 1).pipe(
296 Effect.catchTags({
297 // Forgejo answers a `poster` naming no account with a 400: nobody to list for.
298 PullRequestProviderError: (error) =>
299 params.has("poster") &&
300 isForgejoCliError(error.cause) &&
301 error.cause.httpStatus === 400
302 ? Effect.succeed(null)
303 : Effect.fail(error),
304 }),
305 );
306 if (first === null) return { items: [], truncated: false, continues: false };
307 const pageSize = first.rows.length || 50;
308 const firstIndex = Math.floor(offset / pageSize) + 1;
309 let consumed = 0;
310 let more = true;
311 for (let index = firstIndex; more && consumed < input.limit; index++) {
312 const result =
313 index === 1 ? first : yield* readPage(query, Schema.NullOr(ForgejoPullRequest), index);
314 const rows = result.rows;
315 const start = index === firstIndex ? offset % pageSize : 0;
316 const countBefore = consumed;
317 for (const row of rows.slice(start)) {
318 if (consumed >= input.limit) break;
319 consumed++;
320 if (row) items.push(forgejoChangeRequest(row));
321 }
322 more = result.more || rows.length - start > consumed - countBefore;
323 }
324 return { items, truncated: more, continues: true, cursorAdvance: consumed };
325 },
326 ),
327 getChangeRequestSummary: (input) => getPull(input).pipe(Effect.map(forgejoChangeRequest)),
328 getChangeRequestChecks: Effect.fn("ForgejoPullRequestProvider.getChangeRequestChecks")(
329 function* (input) {
330 const pr = yield* getPull(input);
331 return { state: forgejoChangeRequest(pr).state, checks: yield* readChecks(input, pr) };
332 },
333 ),
334 getChangeRequest: Effect.fn("ForgejoPullRequestProvider.getChangeRequest")(function* (input) {
335 const [pr, repo, viewer] = yield* Effect.all(
336 [getPull(input), getRepo(input), getViewer(input)],
337 { concurrency: 3 },
338 );
339 const checks = yield* readChecks(input, pr);
340 return {
341 ...forgejoChangeRequest(pr),
342 headSha: pr.head.sha,
343 body: pr.body ?? "",
344 changedFiles: pr.changed_files ?? 0,
345 reviewers: (pr.requested_reviewers ?? []).flatMap((user) => {
346 const actor = forgejoActor(user);
347 return actor ? [actor] : [];
348 }),
349 checks,
350 baseComparison: !pr.merge_base
351 ? "unknown"
352 : pr.merge_base === pr.base.sha
353 ? "up-to-date"
354 : "behind",
355 viewerPermissions: permissions(repo, pr, viewer),
356 mergeCapabilities: {
357 merge: repo.allow_merge_commits ?? true,
358 squash: repo.allow_squash_merge ?? true,
359 rebase: repo.allow_rebase ?? true,
360 },
361 } satisfies ProviderChangeRequestDetail;
362 }),
363 getViewerPermissions: getPermissions,
364 getChangeRequestActivity: Effect.fn("ForgejoPullRequestProvider.getChangeRequestActivity")(
365 function* (input) {
366 const [comments, reviews, commits, reactions, viewer] = yield* Effect.all(
367 [
368 // Issue comments ignore page/limit; fetch this unpaginated endpoint once.
369 readArray({ ...input, path: `${issuePath(input)}/comments` }, ForgejoComment).pipe(
370 Effect.map((items) => ({
371 items: items.slice(0, 500),
372 truncated: items.length > 500,
373 })),
374 ),
375 page({ ...input, path: `${pullPath(input)}/reviews` }, ForgejoReview),
376 // Commit file lists can exceed the output limit on large merges.
377 page(
378 { ...input, path: `${pullPath(input)}/commits?files=false&verification=false` },
379 ForgejoCommit,
380 ),
381 page({ ...input, path: `${issuePath(input)}/reactions` }, ForgejoReaction),
382 getViewer(input),
383 ],
384 { concurrency: 5 },
385 );
386 const reviewComments = yield* Effect.forEach(
387 reviews.items.filter((review) => review.comments_count > 0 && review.state !== "PENDING"),
388 (review) =>
389 readArray(
390 { ...input, path: `${pullPath(input)}/reviews/${review.id}/comments` },
391 ForgejoReviewComment,
392 ),
393 { concurrency: 4 },
394 );
395 const allInline = reviewComments.flat();
396 const inline = allInline.slice(0, 500);
397 const entries = [
398 ...comments.items.map((comment) => ({
399 comment: forgejoComment(comment),
400 reactionId: String(comment.id),
401 })),
402 ...reviews.items
403 .filter((review) => review.state !== "PENDING" && review.state !== "REQUEST_REVIEW")
404 .map((review) => ({
405 comment: forgejoReview(review),
406 reactionId: reviewCommentId(review),
407 })),
408 ...inline.map((comment) => ({
409 comment: {
410 ...forgejoComment(comment),
411 kind: "review-comment" as const,
412 path: comment.path,
413 },
414 reactionId: String(comment.id),
415 })),
416 ];
417 const enriched = yield* Effect.forEach(
418 entries,
419 ({ comment, reactionId }) =>
420 (reactionId === undefined
421 ? Effect.succeed([])
422 : readArray(
423 { ...input, path: `${repoPath(input)}/issues/comments/${reactionId}/reactions` },
424 ForgejoReaction,
425 )
426 ).pipe(
427 Effect.map((rows) => ({ ...comment, reactions: forgejoReactions(rows, viewer) })),
428 ),
429 { concurrency: 4 },
430 );
431 const byId = new Map(enriched.map((comment) => [comment.id, comment]));
432 const timeline = enriched.toSorted((a, b) => a.createdAt.localeCompare(b.createdAt));
433 return {
434 comments: timeline,
435 commentCount: timeline.length,
436 commentsTruncated:
437 comments.truncated || reviews.truncated || allInline.length > inline.length,
438 reviewThreads: inline.map((comment) => ({
439 ...forgejoReviewThread(comment),
440 comments: [byId.get(String(comment.id)) ?? forgejoComment(comment)],
441 })),
442 commits: commits.items.map(forgejoCommit),
443 reactions: forgejoReactions(reactions.items, viewer),
444 };
445 },
446 ),
447 getFileRevisions: Effect.fn("ForgejoPullRequestProvider.getFileRevisions")(function* (input) {
448 const result = yield* request({ ...input, path: `${pullPath(input)}.diff` });
449 if (result.stdoutTruncated) {
450 return yield* failure("getFileRevisions", "Forgejo diff exceeded the output limit.");
451 }
452 const revisions = new Map(parseDiffFileRevisions(result.stdout));
453 for (const path of input.paths) {
454 if (!revisions.has(path)) revisions.set(path, "");
455 }
456 return { revisions, complete: true };
457 }),
458 getDiff: (input) =>
459 request({
460 ...input,
461 path: input.commit
462 ? `${repoPath(input)}/git/commits/${encodeURIComponent(input.commit)}.diff`
463 : `${pullPath(input)}.diff`,
464 }).pipe(
465 Effect.map((result) => ({
466 patch: result.stdout,
467 truncated: result.stdoutTruncated,
468 nextCursor: null,
469 })),
470 ),
471 getDiffFileContents: Effect.fn("ForgejoPullRequestProvider.getDiffFileContents")(
472 function* (input) {
473 const pr = yield* getPull(input);
474 const commit = input.commit
475 ? yield* read(
476 {
477 ...input,
478 path: `${repoPath(input)}/git/commits/${encodeURIComponent(input.commit)}?files=false&verification=false`,
479 },
480 ForgejoCommit,
481 )
482 : null;
483 const oldRef = commit ? commit.parents[0]?.sha : pr.merge_base || pr.base.sha;
484 const newRef = input.commit ?? pr.head.sha;
485 const content = (repository: string, ref: string, path: string) =>
486 read(
487 {
488 ...input,
489 repository,
490 path: `${repoPath({ ...input, repository })}/contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=${encodeURIComponent(ref)}`,
491 },
492 Schema.Struct({ content: Schema.String, encoding: Schema.Literal("base64") }),
493 ).pipe(Effect.map((file) => Buffer.from(file.content, "base64").toString("utf8")));
494 const [oldContents, newContents] = yield* Effect.all(
495 [
496 input.changeType === "new" || !oldRef
497 ? Effect.succeed("")
498 : content(input.repository, oldRef, input.oldPath),
499 input.changeType === "deleted"
500 ? Effect.succeed("")
501 : content(pr.head.repo?.full_name ?? input.repository, newRef, input.newPath),
502 ],
503 { concurrency: 2 },
504 );
505 return { oldContents, newContents };
506 },
507 ),
508 runAction: (input) => {
509 switch (input.action) {
510 case "merge":
511 return Effect.gen(function* () {
512 const deleteBranch = (yield* getRepo(input)).default_delete_branch_after_merge ?? false;
513 yield* write({
514 ...input,
515 path: `${pullPath(input)}/merge`,
516 method: "POST",
517 body: { Do: input.mergeMethod ?? "merge", delete_branch_after_merge: deleteBranch },
518 }).pipe(
519 Effect.catchTags({
520 // Forgejo merges before deleting the branch, so a refused deletion still merged.
521 PullRequestProviderError: (error) =>
522 deleteBranch
523 ? getPull(input).pipe(
524 Effect.mapError(() => error),
525 Effect.flatMap((pr) => (pr.merged ? Effect.void : Effect.fail(error))),
526 )
527 : Effect.fail(error),
528 }),
529 );
530 });
531 case "close":
532 case "reopen":
533 return write({
534 ...input,
535 path: pullPath(input),
536 method: "PATCH",
537 body: { state: input.action === "close" ? "closed" : "open" },
538 });
539 case "update-branch":
540 return write({
541 ...input,
542 path: `${pullPath(input)}/update?style=${input.updateMethod ?? "merge"}`,
543 method: "POST",
544 });
545 default:
546 return unsupported(input.action);
547 }
548 },
549 updateChangeRequest: (input) =>
550 write({
551 ...input,
552 path: pullPath(input),
553 method: "PATCH",
554 body: {
555 ...(input.title === undefined ? {} : { title: input.title }),
556 ...(input.body === undefined ? {} : { body: input.body }),
557 },
558 }),
559 comment: (input) =>
560 write({
561 ...input,
562 path: `${issuePath(input)}/comments`,
563 method: "POST",
564 body: { body: input.body },
565 }),
566 updateComment: (input) =>
567 write({
568 ...input,
569 path: `${repoPath(input)}/issues/comments/${encodeURIComponent(input.commentId)}`,
570 method: "PATCH",
571 body: { body: input.body },
572 }),
573 submitReview: Effect.fn("ForgejoPullRequestProvider.submitReview")(function* (input) {
574 const pr = yield* getPull(input);
575 yield* write({
576 ...input,
577 path: `${pullPath(input)}/reviews`,
578 method: "POST",
579 body: {
580 event:
581 input.verdict === "approve"
582 ? "APPROVED"
583 : input.verdict === "request-changes"
584 ? "REQUEST_CHANGES"
585 : "COMMENT",
586 body: input.body,
587 commit_id: pr.head.sha,
588 comments: input.comments.map((comment) => {
589 const position = comment.position;
590 const old =
591 position.kind === "deleted" ||
592 (position.kind === "context" && position.side === "left");
593 return {
594 path: old ? (comment.oldPath ?? comment.path) : comment.path,
595 body: comment.body,
596 old_position: old ? position.oldLine : 0,
597 new_position: old ? 0 : position.newLine,
598 };
599 }),
600 },
601 });
602 }),
603 listReviewerCandidates: Effect.fn("ForgejoPullRequestProvider.listReviewerCandidates")(
604 function* (input) {
605 const [pr, users] = yield* Effect.all(
606 [getPull(input), page({ ...input, path: `${repoPath(input)}/assignees` }, ForgejoUser)],
607 { concurrency: 2 },
608 );
609 return {
610 candidates: users.items
611 .filter((user) => user.login !== pr.user?.login)
612 .flatMap((user) => {
613 const actor = forgejoActor(user);
614 return actor
615 ? [
616 {
617 ...actor,
618 id: user.login,
619 kind: "user" as const,
620 isRequested:
621 pr.requested_reviewers?.some((reviewer) => reviewer.login === user.login) ??
622 false,
623 },
624 ]
625 : [];
626 }),
627 truncated: users.truncated,
628 };
629 },
630 ),
631 setReviewerRequest: (input) =>
632 write({
633 ...input,
634 path: `${pullPath(input)}/requested_reviewers`,
635 method: input.requested ? "POST" : "DELETE",
636 body: { reviewers: input.reviewers.map((reviewer) => reviewer.id) },
637 }),
638 listLabelCandidates: Effect.fn("ForgejoPullRequestProvider.listLabelCandidates")(
639 function* (input) {
640 const [pr, labels] = yield* Effect.all(
641 [getPull(input), page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel)],
642 { concurrency: 2 },
643 );
644 return {
645 candidates: labels.items.map((label) => ({
646 name: label.name,
647 color: label.color ?? null,
648 description: label.description ?? null,
649 isApplied: pr.labels?.some((applied) => applied.id === label.id) ?? false,
650 })),
651 truncated: labels.truncated,
652 };
653 },
654 ),
655 listRepositoryLabels: Effect.fn("ForgejoPullRequestProvider.listRepositoryLabels")(
656 function* (input) {
657 const labels = yield* page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel);
658 return {
659 items: labels.items.map((label) => ({ name: label.name, color: label.color ?? null })),
660 truncated: labels.truncated,
661 };
662 },
663 ),
664 searchRepositoryAuthors: Effect.fn("ForgejoPullRequestProvider.searchRepositoryAuthors")(
665 function* (input) {
666 const query = input.query?.trim() ?? "";
667 const actors = (users: ReadonlyArray<typeof ForgejoUser.Type>) =>
668 users.flatMap((user) => {
669 const actor = forgejoActor(user);
670 return actor ? [actor] : [];
671 });
672 // Before anything is typed the repository's own people stand in; a search reaches
673 // contributors from forks, who are never assignable.
674 if (query.length === 0) {
675 const users = yield* page(
676 { ...input, path: `${repoPath(input)}/assignees` },
677 ForgejoUser,
678 100,
679 );
680 return { items: actors(users.items), truncated: users.truncated };
681 }
682 const found = yield* readLinked(
683 {
684 ...input,
685 path: `users/search?${new URLSearchParams({ q: query, limit: String(USER_SEARCH_LIMIT) })}`,
686 },
687 ForgejoUserSearch,
688 );
689 const users = found.value.data ?? [];
690 // A server may cap pages below the limit asked for; its `link` header still says more.
691 return {
692 items: actors(users),
693 truncated: found.next || users.length >= USER_SEARCH_LIMIT,
694 };
695 },
696 ),
697 setLabels: Effect.fn("ForgejoPullRequestProvider.setLabels")(function* (input) {
698 const labels = yield* page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel);
699 const selected = labels.items.filter((label) => input.labels.includes(label.name));
700 if (selected.length !== input.labels.length)
701 return yield* failure("setLabels", "One or more requested labels could not be found.");
702 if (input.applied)
703 yield* write({
704 ...input,
705 path: `${issuePath(input)}/labels`,
706 method: "POST",
707 body: { labels: selected.map((label) => label.id) },
708 });
709 else
710 yield* Effect.forEach(
711 selected,
712 (label) =>
713 write({ ...input, path: `${issuePath(input)}/labels/${label.id}`, method: "DELETE" }),
714 { concurrency: 1 },
715 );
716 }),
717 setReaction: Effect.fn("ForgejoPullRequestProvider.setReaction")(function* (input) {
718 let commentId = input.subjectId;
719 if (commentId?.startsWith("review:")) {
720 const reviewId = /^review:([1-9]\d*)$/.exec(commentId)?.[1];
721 if (!reviewId) return yield* failure("setReaction", "Invalid Forgejo review ID.");
722 const review = yield* read(
723 { ...input, path: `${pullPath(input)}/reviews/${reviewId}` },
724 ForgejoReview,
725 );
726 commentId = reviewCommentId(review);
727 if (!commentId)
728 return yield* failure(
729 "setReaction",
730 "Forgejo did not return a comment ID for this review.",
731 );
732 }
733 if (commentId && !/^[1-9]\d*$/.test(commentId))
734 return yield* failure("setReaction", "Invalid Forgejo comment ID.");
735 yield* write({
736 ...input,
737 path: commentId
738 ? `${repoPath(input)}/issues/comments/${commentId}/reactions`
739 : `${issuePath(input)}/reactions`,
740 method: input.reacted ? "POST" : "DELETE",
741 body: { content: FORGEJO_REACTIONS[input.content] },
742 });
743 }),
744 replyToThread: () => unsupported("thread replies"),
745 setThreadResolution: () => unsupported("thread resolution"),
746 };
747 return provider;
748});