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

ForgejoPullRequestProvider.ts

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