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

ForgejoPullRequestProvider.ts

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