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