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