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