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

ForgejoPullRequestProvider.ts

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