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

ForgejoPullRequestProvider.ts

759 lines29.9 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 // Forgejo has no `merged` list state: `state=closed` returns merged and
312 // closed-unmerged rows alike, so rows are filtered by their mapped state and
313 // only matching rows count toward the requested limit.
314 for (let index = firstIndex; more && items.length < input.limit; index++) {
315 const result =
316 index === 1 ? first : yield* readPage(query, Schema.NullOr(ForgejoPullRequest), index);
317 const rows = result.rows;
318 const start = index === firstIndex ? offset % pageSize : 0;
319 const countBefore = consumed;
320 for (const row of rows.slice(start)) {
321 if (items.length >= input.limit) break;
322 consumed++;
323 if (!row) continue;
324 const changeRequest = forgejoChangeRequest(row);
325 if (input.state !== "all" && changeRequest.state !== input.state) continue;
326 items.push(changeRequest);
327 }
328 more = result.more || rows.length - start > consumed - countBefore;
329 }
330 return { items, truncated: more, continues: true, cursorAdvance: consumed };
331 },
332 ),
333 getChangeRequestPreview: (input) => getPull(input).pipe(Effect.map(forgejoChangeRequest)),
334 getChangeRequestSummary: (input) => getPull(input).pipe(Effect.map(forgejoChangeRequest)),
335 getChangeRequestChecks: Effect.fn("ForgejoPullRequestProvider.getChangeRequestChecks")(
336 function* (input) {
337 const pr = yield* getPull(input);
338 return { state: forgejoChangeRequest(pr).state, checks: yield* readChecks(input, pr) };
339 },
340 ),
341 getChangeRequest: Effect.fn("ForgejoPullRequestProvider.getChangeRequest")(function* (input) {
342 const [pr, repo, viewer] = yield* Effect.all(
343 [getPull(input), getRepo(input), getViewer(input)],
344 { concurrency: 3 },
345 );
346 const checks = yield* readChecks(input, pr);
347 return {
348 ...forgejoChangeRequest(pr),
349 headSha: pr.head.sha,
350 body: pr.body ?? "",
351 changedFiles: pr.changed_files ?? 0,
352 reviewers: (pr.requested_reviewers ?? []).flatMap((user) => {
353 const actor = forgejoActor(user);
354 return actor ? [actor] : [];
355 }),
356 checks,
357 baseComparison: !pr.merge_base
358 ? "unknown"
359 : pr.merge_base === pr.base.sha
360 ? "up-to-date"
361 : "behind",
362 viewerPermissions: permissions(repo, pr, viewer),
363 mergeCapabilities: {
364 merge: repo.allow_merge_commits ?? true,
365 squash: repo.allow_squash_merge ?? true,
366 rebase: repo.allow_rebase ?? true,
367 },
368 } satisfies ProviderChangeRequestDetail;
369 }),
370 getViewerPermissions: getPermissions,
371 getChangeRequestActivity: Effect.fn("ForgejoPullRequestProvider.getChangeRequestActivity")(
372 function* (input) {
373 const [comments, reviews, commits, reactions, viewer] = yield* Effect.all(
374 [
375 // Issue comments ignore page/limit; fetch this unpaginated endpoint once.
376 readArray({ ...input, path: `${issuePath(input)}/comments` }, ForgejoComment).pipe(
377 Effect.map((items) => ({
378 items: items.slice(0, 500),
379 truncated: items.length > 500,
380 })),
381 ),
382 page({ ...input, path: `${pullPath(input)}/reviews` }, ForgejoReview),
383 // Commit file lists can exceed the output limit on large merges.
384 page(
385 { ...input, path: `${pullPath(input)}/commits?files=false&verification=false` },
386 ForgejoCommit,
387 ),
388 page({ ...input, path: `${issuePath(input)}/reactions` }, ForgejoReaction),
389 getViewer(input),
390 ],
391 { concurrency: 5 },
392 );
393 const reviewComments = yield* Effect.forEach(
394 reviews.items.filter((review) => review.comments_count > 0 && review.state !== "PENDING"),
395 (review) =>
396 readArray(
397 { ...input, path: `${pullPath(input)}/reviews/${review.id}/comments` },
398 ForgejoReviewComment,
399 ),
400 { concurrency: 4 },
401 );
402 const allInline = reviewComments.flat();
403 const inline = allInline.slice(0, 500);
404 const entries = [
405 ...comments.items.map((comment) => ({
406 comment: forgejoComment(comment),
407 reactionId: String(comment.id),
408 })),
409 ...reviews.items
410 .filter((review) => review.state !== "PENDING" && review.state !== "REQUEST_REVIEW")
411 .map((review) => ({
412 comment: forgejoReview(review),
413 reactionId: reviewCommentId(review),
414 })),
415 ...inline.map((comment) => ({
416 comment: {
417 ...forgejoComment(comment),
418 kind: "review-comment" as const,
419 path: comment.path,
420 },
421 reactionId: String(comment.id),
422 })),
423 ];
424 const enriched = yield* Effect.forEach(
425 entries,
426 ({ comment, reactionId }) =>
427 (reactionId === undefined
428 ? Effect.succeed([])
429 : readArray(
430 { ...input, path: `${repoPath(input)}/issues/comments/${reactionId}/reactions` },
431 ForgejoReaction,
432 )
433 ).pipe(
434 Effect.map((rows) => ({ ...comment, reactions: forgejoReactions(rows, viewer) })),
435 ),
436 { concurrency: 4 },
437 );
438 const byId = new Map(enriched.map((comment) => [comment.id, comment]));
439 const timeline = enriched.toSorted((a, b) => a.createdAt.localeCompare(b.createdAt));
440 return {
441 comments: timeline,
442 commentCount: timeline.length,
443 commentsTruncated:
444 comments.truncated || reviews.truncated || allInline.length > inline.length,
445 reviewThreads: inline.map((comment) => ({
446 ...forgejoReviewThread(comment),
447 comments: [byId.get(String(comment.id)) ?? forgejoComment(comment)],
448 })),
449 commits: commits.items.map(forgejoCommit),
450 reactions: forgejoReactions(reactions.items, viewer),
451 };
452 },
453 ),
454 getFileRevisions: Effect.fn("ForgejoPullRequestProvider.getFileRevisions")(function* (input) {
455 const result = yield* request({ ...input, path: `${pullPath(input)}.diff` });
456 if (result.stdoutTruncated) {
457 return yield* failure("getFileRevisions", "Forgejo diff exceeded the output limit.");
458 }
459 const revisions = new Map(parseDiffFileRevisions(result.stdout));
460 for (const path of input.paths) {
461 if (!revisions.has(path)) revisions.set(path, "");
462 }
463 return { revisions, complete: true };
464 }),
465 getDiff: (input) =>
466 request({
467 ...input,
468 path: input.commit
469 ? `${repoPath(input)}/git/commits/${encodeURIComponent(input.commit)}.diff`
470 : `${pullPath(input)}.diff`,
471 }).pipe(
472 Effect.map((result) => ({
473 patch: result.stdout,
474 truncated: result.stdoutTruncated,
475 nextCursor: null,
476 })),
477 ),
478 getDiffFileContents: Effect.fn("ForgejoPullRequestProvider.getDiffFileContents")(
479 function* (input) {
480 const pr = yield* getPull(input);
481 const commit = input.commit
482 ? yield* read(
483 {
484 ...input,
485 path: `${repoPath(input)}/git/commits/${encodeURIComponent(input.commit)}?files=false&verification=false`,
486 },
487 ForgejoCommit,
488 )
489 : null;
490 const oldRef = commit ? commit.parents[0]?.sha : pr.merge_base || pr.base.sha;
491 const newRef = input.commit ?? pr.head.sha;
492 const content = (repository: string, ref: string, path: string) =>
493 read(
494 {
495 ...input,
496 repository,
497 path: `${repoPath({ ...input, repository })}/contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=${encodeURIComponent(ref)}`,
498 },
499 Schema.Struct({ content: Schema.String, encoding: Schema.Literal("base64") }),
500 ).pipe(Effect.map((file) => Buffer.from(file.content, "base64").toString("utf8")));
501 const [oldContents, newContents] = yield* Effect.all(
502 [
503 input.changeType === "new" || !oldRef
504 ? Effect.succeed("")
505 : content(input.repository, oldRef, input.oldPath),
506 input.changeType === "deleted"
507 ? Effect.succeed("")
508 : content(pr.head.repo?.full_name ?? input.repository, newRef, input.newPath),
509 ],
510 { concurrency: 2 },
511 );
512 return { oldContents, newContents };
513 },
514 ),
515 runAction: (input) => {
516 switch (input.action) {
517 case "merge":
518 return Effect.gen(function* () {
519 const deleteBranch = (yield* getRepo(input)).default_delete_branch_after_merge ?? false;
520 yield* write({
521 ...input,
522 path: `${pullPath(input)}/merge`,
523 method: "POST",
524 body: { Do: input.mergeMethod ?? "merge", delete_branch_after_merge: deleteBranch },
525 }).pipe(
526 Effect.catchTags({
527 // Forgejo merges before deleting the branch, so a refused deletion still merged.
528 PullRequestProviderError: (error) =>
529 deleteBranch
530 ? getPull(input).pipe(
531 Effect.mapError(() => error),
532 Effect.flatMap((pr) => (pr.merged ? Effect.void : Effect.fail(error))),
533 )
534 : Effect.fail(error),
535 }),
536 );
537 });
538 case "close":
539 case "reopen":
540 return write({
541 ...input,
542 path: pullPath(input),
543 method: "PATCH",
544 body: { state: input.action === "close" ? "closed" : "open" },
545 });
546 case "update-branch":
547 return write({
548 ...input,
549 path: `${pullPath(input)}/update?style=${input.updateMethod ?? "merge"}`,
550 method: "POST",
551 });
552 default:
553 return unsupported(input.action);
554 }
555 },
556 updateChangeRequest: (input) =>
557 write({
558 ...input,
559 path: pullPath(input),
560 method: "PATCH",
561 body: {
562 ...(input.title === undefined ? {} : { title: input.title }),
563 ...(input.body === undefined ? {} : { body: input.body }),
564 },
565 }),
566 comment: (input) =>
567 write({
568 ...input,
569 path: `${issuePath(input)}/comments`,
570 method: "POST",
571 body: { body: input.body },
572 }),
573 updateComment: (input) =>
574 write({
575 ...input,
576 path: `${repoPath(input)}/issues/comments/${encodeURIComponent(input.commentId)}`,
577 method: "PATCH",
578 body: { body: input.body },
579 }),
580 submitReview: Effect.fn("ForgejoPullRequestProvider.submitReview")(function* (input) {
581 const pr = yield* getPull(input);
582 yield* write({
583 ...input,
584 path: `${pullPath(input)}/reviews`,
585 method: "POST",
586 body: {
587 event:
588 input.verdict === "approve"
589 ? "APPROVED"
590 : input.verdict === "request-changes"
591 ? "REQUEST_CHANGES"
592 : "COMMENT",
593 body: input.body,
594 commit_id: pr.head.sha,
595 comments: input.comments.map((comment) => {
596 const position = comment.position;
597 const old =
598 position.kind === "deleted" ||
599 (position.kind === "context" && position.side === "left");
600 return {
601 path: old ? (comment.oldPath ?? comment.path) : comment.path,
602 body: comment.body,
603 old_position: old ? position.oldLine : 0,
604 new_position: old ? 0 : position.newLine,
605 };
606 }),
607 },
608 });
609 }),
610 listReviewerCandidates: Effect.fn("ForgejoPullRequestProvider.listReviewerCandidates")(
611 function* (input) {
612 // Unpaginated in Forgejo: paging it returns the full list on every page.
613 const [pr, users] = yield* Effect.all(
614 [
615 getPull(input),
616 readArray({ ...input, path: `${repoPath(input)}/assignees` }, ForgejoUser),
617 ],
618 { concurrency: 2 },
619 );
620 return {
621 candidates: users
622 .filter((user) => user.login !== pr.user?.login)
623 .flatMap((user) => {
624 const actor = forgejoActor(user);
625 return actor
626 ? [
627 {
628 ...actor,
629 id: user.login,
630 kind: "user" as const,
631 isRequested:
632 pr.requested_reviewers?.some((reviewer) => reviewer.login === user.login) ??
633 false,
634 },
635 ]
636 : [];
637 }),
638 truncated: false,
639 };
640 },
641 ),
642 setReviewerRequest: (input) =>
643 write({
644 ...input,
645 path: `${pullPath(input)}/requested_reviewers`,
646 method: input.requested ? "POST" : "DELETE",
647 body: { reviewers: input.reviewers.map((reviewer) => reviewer.id) },
648 }),
649 listLabelCandidates: Effect.fn("ForgejoPullRequestProvider.listLabelCandidates")(
650 function* (input) {
651 const [pr, labels] = yield* Effect.all(
652 [getPull(input), page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel)],
653 { concurrency: 2 },
654 );
655 return {
656 candidates: labels.items.map((label) => ({
657 name: label.name,
658 color: label.color ?? null,
659 description: label.description ?? null,
660 isApplied: pr.labels?.some((applied) => applied.id === label.id) ?? false,
661 })),
662 truncated: labels.truncated,
663 };
664 },
665 ),
666 listRepositoryLabels: Effect.fn("ForgejoPullRequestProvider.listRepositoryLabels")(
667 function* (input) {
668 const labels = yield* page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel);
669 return {
670 items: labels.items.map((label) => ({ name: label.name, color: label.color ?? null })),
671 truncated: labels.truncated,
672 };
673 },
674 ),
675 searchRepositoryAuthors: Effect.fn("ForgejoPullRequestProvider.searchRepositoryAuthors")(
676 function* (input) {
677 const query = input.query?.trim() ?? "";
678 const actors = (users: ReadonlyArray<typeof ForgejoUser.Type>) =>
679 users.flatMap((user) => {
680 const actor = forgejoActor(user);
681 return actor ? [actor] : [];
682 });
683 // Before anything is typed the repository's own people stand in; a search reaches
684 // contributors from forks, who are never assignable.
685 if (query.length === 0) {
686 const users = yield* page(
687 { ...input, path: `${repoPath(input)}/assignees` },
688 ForgejoUser,
689 100,
690 );
691 return { items: actors(users.items), truncated: users.truncated };
692 }
693 const found = yield* readLinked(
694 {
695 ...input,
696 path: `users/search?${new URLSearchParams({ q: query, limit: String(USER_SEARCH_LIMIT) })}`,
697 },
698 ForgejoUserSearch,
699 );
700 const users = found.value.data ?? [];
701 // A server may cap pages below the limit asked for; its `link` header still says more.
702 return {
703 items: actors(users),
704 truncated: found.next || users.length >= USER_SEARCH_LIMIT,
705 };
706 },
707 ),
708 setLabels: Effect.fn("ForgejoPullRequestProvider.setLabels")(function* (input) {
709 const labels = yield* page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel);
710 const selected = labels.items.filter((label) => input.labels.includes(label.name));
711 if (selected.length !== input.labels.length)
712 return yield* failure("setLabels", "One or more requested labels could not be found.");
713 if (input.applied)
714 yield* write({
715 ...input,
716 path: `${issuePath(input)}/labels`,
717 method: "POST",
718 body: { labels: selected.map((label) => label.id) },
719 });
720 else
721 yield* Effect.forEach(
722 selected,
723 (label) =>
724 write({ ...input, path: `${issuePath(input)}/labels/${label.id}`, method: "DELETE" }),
725 { concurrency: 1 },
726 );
727 }),
728 setReaction: Effect.fn("ForgejoPullRequestProvider.setReaction")(function* (input) {
729 let commentId = input.subjectId;
730 if (commentId?.startsWith("review:")) {
731 const reviewId = /^review:([1-9]\d*)$/.exec(commentId)?.[1];
732 if (!reviewId) return yield* failure("setReaction", "Invalid Forgejo review ID.");
733 const review = yield* read(
734 { ...input, path: `${pullPath(input)}/reviews/${reviewId}` },
735 ForgejoReview,
736 );
737 commentId = reviewCommentId(review);
738 if (!commentId)
739 return yield* failure(
740 "setReaction",
741 "Forgejo did not return a comment ID for this review.",
742 );
743 }
744 if (commentId && !/^[1-9]\d*$/.test(commentId))
745 return yield* failure("setReaction", "Invalid Forgejo comment ID.");
746 yield* write({
747 ...input,
748 path: commentId
749 ? `${repoPath(input)}/issues/comments/${commentId}/reactions`
750 : `${issuePath(input)}/reactions`,
751 method: input.reacted ? "POST" : "DELETE",
752 body: { content: FORGEJO_REACTIONS[input.content] },
753 });
754 }),
755 replyToThread: () => unsupported("thread replies"),
756 setThreadResolution: () => unsupported("thread resolution"),
757 };
758 return provider;
759});