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