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

ForgejoPullRequestProvider.ts

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