Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Schema from "effect/Schema";
4import * as Result from "effect/Result";
5import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
6import { decodeJsonResult } from "@t3tools/shared/schemaJson";
7import * as ForgejoCli from "./ForgejoCli.ts";
8import { parseDiffFileRevisions } from "@t3tools/source-control-core/server/diffFileRevisions";
9import {
10 PullRequestProviderError,
11 type ProviderChangeRequestDetail,
12 type ProviderRepositoryRef,
13 type PullRequestProviderApi,
14} from "@t3tools/source-control-core/server/PullRequestProvider";
15import {
16 ForgejoPullRequest,
17 ForgejoRepository,
18 ForgejoUser,
19 ForgejoComment,
20 ForgejoReview,
21 ForgejoReviewComment,
22 ForgejoCommit,
23 ForgejoStatus,
24 ForgejoLabel,
25 ForgejoReaction,
26 FORGEJO_REACTIONS,
27 forgejoChangeRequest,
28 forgejoActor,
29 forgejoComment,
30 forgejoReview,
31 forgejoReviewThread,
32 forgejoCommit,
33 forgejoChecks,
34 forgejoReactions,
35} from "./forgejoPullRequestJson.ts";
36import { definition } from "../client/definition.ts";
37
38const CAPABILITIES: PullRequestCapabilities = {
39 diff: true,
40 viewedFiles: "environment",
41 comment: true,
42 actions: [...definition.changeRequestActions],
43 mergeMethods: ["merge", "squash", "rebase"],
44 updateMethods: ["merge", "rebase"],
45 search: false,
46 reactions: true,
47 labels: true,
48 // Forgejo's public API has no thread replies/resolution or draft conversion endpoint.
49 review: {
50 inlineComment: true,
51 reply: false,
52 resolve: false,
53 verdicts: ["comment", "approve", "request-changes"],
54 },
55 reviewers: { request: true, listCandidates: true },
56 edit: { changeRequest: true, comment: true },
57};
58const repoPath = (input: ProviderRepositoryRef) =>
59 `repos/${input.repository.split("/").map(encodeURIComponent).join("/")}`;
60const pullPath = (input: ProviderRepositoryRef & { readonly number: number }) =>
61 `${repoPath(input)}/pulls/${input.number}`;
62const issuePath = (input: ProviderRepositoryRef & { readonly number: number }) =>
63 `${repoPath(input)}/issues/${input.number}`;
64// Review IDs differ from the issue-comment IDs used by Forgejo's reactions API.
65const reviewCommentId = (review: typeof ForgejoReview.Type) =>
66 /#issuecomment-([1-9]\d*)$/.exec(review.html_url ?? "")?.[1];
67
68export const make = Effect.gen(function* () {
69 const cli = yield* ForgejoCli.ForgejoCli;
70 const failure = (operation: string, detail: string, cause?: unknown) =>
71 new PullRequestProviderError({
72 provider: SourceControlProviderKind.make("forgejo"),
73 operation,
74 reason: "failed",
75 detail,
76 ...(cause === undefined ? {} : { cause }),
77 });
78 const request = (input: ForgejoCli.ForgejoApiInput) =>
79 cli.api(input).pipe(
80 Effect.mapError(
81 (error) =>
82 new PullRequestProviderError({
83 provider: SourceControlProviderKind.make("forgejo"),
84 operation: input.path,
85 detail: error.detail,
86 cause: error,
87 reason:
88 error.reason === "missing-cli"
89 ? "missing-tool"
90 : error.reason === "authentication"
91 ? "unauthenticated"
92 : error.reason === "rate-limit"
93 ? "rate-limited"
94 : error.reason === "not-found"
95 ? "not-found"
96 : "failed",
97 }),
98 ),
99 );
100 const read = Effect.fn("ForgejoPullRequestProvider.read")(function* <A>(
101 input: ForgejoCli.ForgejoApiInput,
102 schema: Schema.Codec<A, unknown, never, never>,
103 ) {
104 const result = yield* request(input);
105 if (result.stdoutTruncated)
106 return yield* failure(input.path, "Forgejo response exceeded the output limit.");
107 const decoded = decodeJsonResult(schema)(result.stdout);
108 return Result.isSuccess(decoded)
109 ? decoded.success
110 : yield* failure(input.path, "Forgejo returned an invalid response.", decoded.failure);
111 });
112 const readArray = <A>(
113 input: ForgejoCli.ForgejoApiInput,
114 schema: Schema.Codec<A, unknown, never, never>,
115 ) => read(input, Schema.NullOr(Schema.Array(schema))).pipe(Effect.map((rows) => rows ?? []));
116 const readPage = Effect.fn("ForgejoPullRequestProvider.readPage")(function* <A>(
117 input: ForgejoCli.ForgejoApiInput,
118 schema: Schema.Codec<A, unknown, never, never>,
119 index: number,
120 ) {
121 const result = yield* request({
122 ...input,
123 path: `${input.path}${input.path.includes("?") ? "&" : "?"}limit=50&page=${index}`,
124 });
125 if (result.stdoutTruncated)
126 return yield* failure(input.path, "Forgejo response exceeded the output limit.");
127 const decoded = decodeJsonResult(Schema.NullOr(Schema.Array(schema)))(result.stdout);
128 if (Result.isFailure(decoded))
129 return yield* failure(input.path, "Forgejo returned an invalid response.", decoded.failure);
130 const rows = decoded.success ?? [];
131 const links = /^link:\s*(.*)$/im.exec(result.stderr)?.[1];
132 return {
133 rows,
134 more: rows.length > 0 && (links === undefined || /rel="?next"?/i.test(links)),
135 };
136 });
137 // Use a stable, small page size that also works with Forgejo's default maximum of 50.
138 const page = Effect.fn("ForgejoPullRequestProvider.page")(function* <A>(
139 input: ForgejoCli.ForgejoApiInput,
140 schema: Schema.Codec<A, unknown, never, never>,
141 limit = 500,
142 ) {
143 const items: A[] = [];
144 for (let index = 1; items.length < limit; index++) {
145 const { rows, more } = yield* readPage(input, schema, index);
146 items.push(...rows);
147 if (!more) return { items, truncated: false };
148 }
149 return { items, truncated: true };
150 });
151 const write = (input: ForgejoCli.ForgejoApiInput) => request(input).pipe(Effect.asVoid);
152 const getPull = (input: ProviderRepositoryRef & { readonly number: number }) =>
153 read(
154 {
155 cwd: input.cwd,
156 repository: input.repository,
157 host: input.host,
158 path: pullPath(input),
159 },
160 ForgejoPullRequest,
161 );
162 const getRepo = (input: ProviderRepositoryRef) =>
163 read({ ...input, path: repoPath(input) }, ForgejoRepository);
164 const getViewer = (input: {
165 readonly cwd: string;
166 readonly repository?: string;
167 readonly host?: string;
168 }) => read({ ...input, path: "user" }, ForgejoUser).pipe(Effect.map((user) => user.login));
169 const permissions = (
170 repo: typeof ForgejoRepository.Type,
171 pr: typeof ForgejoPullRequest.Type,
172 viewer: string,
173 ): PullRequestViewerPermissions => {
174 const canWrite = repo.permissions?.push ?? false;
175 const canEdit = canWrite || pr.user?.login === viewer;
176 const active = !repo.archived;
177 return {
178 actions: active
179 ? CAPABILITIES.actions.filter((action) =>
180 action === "merge" || action === "update-branch" ? canWrite : canEdit,
181 )
182 : [],
183 comment: active && (!pr.is_locked || canWrite),
184 resolve: false,
185 verdicts: active
186 ? pr.user?.login === viewer
187 ? ["comment"]
188 : CAPABILITIES.review.verdicts
189 : [],
190 requestReviewers: active && canEdit,
191 labels: active && canWrite,
192 updateMethods:
193 active && canWrite ? (repo.allow_rebase_update ? ["merge", "rebase"] : ["merge"]) : [],
194 };
195 };
196 const getPermissions = Effect.fn("ForgejoPullRequestProvider.getPermissions")(function* (
197 input: ProviderRepositoryRef & { readonly number: number },
198 ) {
199 const [repo, pr, viewer] = yield* Effect.all(
200 [getRepo(input), getPull(input), getViewer(input)],
201 { concurrency: 3 },
202 );
203 return permissions(repo, pr, viewer);
204 });
205 const unsupported = (operation: string) =>
206 Effect.fail(failure(operation, `Forgejo does not expose ${operation} through its API.`));
207 const provider: PullRequestProviderApi = {
208 kind: SourceControlProviderKind.make("forgejo"),
209 capabilities: CAPABILITIES,
210 getViewer,
211 listChangeRequests: Effect.fn("ForgejoPullRequestProvider.listChangeRequests")(
212 function* (input) {
213 const offset = input.cursor?.delivered ?? 0;
214 const items: ReturnType<typeof forgejoChangeRequest>[] = [];
215 const state = input.state === "merged" ? "closed" : input.state;
216 const query = {
217 ...input,
218 path: `${repoPath(input)}/pulls?state=${state}&sort=recentupdate`,
219 };
220 // Self-hosted servers may cap pages below 50. Establish their actual page size before
221 // translating the service's row offset into an API page number.
222 const first = yield* readPage(query, Schema.NullOr(ForgejoPullRequest), 1);
223 const pageSize = first.rows.length || 50;
224 const firstIndex = Math.floor(offset / pageSize) + 1;
225 let consumed = 0;
226 let more = true;
227 for (let index = firstIndex; more && consumed < input.limit; index++) {
228 const result =
229 index === 1 ? first : yield* readPage(query, Schema.NullOr(ForgejoPullRequest), index);
230 const rows = result.rows;
231 const start = index === firstIndex ? offset % pageSize : 0;
232 const countBefore = consumed;
233 for (const row of rows.slice(start)) {
234 if (consumed >= input.limit) break;
235 consumed++;
236 if (row) items.push(forgejoChangeRequest(row));
237 }
238 more = result.more || rows.length - start > consumed - countBefore;
239 }
240 return { items, truncated: more, continues: true, cursorAdvance: consumed };
241 },
242 ),
243 getChangeRequestSummary: (input) => getPull(input).pipe(Effect.map(forgejoChangeRequest)),
244 getChangeRequestChecks: Effect.fn("ForgejoPullRequestProvider.getChangeRequestChecks")(
245 function* (input) {
246 const pr = yield* getPull(input);
247 const statuses = yield* page(
248 {
249 ...input,
250 path: `${repoPath(input)}/statuses/${encodeURIComponent(pr.head.sha)}?sort=recentupdate`,
251 },
252 ForgejoStatus,
253 );
254 return {
255 state: forgejoChangeRequest(pr).state,
256 checks: forgejoChecks(statuses.items, pr.html_url),
257 };
258 },
259 ),
260 getChangeRequest: Effect.fn("ForgejoPullRequestProvider.getChangeRequest")(function* (input) {
261 const [pr, repo, viewer] = yield* Effect.all(
262 [getPull(input), getRepo(input), getViewer(input)],
263 { concurrency: 3 },
264 );
265 const statuses = yield* page(
266 {
267 ...input,
268 path: `${repoPath(input)}/statuses/${encodeURIComponent(pr.head.sha)}?sort=recentupdate`,
269 },
270 ForgejoStatus,
271 );
272 return {
273 ...forgejoChangeRequest(pr),
274 headSha: pr.head.sha,
275 body: pr.body ?? "",
276 changedFiles: pr.changed_files ?? 0,
277 reviewers: (pr.requested_reviewers ?? []).flatMap((user) => {
278 const actor = forgejoActor(user);
279 return actor ? [actor] : [];
280 }),
281 checks: forgejoChecks(statuses.items, pr.html_url),
282 baseComparison: !pr.merge_base
283 ? "unknown"
284 : pr.merge_base === pr.base.sha
285 ? "up-to-date"
286 : "behind",
287 viewerPermissions: permissions(repo, pr, viewer),
288 mergeCapabilities: {
289 merge: repo.allow_merge_commits ?? true,
290 squash: repo.allow_squash_merge ?? true,
291 rebase: repo.allow_rebase ?? true,
292 },
293 } satisfies ProviderChangeRequestDetail;
294 }),
295 getViewerPermissions: getPermissions,
296 getChangeRequestActivity: Effect.fn("ForgejoPullRequestProvider.getChangeRequestActivity")(
297 function* (input) {
298 const [comments, reviews, commits, reactions, viewer] = yield* Effect.all(
299 [
300 // Issue comments ignore page/limit; fetch this unpaginated endpoint once.
301 readArray({ ...input, path: `${issuePath(input)}/comments` }, ForgejoComment).pipe(
302 Effect.map((items) => ({
303 items: items.slice(0, 500),
304 truncated: items.length > 500,
305 })),
306 ),
307 page({ ...input, path: `${pullPath(input)}/reviews` }, ForgejoReview),
308 // Without these, each commit lists its files and a big merge outgrows the output limit.
309 page(
310 { ...input, path: `${pullPath(input)}/commits?files=false&verification=false` },
311 ForgejoCommit,
312 ),
313 page({ ...input, path: `${issuePath(input)}/reactions` }, ForgejoReaction),
314 getViewer(input),
315 ],
316 { concurrency: 5 },
317 );
318 const reviewComments = yield* Effect.forEach(
319 reviews.items.filter((review) => review.comments_count > 0 && review.state !== "PENDING"),
320 (review) =>
321 readArray(
322 { ...input, path: `${pullPath(input)}/reviews/${review.id}/comments` },
323 ForgejoReviewComment,
324 ),
325 { concurrency: 4 },
326 );
327 const allInline = reviewComments.flat();
328 const inline = allInline.slice(0, 500);
329 const entries = [
330 ...comments.items.map((comment) => ({
331 comment: forgejoComment(comment),
332 reactionId: String(comment.id),
333 })),
334 ...reviews.items
335 .filter((review) => review.state !== "PENDING" && review.state !== "REQUEST_REVIEW")
336 .map((review) => ({
337 comment: forgejoReview(review),
338 reactionId: reviewCommentId(review),
339 })),
340 ...inline.map((comment) => ({
341 comment: {
342 ...forgejoComment(comment),
343 kind: "review-comment" as const,
344 path: comment.path,
345 },
346 reactionId: String(comment.id),
347 })),
348 ];
349 const enriched = yield* Effect.forEach(
350 entries,
351 ({ comment, reactionId }) =>
352 (reactionId === undefined
353 ? Effect.succeed([])
354 : readArray(
355 { ...input, path: `${repoPath(input)}/issues/comments/${reactionId}/reactions` },
356 ForgejoReaction,
357 )
358 ).pipe(
359 Effect.map((rows) => ({ ...comment, reactions: forgejoReactions(rows, viewer) })),
360 ),
361 { concurrency: 4 },
362 );
363 const byId = new Map(enriched.map((comment) => [comment.id, comment]));
364 const timeline = enriched.toSorted((a, b) => a.createdAt.localeCompare(b.createdAt));
365 return {
366 comments: timeline,
367 commentCount: timeline.length,
368 commentsTruncated:
369 comments.truncated || reviews.truncated || allInline.length > inline.length,
370 reviewThreads: inline.map((comment) => ({
371 ...forgejoReviewThread(comment),
372 comments: [byId.get(String(comment.id)) ?? forgejoComment(comment)],
373 })),
374 commits: commits.items.map(forgejoCommit),
375 reactions: forgejoReactions(reactions.items, viewer),
376 };
377 },
378 ),
379 getFileRevisions: Effect.fn("ForgejoPullRequestProvider.getFileRevisions")(function* (input) {
380 const result = yield* request({ ...input, path: `${pullPath(input)}.diff` });
381 if (result.stdoutTruncated) {
382 return yield* failure("getFileRevisions", "Forgejo diff exceeded the output limit.");
383 }
384 const revisions = new Map(parseDiffFileRevisions(result.stdout));
385 for (const path of input.paths) {
386 if (!revisions.has(path)) revisions.set(path, "");
387 }
388 return { revisions, complete: true };
389 }),
390 getDiff: (input) =>
391 request({
392 ...input,
393 path: input.commit
394 ? `${repoPath(input)}/git/commits/${encodeURIComponent(input.commit)}.diff`
395 : `${pullPath(input)}.diff`,
396 }).pipe(
397 Effect.map((result) => ({
398 patch: result.stdout,
399 truncated: result.stdoutTruncated,
400 nextCursor: null,
401 })),
402 ),
403 getDiffFileContents: Effect.fn("ForgejoPullRequestProvider.getDiffFileContents")(
404 function* (input) {
405 const pr = yield* getPull(input);
406 const commit = input.commit
407 ? yield* read(
408 {
409 ...input,
410 path: `${repoPath(input)}/git/commits/${encodeURIComponent(input.commit)}?files=false&verification=false`,
411 },
412 ForgejoCommit,
413 )
414 : null;
415 const oldRef = commit ? commit.parents[0]?.sha : pr.merge_base || pr.base.sha;
416 const newRef = input.commit ?? pr.head.sha;
417 const content = (repository: string, ref: string, path: string) =>
418 read(
419 {
420 ...input,
421 repository,
422 path: `${repoPath({ ...input, repository })}/contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=${encodeURIComponent(ref)}`,
423 },
424 Schema.Struct({ content: Schema.String, encoding: Schema.Literal("base64") }),
425 ).pipe(Effect.map((file) => Buffer.from(file.content, "base64").toString("utf8")));
426 const [oldContents, newContents] = yield* Effect.all(
427 [
428 input.changeType === "new" || !oldRef
429 ? Effect.succeed("")
430 : content(input.repository, oldRef, input.oldPath),
431 input.changeType === "deleted"
432 ? Effect.succeed("")
433 : content(pr.head.repo?.full_name ?? input.repository, newRef, input.newPath),
434 ],
435 { concurrency: 2 },
436 );
437 return { oldContents, newContents };
438 },
439 ),
440 runAction: (input) => {
441 switch (input.action) {
442 case "merge":
443 return write({
444 ...input,
445 path: `${pullPath(input)}/merge`,
446 method: "POST",
447 body: { Do: input.mergeMethod ?? "merge" },
448 });
449 case "close":
450 case "reopen":
451 return write({
452 ...input,
453 path: pullPath(input),
454 method: "PATCH",
455 body: { state: input.action === "close" ? "closed" : "open" },
456 });
457 case "update-branch":
458 return write({
459 ...input,
460 path: `${pullPath(input)}/update?style=${input.updateMethod ?? "merge"}`,
461 method: "POST",
462 });
463 default:
464 return unsupported(input.action);
465 }
466 },
467 updateChangeRequest: (input) =>
468 write({
469 ...input,
470 path: pullPath(input),
471 method: "PATCH",
472 body: {
473 ...(input.title === undefined ? {} : { title: input.title }),
474 ...(input.body === undefined ? {} : { body: input.body }),
475 },
476 }),
477 comment: (input) =>
478 write({
479 ...input,
480 path: `${issuePath(input)}/comments`,
481 method: "POST",
482 body: { body: input.body },
483 }),
484 updateComment: (input) =>
485 write({
486 ...input,
487 path: `${repoPath(input)}/issues/comments/${encodeURIComponent(input.commentId)}`,
488 method: "PATCH",
489 body: { body: input.body },
490 }),
491 submitReview: Effect.fn("ForgejoPullRequestProvider.submitReview")(function* (input) {
492 const pr = yield* getPull(input);
493 yield* write({
494 ...input,
495 path: `${pullPath(input)}/reviews`,
496 method: "POST",
497 body: {
498 event:
499 input.verdict === "approve"
500 ? "APPROVED"
501 : input.verdict === "request-changes"
502 ? "REQUEST_CHANGES"
503 : "COMMENT",
504 body: input.body,
505 commit_id: pr.head.sha,
506 comments: input.comments.map((comment) => {
507 const position = comment.position;
508 const old =
509 position.kind === "deleted" ||
510 (position.kind === "context" && position.side === "left");
511 return {
512 path: old ? (comment.oldPath ?? comment.path) : comment.path,
513 body: comment.body,
514 old_position: old ? position.oldLine : 0,
515 new_position: old ? 0 : position.newLine,
516 };
517 }),
518 },
519 });
520 }),
521 listReviewerCandidates: Effect.fn("ForgejoPullRequestProvider.listReviewerCandidates")(
522 function* (input) {
523 const [pr, users] = yield* Effect.all(
524 [getPull(input), page({ ...input, path: `${repoPath(input)}/assignees` }, ForgejoUser)],
525 { concurrency: 2 },
526 );
527 return {
528 candidates: users.items
529 .filter((user) => user.login !== pr.user?.login)
530 .flatMap((user) => {
531 const actor = forgejoActor(user);
532 return actor
533 ? [
534 {
535 ...actor,
536 id: user.login,
537 kind: "user" as const,
538 isRequested:
539 pr.requested_reviewers?.some((reviewer) => reviewer.login === user.login) ??
540 false,
541 },
542 ]
543 : [];
544 }),
545 truncated: users.truncated,
546 };
547 },
548 ),
549 setReviewerRequest: (input) =>
550 write({
551 ...input,
552 path: `${pullPath(input)}/requested_reviewers`,
553 method: input.requested ? "POST" : "DELETE",
554 body: { reviewers: input.reviewers.map((reviewer) => reviewer.id) },
555 }),
556 listLabelCandidates: Effect.fn("ForgejoPullRequestProvider.listLabelCandidates")(
557 function* (input) {
558 const [pr, labels] = yield* Effect.all(
559 [getPull(input), page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel)],
560 { concurrency: 2 },
561 );
562 return {
563 candidates: labels.items.map((label) => ({
564 name: label.name,
565 color: label.color ?? null,
566 description: label.description ?? null,
567 isApplied: pr.labels?.some((applied) => applied.id === label.id) ?? false,
568 })),
569 truncated: labels.truncated,
570 };
571 },
572 ),
573 setLabels: Effect.fn("ForgejoPullRequestProvider.setLabels")(function* (input) {
574 const labels = yield* page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel);
575 const selected = labels.items.filter((label) => input.labels.includes(label.name));
576 if (selected.length !== input.labels.length)
577 return yield* failure("setLabels", "One or more requested labels could not be found.");
578 if (input.applied)
579 yield* write({
580 ...input,
581 path: `${issuePath(input)}/labels`,
582 method: "POST",
583 body: { labels: selected.map((label) => label.id) },
584 });
585 else
586 yield* Effect.forEach(
587 selected,
588 (label) =>
589 write({ ...input, path: `${issuePath(input)}/labels/${label.id}`, method: "DELETE" }),
590 { concurrency: 1 },
591 );
592 }),
593 setReaction: Effect.fn("ForgejoPullRequestProvider.setReaction")(function* (input) {
594 let commentId = input.subjectId;
595 if (commentId?.startsWith("review:")) {
596 const reviewId = /^review:([1-9]\d*)$/.exec(commentId)?.[1];
597 if (!reviewId) return yield* failure("setReaction", "Invalid Forgejo review ID.");
598 const review = yield* read(
599 { ...input, path: `${pullPath(input)}/reviews/${reviewId}` },
600 ForgejoReview,
601 );
602 commentId = reviewCommentId(review);
603 if (!commentId)
604 return yield* failure(
605 "setReaction",
606 "Forgejo did not return a comment ID for this review.",
607 );
608 }
609 if (commentId && !/^[1-9]\d*$/.test(commentId))
610 return yield* failure("setReaction", "Invalid Forgejo comment ID.");
611 yield* write({
612 ...input,
613 path: commentId
614 ? `${repoPath(input)}/issues/comments/${commentId}/reactions`
615 : `${issuePath(input)}/reactions`,
616 method: input.reacted ? "POST" : "DELETE",
617 body: { content: FORGEJO_REACTIONS[input.content] },
618 });
619 }),
620 replyToThread: () => unsupported("thread replies"),
621 setThreadResolution: () => unsupported("thread resolution"),
622 };
623 return provider;
624});