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

ForgejoPullRequestProvider.ts

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