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 { state: forgejoChangeRequest(pr).state, checks: forgejoChecks(statuses.items) };
255 },
256 ),
257 getChangeRequest: Effect.fn("ForgejoPullRequestProvider.getChangeRequest")(function* (input) {
258 const [pr, repo, viewer] = yield* Effect.all(
259 [getPull(input), getRepo(input), getViewer(input)],
260 { concurrency: 3 },
261 );
262 const statuses = yield* page(
263 {
264 ...input,
265 path: `${repoPath(input)}/statuses/${encodeURIComponent(pr.head.sha)}?sort=recentupdate`,
266 },
267 ForgejoStatus,
268 );
269 return {
270 ...forgejoChangeRequest(pr),
271 body: pr.body ?? "",
272 changedFiles: pr.changed_files ?? 0,
273 reviewers: (pr.requested_reviewers ?? []).flatMap((user) => {
274 const actor = forgejoActor(user);
275 return actor ? [actor] : [];
276 }),
277 checks: forgejoChecks(statuses.items),
278 baseComparison: !pr.merge_base
279 ? "unknown"
280 : pr.merge_base === pr.base.sha
281 ? "up-to-date"
282 : "behind",
283 viewerPermissions: permissions(repo, pr, viewer),
284 mergeCapabilities: {
285 merge: repo.allow_merge_commits ?? true,
286 squash: repo.allow_squash_merge ?? true,
287 rebase: repo.allow_rebase ?? true,
288 },
289 } satisfies ProviderChangeRequestDetail;
290 }),
291 getViewerPermissions: getPermissions,
292 getChangeRequestActivity: Effect.fn("ForgejoPullRequestProvider.getChangeRequestActivity")(
293 function* (input) {
294 const [comments, reviews, commits, reactions, viewer] = yield* Effect.all(
295 [
296 // Issue comments ignore page/limit; fetch this unpaginated endpoint once.
297 readArray({ ...input, path: `${issuePath(input)}/comments` }, ForgejoComment).pipe(
298 Effect.map((items) => ({
299 items: items.slice(0, 500),
300 truncated: items.length > 500,
301 })),
302 ),
303 page({ ...input, path: `${pullPath(input)}/reviews` }, ForgejoReview),
304 page({ ...input, path: `${pullPath(input)}/commits` }, ForgejoCommit),
305 page({ ...input, path: `${issuePath(input)}/reactions` }, ForgejoReaction),
306 getViewer(input),
307 ],
308 { concurrency: 5 },
309 );
310 const reviewComments = yield* Effect.forEach(
311 reviews.items.filter((review) => review.comments_count > 0 && review.state !== "PENDING"),
312 (review) =>
313 readArray(
314 { ...input, path: `${pullPath(input)}/reviews/${review.id}/comments` },
315 ForgejoReviewComment,
316 ),
317 { concurrency: 4 },
318 );
319 const allInline = reviewComments.flat();
320 const inline = allInline.slice(0, 500);
321 const entries = [
322 ...comments.items.map((comment) => ({
323 comment: forgejoComment(comment),
324 reactionId: String(comment.id),
325 })),
326 ...reviews.items
327 .filter((review) => review.state !== "PENDING" && review.state !== "REQUEST_REVIEW")
328 .map((review) => ({
329 comment: forgejoReview(review),
330 reactionId: reviewCommentId(review),
331 })),
332 ...inline.map((comment) => ({
333 comment: {
334 ...forgejoComment(comment),
335 kind: "review-comment" as const,
336 path: comment.path,
337 },
338 reactionId: String(comment.id),
339 })),
340 ];
341 const enriched = yield* Effect.forEach(
342 entries,
343 ({ comment, reactionId }) =>
344 (reactionId === undefined
345 ? Effect.succeed([])
346 : readArray(
347 { ...input, path: `${repoPath(input)}/issues/comments/${reactionId}/reactions` },
348 ForgejoReaction,
349 )
350 ).pipe(
351 Effect.map((rows) => ({ ...comment, reactions: forgejoReactions(rows, viewer) })),
352 ),
353 { concurrency: 4 },
354 );
355 const byId = new Map(enriched.map((comment) => [comment.id, comment]));
356 const timeline = enriched.toSorted((a, b) => a.createdAt.localeCompare(b.createdAt));
357 return {
358 comments: timeline,
359 commentCount: timeline.length,
360 commentsTruncated:
361 comments.truncated || reviews.truncated || allInline.length > inline.length,
362 reviewThreads: inline.map((comment) => ({
363 ...forgejoReviewThread(comment),
364 comments: [byId.get(String(comment.id)) ?? forgejoComment(comment)],
365 })),
366 commits: commits.items.map(forgejoCommit),
367 reactions: forgejoReactions(reactions.items, viewer),
368 };
369 },
370 ),
371 getFileRevisions: Effect.fn("ForgejoPullRequestProvider.getFileRevisions")(function* (input) {
372 const result = yield* request({ ...input, path: `${pullPath(input)}.diff` });
373 if (result.stdoutTruncated) {
374 return yield* failure("getFileRevisions", "Forgejo diff exceeded the output limit.");
375 }
376 const revisions = new Map(parseDiffFileRevisions(result.stdout));
377 for (const path of input.paths) {
378 if (!revisions.has(path)) revisions.set(path, "");
379 }
380 return { revisions, complete: true };
381 }),
382 getDiff: (input) =>
383 request({
384 ...input,
385 path: input.commit
386 ? `${repoPath(input)}/git/commits/${encodeURIComponent(input.commit)}.diff`
387 : `${pullPath(input)}.diff`,
388 }).pipe(
389 Effect.map((result) => ({
390 patch: result.stdout,
391 truncated: result.stdoutTruncated,
392 nextCursor: null,
393 })),
394 ),
395 getDiffFileContents: Effect.fn("ForgejoPullRequestProvider.getDiffFileContents")(
396 function* (input) {
397 const pr = yield* getPull(input);
398 const commit = input.commit
399 ? yield* read(
400 {
401 ...input,
402 path: `${repoPath(input)}/git/commits/${encodeURIComponent(input.commit)}`,
403 },
404 ForgejoCommit,
405 )
406 : null;
407 const oldRef = commit ? commit.parents[0]?.sha : pr.merge_base || pr.base.sha;
408 const newRef = input.commit ?? pr.head.sha;
409 const content = (repository: string, ref: string, path: string) =>
410 read(
411 {
412 ...input,
413 repository,
414 path: `${repoPath({ ...input, repository })}/contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=${encodeURIComponent(ref)}`,
415 },
416 Schema.Struct({ content: Schema.String, encoding: Schema.Literal("base64") }),
417 ).pipe(Effect.map((file) => Buffer.from(file.content, "base64").toString("utf8")));
418 const [oldContents, newContents] = yield* Effect.all(
419 [
420 input.changeType === "new" || !oldRef
421 ? Effect.succeed("")
422 : content(input.repository, oldRef, input.oldPath),
423 input.changeType === "deleted"
424 ? Effect.succeed("")
425 : content(pr.head.repo?.full_name ?? input.repository, newRef, input.newPath),
426 ],
427 { concurrency: 2 },
428 );
429 return { oldContents, newContents };
430 },
431 ),
432 runAction: (input) => {
433 switch (input.action) {
434 case "merge":
435 return write({
436 ...input,
437 path: `${pullPath(input)}/merge`,
438 method: "POST",
439 body: { Do: input.mergeMethod ?? "merge" },
440 });
441 case "close":
442 case "reopen":
443 return write({
444 ...input,
445 path: pullPath(input),
446 method: "PATCH",
447 body: { state: input.action === "close" ? "closed" : "open" },
448 });
449 case "update-branch":
450 return write({
451 ...input,
452 path: `${pullPath(input)}/update?style=${input.updateMethod ?? "merge"}`,
453 method: "POST",
454 });
455 default:
456 return unsupported(input.action);
457 }
458 },
459 updateChangeRequest: (input) =>
460 write({
461 ...input,
462 path: pullPath(input),
463 method: "PATCH",
464 body: {
465 ...(input.title === undefined ? {} : { title: input.title }),
466 ...(input.body === undefined ? {} : { body: input.body }),
467 },
468 }),
469 comment: (input) =>
470 write({
471 ...input,
472 path: `${issuePath(input)}/comments`,
473 method: "POST",
474 body: { body: input.body },
475 }),
476 updateComment: (input) =>
477 write({
478 ...input,
479 path: `${repoPath(input)}/issues/comments/${encodeURIComponent(input.commentId)}`,
480 method: "PATCH",
481 body: { body: input.body },
482 }),
483 submitReview: Effect.fn("ForgejoPullRequestProvider.submitReview")(function* (input) {
484 const pr = yield* getPull(input);
485 yield* write({
486 ...input,
487 path: `${pullPath(input)}/reviews`,
488 method: "POST",
489 body: {
490 event:
491 input.verdict === "approve"
492 ? "APPROVED"
493 : input.verdict === "request-changes"
494 ? "REQUEST_CHANGES"
495 : "COMMENT",
496 body: input.body,
497 commit_id: pr.head.sha,
498 comments: input.comments.map((comment) => {
499 const position = comment.position;
500 const old =
501 position.kind === "deleted" ||
502 (position.kind === "context" && position.side === "left");
503 return {
504 path: old ? (comment.oldPath ?? comment.path) : comment.path,
505 body: comment.body,
506 old_position: old ? position.oldLine : 0,
507 new_position: old ? 0 : position.newLine,
508 };
509 }),
510 },
511 });
512 }),
513 listReviewerCandidates: Effect.fn("ForgejoPullRequestProvider.listReviewerCandidates")(
514 function* (input) {
515 const [pr, users] = yield* Effect.all(
516 [getPull(input), page({ ...input, path: `${repoPath(input)}/assignees` }, ForgejoUser)],
517 { concurrency: 2 },
518 );
519 return {
520 candidates: users.items
521 .filter((user) => user.login !== pr.user?.login)
522 .flatMap((user) => {
523 const actor = forgejoActor(user);
524 return actor
525 ? [
526 {
527 ...actor,
528 id: user.login,
529 kind: "user" as const,
530 isRequested:
531 pr.requested_reviewers?.some((reviewer) => reviewer.login === user.login) ??
532 false,
533 },
534 ]
535 : [];
536 }),
537 truncated: users.truncated,
538 };
539 },
540 ),
541 setReviewerRequest: (input) =>
542 write({
543 ...input,
544 path: `${pullPath(input)}/requested_reviewers`,
545 method: input.requested ? "POST" : "DELETE",
546 body: { reviewers: input.reviewers.map((reviewer) => reviewer.id) },
547 }),
548 listLabelCandidates: Effect.fn("ForgejoPullRequestProvider.listLabelCandidates")(
549 function* (input) {
550 const [pr, labels] = yield* Effect.all(
551 [getPull(input), page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel)],
552 { concurrency: 2 },
553 );
554 return {
555 candidates: labels.items.map((label) => ({
556 name: label.name,
557 color: label.color ?? null,
558 description: label.description ?? null,
559 isApplied: pr.labels?.some((applied) => applied.id === label.id) ?? false,
560 })),
561 truncated: labels.truncated,
562 };
563 },
564 ),
565 setLabels: Effect.fn("ForgejoPullRequestProvider.setLabels")(function* (input) {
566 const labels = yield* page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel);
567 const selected = labels.items.filter((label) => input.labels.includes(label.name));
568 if (selected.length !== input.labels.length)
569 return yield* failure("setLabels", "One or more requested labels could not be found.");
570 if (input.applied)
571 yield* write({
572 ...input,
573 path: `${issuePath(input)}/labels`,
574 method: "POST",
575 body: { labels: selected.map((label) => label.id) },
576 });
577 else
578 yield* Effect.forEach(
579 selected,
580 (label) =>
581 write({ ...input, path: `${issuePath(input)}/labels/${label.id}`, method: "DELETE" }),
582 { concurrency: 1 },
583 );
584 }),
585 setReaction: Effect.fn("ForgejoPullRequestProvider.setReaction")(function* (input) {
586 let commentId = input.subjectId;
587 if (commentId?.startsWith("review:")) {
588 const reviewId = /^review:([1-9]\d*)$/.exec(commentId)?.[1];
589 if (!reviewId) return yield* failure("setReaction", "Invalid Forgejo review ID.");
590 const review = yield* read(
591 { ...input, path: `${pullPath(input)}/reviews/${reviewId}` },
592 ForgejoReview,
593 );
594 commentId = reviewCommentId(review);
595 if (!commentId)
596 return yield* failure(
597 "setReaction",
598 "Forgejo did not return a comment ID for this review.",
599 );
600 }
601 if (commentId && !/^[1-9]\d*$/.test(commentId))
602 return yield* failure("setReaction", "Invalid Forgejo comment ID.");
603 yield* write({
604 ...input,
605 path: commentId
606 ? `${repoPath(input)}/issues/comments/${commentId}/reactions`
607 : `${issuePath(input)}/reactions`,
608 method: input.reacted ? "POST" : "DELETE",
609 body: { content: FORGEJO_REACTIONS[input.content] },
610 });
611 }),
612 replyToThread: () => unsupported("thread replies"),
613 setThreadResolution: () => unsupported("thread resolution"),
614 };
615 return provider;
616});