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

ForgejoPullRequestProvider.ts

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