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

ForgejoPullRequestProvider.ts

610 lines23.0 KB

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