The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { resolvePullRequestAuthorFilter, SourceControlProviderKind } from "@t3tools/contracts"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import * as Schema from "effect/Schema"; |
| 4 | import * as Result from "effect/Result"; |
| 5 | import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts"; |
| 6 | import { decodeJsonResult } from "@t3tools/shared/schemaJson"; |
| 7 | import * as ForgejoCli from "./ForgejoCli.ts"; |
| 8 | import { parseDiffFileRevisions } from "@t3tools/source-control-core/server/diffFileRevisions"; |
| 9 | import { |
| 10 | PullRequestProviderError, |
| 11 | type ProviderChangeRequestDetail, |
| 12 | type ProviderChangeRequestSummary, |
| 13 | type ProviderRepositoryRef, |
| 14 | type PullRequestProviderApi, |
| 15 | } from "@t3tools/source-control-core/server/PullRequestProvider"; |
| 16 | import { |
| 17 | ForgejoPullRequest, |
| 18 | ForgejoRepository, |
| 19 | ForgejoUser, |
| 20 | ForgejoComment, |
| 21 | ForgejoReview, |
| 22 | ForgejoReviewComment, |
| 23 | ForgejoCommit, |
| 24 | ForgejoStatus, |
| 25 | ForgejoLabel, |
| 26 | ForgejoReaction, |
| 27 | FORGEJO_REACTIONS, |
| 28 | forgejoChangeRequest, |
| 29 | forgejoActor, |
| 30 | forgejoComment, |
| 31 | forgejoReview, |
| 32 | forgejoReviewThread, |
| 33 | forgejoCommit, |
| 34 | forgejoChecks, |
| 35 | forgejoReactions, |
| 36 | } from "./forgejoPullRequestJson.ts"; |
| 37 | import { ForgejoBranchStatusChecks, markRequiredForgejoChecks } from "./forgejoRequiredChecks.ts"; |
| 38 | import { definition } from "../shared/definition.ts"; |
| 39 | |
| 40 | const isForgejoCliError = Schema.is(ForgejoCli.ForgejoCliError); |
| 41 | |
| 42 | const CAPABILITIES: PullRequestCapabilities = { |
| 43 | diff: true, |
| 44 | viewedFiles: "environment", |
| 45 | comment: true, |
| 46 | actions: [...definition.changeRequestActions], |
| 47 | mergeMethods: ["merge", "squash", "rebase", "fast-forward"], |
| 48 | updateMethods: ["merge", "rebase"], |
| 49 | search: false, |
| 50 | reactions: true, |
| 51 | mentions: true, |
| 52 | referenceSigils: [], |
| 53 | labels: true, |
| 54 | // Forgejo's public API has no thread replies/resolution or draft conversion endpoint. |
| 55 | review: { |
| 56 | inlineComment: true, |
| 57 | reply: false, |
| 58 | resolve: false, |
| 59 | verdicts: ["comment", "approve", "request-changes"], |
| 60 | }, |
| 61 | reviewers: { request: true, listCandidates: true, searchCandidates: false }, |
| 62 | edit: { changeRequest: true, comment: true }, |
| 63 | }; |
| 64 | const USER_SEARCH_LIMIT = 50; |
| 65 | const ForgejoUserSearch = Schema.Struct({ |
| 66 | data: Schema.optional(Schema.NullOr(Schema.Array(ForgejoUser))), |
| 67 | }); |
| 68 | |
| 69 | const UNAVAILABLE_REQUIREMENT = { |
| 70 | missing: |
| 71 | "Install Forgejo CLI (`fj` 0.6 or later) from https://codeberg.org/forgejo-contrib/forgejo-cli or Gitea CLI (`tea` 0.16 or later) from https://gitea.com/gitea/tea to browse Forgejo pull requests.", |
| 72 | unauthenticated: |
| 73 | "Authenticate your Forgejo or Gitea server with `fj --host <server-url> auth add-token` on the T3 Code server. If fj is missing or unconfigured for that server, use `tea login add`. A configured fj account must be repaired with fj.", |
| 74 | }; |
| 75 | |
| 76 | const repoPath = (input: ProviderRepositoryRef) => |
| 77 | `repos/${input.repository.split("/").map(encodeURIComponent).join("/")}`; |
| 78 | const pullPath = (input: ProviderRepositoryRef & { readonly number: number }) => |
| 79 | `${repoPath(input)}/pulls/${input.number}`; |
| 80 | const issuePath = (input: ProviderRepositoryRef & { readonly number: number }) => |
| 81 | `${repoPath(input)}/issues/${input.number}`; |
| 82 | // Review IDs differ from the issue-comment IDs used by Forgejo's reactions API. |
| 83 | const reviewCommentId = (review: typeof ForgejoReview.Type) => |
| 84 | /#issuecomment-([1-9]\d*)$/.exec(review.html_url ?? "")?.[1]; |
| 85 | |
| 86 | const decodePullRequest = decodeJsonResult(ForgejoPullRequest); |
| 87 | |
| 88 | /** Only the PATCH reply carries the pull request; merge and update reply with an empty body. */ |
| 89 | function forgejoActionSummary(stdout: string): ProviderChangeRequestSummary | undefined { |
| 90 | const decoded = decodePullRequest(stdout); |
| 91 | if (Result.isFailure(decoded)) return undefined; |
| 92 | const pr = decoded.success; |
| 93 | // A state PATCH does not recompute conflicts, so "unknown" there would hide a known conflict. |
| 94 | const { mergeability, ...summary } = forgejoChangeRequest(pr); |
| 95 | return { |
| 96 | ...summary, |
| 97 | ...(mergeability === "unknown" ? {} : { mergeability }), |
| 98 | additions: pr.additions ?? undefined, |
| 99 | deletions: pr.deletions ?? undefined, |
| 100 | ...(pr.head.sha.trim() === "" ? {} : { headSha: pr.head.sha }), |
| 101 | }; |
| 102 | } |
| 103 | |
| 104 | export const make = Effect.gen(function* () { |
| 105 | const cli = yield* ForgejoCli.ForgejoCli; |
| 106 | const failure = (operation: string, detail: string, cause?: unknown) => |
| 107 | new PullRequestProviderError({ |
| 108 | provider: SourceControlProviderKind.make("forgejo"), |
| 109 | operation, |
| 110 | reason: "failed", |
| 111 | detail, |
| 112 | ...(cause === undefined ? {} : { cause }), |
| 113 | }); |
| 114 | const request = (input: ForgejoCli.ForgejoApiInput) => |
| 115 | cli.api(input).pipe( |
| 116 | Effect.mapError( |
| 117 | (error) => |
| 118 | new PullRequestProviderError({ |
| 119 | provider: SourceControlProviderKind.make("forgejo"), |
| 120 | operation: input.path, |
| 121 | detail: error.detail, |
| 122 | cause: error, |
| 123 | reason: |
| 124 | error.reason === "missing-cli" |
| 125 | ? "missing-tool" |
| 126 | : error.reason === "authentication" |
| 127 | ? "unauthenticated" |
| 128 | : error.reason === "rate-limit" |
| 129 | ? "rate-limited" |
| 130 | : error.reason === "not-found" |
| 131 | ? "not-found" |
| 132 | : "failed", |
| 133 | }), |
| 134 | ), |
| 135 | ); |
| 136 | /** A response, and whether its `link` header points at a further page. */ |
| 137 | const readLinked = Effect.fn("ForgejoPullRequestProvider.readLinked")(function* <A>( |
| 138 | input: ForgejoCli.ForgejoApiInput, |
| 139 | schema: Schema.Codec<A, unknown, never, never>, |
| 140 | ) { |
| 141 | const result = yield* request(input); |
| 142 | if (result.stdoutTruncated) |
| 143 | return yield* failure(input.path, "Forgejo response exceeded the output limit."); |
| 144 | const decoded = decodeJsonResult(schema)(result.stdout); |
| 145 | if (Result.isFailure(decoded)) |
| 146 | return yield* failure(input.path, "Forgejo returned an invalid response.", decoded.failure); |
| 147 | const links = /^link:\s*(.*)$/im.exec(result.stderr)?.[1]; |
| 148 | return { value: decoded.success, next: links !== undefined && /rel="?next"?/i.test(links) }; |
| 149 | }); |
| 150 | const read = <A>( |
| 151 | input: ForgejoCli.ForgejoApiInput, |
| 152 | schema: Schema.Codec<A, unknown, never, never>, |
| 153 | ) => readLinked(input, schema).pipe(Effect.map(({ value }) => value)); |
| 154 | const readArray = <A>( |
| 155 | input: ForgejoCli.ForgejoApiInput, |
| 156 | schema: Schema.Codec<A, unknown, never, never>, |
| 157 | ) => read(input, Schema.NullOr(Schema.Array(schema))).pipe(Effect.map((rows) => rows ?? [])); |
| 158 | const readPage = Effect.fn("ForgejoPullRequestProvider.readPage")(function* <A>( |
| 159 | input: ForgejoCli.ForgejoApiInput, |
| 160 | schema: Schema.Codec<A, unknown, never, never>, |
| 161 | index: number, |
| 162 | ) { |
| 163 | const result = yield* request({ |
| 164 | ...input, |
| 165 | path: `${input.path}${input.path.includes("?") ? "&" : "?"}limit=50&page=${index}`, |
| 166 | }); |
| 167 | if (result.stdoutTruncated) |
| 168 | return yield* failure(input.path, "Forgejo response exceeded the output limit."); |
| 169 | const decoded = decodeJsonResult(Schema.NullOr(Schema.Array(schema)))(result.stdout); |
| 170 | if (Result.isFailure(decoded)) |
| 171 | return yield* failure(input.path, "Forgejo returned an invalid response.", decoded.failure); |
| 172 | const rows = decoded.success ?? []; |
| 173 | const links = /^link:\s*(.*)$/im.exec(result.stderr)?.[1]; |
| 174 | return { |
| 175 | rows, |
| 176 | more: rows.length > 0 && (links === undefined || /rel="?next"?/i.test(links)), |
| 177 | }; |
| 178 | }); |
| 179 | // Forgejo's default page limit is 50. |
| 180 | const page = Effect.fn("ForgejoPullRequestProvider.page")(function* <A>( |
| 181 | input: ForgejoCli.ForgejoApiInput, |
| 182 | schema: Schema.Codec<A, unknown, never, never>, |
| 183 | limit = 500, |
| 184 | ) { |
| 185 | const items: A[] = []; |
| 186 | for (let index = 1; items.length < limit; index++) { |
| 187 | const { rows, more } = yield* readPage(input, schema, index); |
| 188 | items.push(...rows); |
| 189 | if (!more) return { items, truncated: false }; |
| 190 | } |
| 191 | return { items, truncated: true }; |
| 192 | }); |
| 193 | const write = (input: ForgejoCli.ForgejoApiInput) => request(input).pipe(Effect.asVoid); |
| 194 | const getPull = (input: ProviderRepositoryRef & { readonly number: number }) => |
| 195 | read( |
| 196 | { |
| 197 | cwd: input.cwd, |
| 198 | repository: input.repository, |
| 199 | host: input.host, |
| 200 | path: pullPath(input), |
| 201 | }, |
| 202 | ForgejoPullRequest, |
| 203 | ); |
| 204 | const getRepo = (input: ProviderRepositoryRef) => |
| 205 | read({ ...input, path: repoPath(input) }, ForgejoRepository); |
| 206 | const getViewer = (input: { |
| 207 | readonly cwd: string; |
| 208 | readonly repository?: string; |
| 209 | readonly host?: string; |
| 210 | }) => read({ ...input, path: "user" }, ForgejoUser).pipe(Effect.map((user) => user.login)); |
| 211 | const permissions = ( |
| 212 | repo: typeof ForgejoRepository.Type, |
| 213 | pr: typeof ForgejoPullRequest.Type, |
| 214 | viewer: string, |
| 215 | ): PullRequestViewerPermissions => { |
| 216 | const canWrite = repo.permissions?.push ?? false; |
| 217 | const canEdit = canWrite || pr.user?.login === viewer; |
| 218 | const active = !repo.archived; |
| 219 | return { |
| 220 | actions: active |
| 221 | ? CAPABILITIES.actions.filter((action) => |
| 222 | action === "merge" || action === "update-branch" ? canWrite : canEdit, |
| 223 | ) |
| 224 | : [], |
| 225 | comment: active && (!pr.is_locked || canWrite), |
| 226 | resolve: false, |
| 227 | verdicts: active |
| 228 | ? pr.user?.login === viewer |
| 229 | ? ["comment"] |
| 230 | : CAPABILITIES.review.verdicts |
| 231 | : [], |
| 232 | requestReviewers: active && canEdit, |
| 233 | labels: active && canWrite, |
| 234 | updateMethods: |
| 235 | active && canWrite ? (repo.allow_rebase_update ? ["merge", "rebase"] : ["merge"]) : [], |
| 236 | }; |
| 237 | }; |
| 238 | const getPermissions = Effect.fn("ForgejoPullRequestProvider.getPermissions")(function* ( |
| 239 | input: ProviderRepositoryRef & { readonly number: number }, |
| 240 | ) { |
| 241 | const [repo, pr, viewer] = yield* Effect.all( |
| 242 | [getRepo(input), getPull(input), getViewer(input)], |
| 243 | { concurrency: 3 }, |
| 244 | ); |
| 245 | return permissions(repo, pr, viewer); |
| 246 | }); |
| 247 | const readChecks = Effect.fn("ForgejoPullRequestProvider.readChecks")(function* ( |
| 248 | input: ProviderRepositoryRef, |
| 249 | pr: typeof ForgejoPullRequest.Type, |
| 250 | ) { |
| 251 | const branch = read( |
| 252 | { |
| 253 | ...input, |
| 254 | path: `${repoPath(input)}/branches/${pr.base.ref.split("/").map(encodeURIComponent).join("/")}`, |
| 255 | }, |
| 256 | ForgejoBranchStatusChecks, |
| 257 | ).pipe( |
| 258 | Effect.catchTags({ |
| 259 | PullRequestProviderError: (error) => { |
| 260 | if ( |
| 261 | isForgejoCliError(error.cause) && |
| 262 | (error.cause.reason === "forbidden" || error.cause.reason === "not-found") |
| 263 | ) { |
| 264 | return Effect.succeed({}); |
| 265 | } |
| 266 | return Effect.fail(error); |
| 267 | }, |
| 268 | }), |
| 269 | ); |
| 270 | const [statuses, policy] = yield* Effect.all( |
| 271 | [ |
| 272 | page( |
| 273 | { |
| 274 | ...input, |
| 275 | path: `${repoPath(input)}/statuses/${encodeURIComponent(pr.head.sha)}?sort=recentupdate`, |
| 276 | }, |
| 277 | ForgejoStatus, |
| 278 | ), |
| 279 | branch, |
| 280 | ], |
| 281 | { concurrency: 2 }, |
| 282 | ); |
| 283 | return markRequiredForgejoChecks(forgejoChecks(statuses.items, pr.html_url), policy); |
| 284 | }); |
| 285 | const unsupported = (operation: string) => |
| 286 | Effect.fail(failure(operation, `Forgejo does not expose ${operation} through its API.`)); |
| 287 | const provider: PullRequestProviderApi = { |
| 288 | kind: SourceControlProviderKind.make("forgejo"), |
| 289 | capabilities: CAPABILITIES, |
| 290 | unavailableRequirement: UNAVAILABLE_REQUIREMENT, |
| 291 | readsPublicHostWithoutCheckout: true, |
| 292 | getViewer, |
| 293 | listChangeRequests: Effect.fn("ForgejoPullRequestProvider.listChangeRequests")( |
| 294 | function* (input) { |
| 295 | const offset = input.cursor?.delivered ?? 0; |
| 296 | const items: ReturnType<typeof forgejoChangeRequest>[] = []; |
| 297 | const state = input.state === "merged" ? "closed" : input.state; |
| 298 | const params = new URLSearchParams({ state, sort: "recentupdate" }); |
| 299 | const filters = input.filters; |
| 300 | // Several `labels` match a pull request holding any of them but list it once per label it |
| 301 | // holds, which would throw the row offset off, so one required label is all Forgejo is |
| 302 | // asked for. The service narrows the rest. |
| 303 | const single = filters?.labels?.find((group) => group.length === 1)?.[0]; |
| 304 | if (single !== undefined) { |
| 305 | const labels = yield* page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel); |
| 306 | const label = labels.items.find( |
| 307 | (candidate) => candidate.name.toLowerCase() === single.trim().toLowerCase(), |
| 308 | ); |
| 309 | if (label !== undefined) params.set("labels", String(label.id)); |
| 310 | } |
| 311 | if (filters?.author !== undefined) |
| 312 | params.set("poster", resolvePullRequestAuthorFilter(filters.author, input.viewer)); |
| 313 | const query = { ...input, path: `${repoPath(input)}/pulls?${params}` }; |
| 314 | // Self-hosted servers may cap pages below 50. Establish their actual page size before |
| 315 | // translating the service's row offset into an API page number. |
| 316 | const first = yield* readPage(query, Schema.NullOr(ForgejoPullRequest), 1).pipe( |
| 317 | Effect.catchTags({ |
| 318 | // Forgejo answers a `poster` naming no account with a 400: nobody to list for. |
| 319 | PullRequestProviderError: (error) => |
| 320 | params.has("poster") && |
| 321 | isForgejoCliError(error.cause) && |
| 322 | error.cause.httpStatus === 400 |
| 323 | ? Effect.succeed(null) |
| 324 | : Effect.fail(error), |
| 325 | }), |
| 326 | ); |
| 327 | if (first === null) return { items: [], truncated: false, continues: false }; |
| 328 | const pageSize = first.rows.length || 50; |
| 329 | const firstIndex = Math.floor(offset / pageSize) + 1; |
| 330 | let consumed = 0; |
| 331 | let more = true; |
| 332 | // Forgejo has no `merged` list state: `state=closed` returns merged and |
| 333 | // closed-unmerged rows alike, so rows are filtered by their mapped state and |
| 334 | // only matching rows count toward the requested limit. |
| 335 | for (let index = firstIndex; more && items.length < input.limit; index++) { |
| 336 | const result = |
| 337 | index === 1 ? first : yield* readPage(query, Schema.NullOr(ForgejoPullRequest), index); |
| 338 | const rows = result.rows; |
| 339 | const start = index === firstIndex ? offset % pageSize : 0; |
| 340 | const countBefore = consumed; |
| 341 | for (const row of rows.slice(start)) { |
| 342 | if (items.length >= input.limit) break; |
| 343 | consumed++; |
| 344 | if (!row) continue; |
| 345 | const changeRequest = forgejoChangeRequest(row); |
| 346 | if (input.state !== "all" && changeRequest.state !== input.state) continue; |
| 347 | items.push(changeRequest); |
| 348 | } |
| 349 | more = result.more || rows.length - start > consumed - countBefore; |
| 350 | } |
| 351 | return { items, truncated: more, continues: true, cursorAdvance: consumed }; |
| 352 | }, |
| 353 | ), |
| 354 | getChangeRequestPreview: (input) => getPull(input).pipe(Effect.map(forgejoChangeRequest)), |
| 355 | getChangeRequestSummary: (input) => getPull(input).pipe(Effect.map(forgejoChangeRequest)), |
| 356 | getChangeRequestChecks: Effect.fn("ForgejoPullRequestProvider.getChangeRequestChecks")( |
| 357 | function* (input) { |
| 358 | const pr = yield* getPull(input); |
| 359 | return { state: forgejoChangeRequest(pr).state, checks: yield* readChecks(input, pr) }; |
| 360 | }, |
| 361 | ), |
| 362 | getChangeRequest: Effect.fn("ForgejoPullRequestProvider.getChangeRequest")(function* (input) { |
| 363 | const [pr, repo, viewer] = yield* Effect.all( |
| 364 | [getPull(input), getRepo(input), getViewer(input)], |
| 365 | { concurrency: 3 }, |
| 366 | ); |
| 367 | const checks = yield* readChecks(input, pr); |
| 368 | return { |
| 369 | ...forgejoChangeRequest(pr), |
| 370 | headSha: pr.head.sha, |
| 371 | mergeCommitSha: pr.merge_commit_sha || null, |
| 372 | mergedBy: forgejoActor(pr.merged_by), |
| 373 | body: pr.body ?? "", |
| 374 | changedFiles: pr.changed_files ?? 0, |
| 375 | reviewers: (pr.requested_reviewers ?? []).flatMap((user) => { |
| 376 | const actor = forgejoActor(user); |
| 377 | return actor ? [actor] : []; |
| 378 | }), |
| 379 | checks, |
| 380 | baseComparison: !pr.merge_base |
| 381 | ? "unknown" |
| 382 | : pr.merge_base === pr.base.sha |
| 383 | ? "up-to-date" |
| 384 | : "behind", |
| 385 | viewerPermissions: permissions(repo, pr, viewer), |
| 386 | mergeCapabilities: { |
| 387 | merge: repo.allow_merge_commits ?? true, |
| 388 | squash: repo.allow_squash_merge ?? true, |
| 389 | rebase: repo.allow_rebase ?? true, |
| 390 | // Added in Forgejo 7; older servers cannot fast-forward-only merge. |
| 391 | "fast-forward": repo.allow_fast_forward_only_merge ?? false, |
| 392 | }, |
| 393 | } satisfies ProviderChangeRequestDetail; |
| 394 | }), |
| 395 | getViewerPermissions: getPermissions, |
| 396 | getChangeRequestActivity: Effect.fn("ForgejoPullRequestProvider.getChangeRequestActivity")( |
| 397 | function* (input) { |
| 398 | const [comments, reviews, commits, reactions, viewer] = yield* Effect.all( |
| 399 | [ |
| 400 | // Issue comments ignore page/limit; fetch this unpaginated endpoint once. |
| 401 | readArray({ ...input, path: `${issuePath(input)}/comments` }, ForgejoComment).pipe( |
| 402 | Effect.map((items) => ({ |
| 403 | items: items.slice(0, 500), |
| 404 | truncated: items.length > 500, |
| 405 | })), |
| 406 | ), |
| 407 | page({ ...input, path: `${pullPath(input)}/reviews` }, ForgejoReview), |
| 408 | // Commit file lists can exceed the output limit on large merges. |
| 409 | page( |
| 410 | { ...input, path: `${pullPath(input)}/commits?files=false&verification=false` }, |
| 411 | ForgejoCommit, |
| 412 | ), |
| 413 | page({ ...input, path: `${issuePath(input)}/reactions` }, ForgejoReaction), |
| 414 | getViewer(input), |
| 415 | ], |
| 416 | { concurrency: 5 }, |
| 417 | ); |
| 418 | const reviewComments = yield* Effect.forEach( |
| 419 | reviews.items.filter((review) => review.comments_count > 0 && review.state !== "PENDING"), |
| 420 | (review) => |
| 421 | readArray( |
| 422 | { ...input, path: `${pullPath(input)}/reviews/${review.id}/comments` }, |
| 423 | ForgejoReviewComment, |
| 424 | ), |
| 425 | { concurrency: 4 }, |
| 426 | ); |
| 427 | const allInline = reviewComments.flat(); |
| 428 | const inline = allInline.slice(0, 500); |
| 429 | const entries = [ |
| 430 | ...comments.items.map((comment) => ({ |
| 431 | comment: forgejoComment(comment), |
| 432 | reactionId: String(comment.id), |
| 433 | })), |
| 434 | ...reviews.items |
| 435 | .filter((review) => review.state !== "PENDING" && review.state !== "REQUEST_REVIEW") |
| 436 | .map((review) => ({ |
| 437 | comment: forgejoReview(review), |
| 438 | reactionId: reviewCommentId(review), |
| 439 | })), |
| 440 | ...inline.map((comment) => ({ |
| 441 | comment: { |
| 442 | ...forgejoComment(comment), |
| 443 | kind: "review-comment" as const, |
| 444 | path: comment.path, |
| 445 | }, |
| 446 | reactionId: String(comment.id), |
| 447 | })), |
| 448 | ]; |
| 449 | const enriched = yield* Effect.forEach( |
| 450 | entries, |
| 451 | ({ comment, reactionId }) => |
| 452 | (reactionId === undefined |
| 453 | ? Effect.succeed([]) |
| 454 | : readArray( |
| 455 | { ...input, path: `${repoPath(input)}/issues/comments/${reactionId}/reactions` }, |
| 456 | ForgejoReaction, |
| 457 | ) |
| 458 | ).pipe( |
| 459 | Effect.map((rows) => ({ ...comment, reactions: forgejoReactions(rows, viewer) })), |
| 460 | ), |
| 461 | { concurrency: 4 }, |
| 462 | ); |
| 463 | const byId = new Map(enriched.map((comment) => [comment.id, comment])); |
| 464 | const timeline = enriched.toSorted((a, b) => a.createdAt.localeCompare(b.createdAt)); |
| 465 | return { |
| 466 | comments: timeline, |
| 467 | commentCount: timeline.length, |
| 468 | commentsTruncated: |
| 469 | comments.truncated || reviews.truncated || allInline.length > inline.length, |
| 470 | reviewThreads: inline.map((comment) => ({ |
| 471 | ...forgejoReviewThread(comment), |
| 472 | comments: [byId.get(String(comment.id)) ?? forgejoComment(comment)], |
| 473 | })), |
| 474 | commits: commits.items.map(forgejoCommit), |
| 475 | reactions: forgejoReactions(reactions.items, viewer), |
| 476 | }; |
| 477 | }, |
| 478 | ), |
| 479 | getFileRevisions: Effect.fn("ForgejoPullRequestProvider.getFileRevisions")(function* (input) { |
| 480 | const result = yield* request({ ...input, path: `${pullPath(input)}.diff` }); |
| 481 | if (result.stdoutTruncated) { |
| 482 | return yield* failure("getFileRevisions", "Forgejo diff exceeded the output limit."); |
| 483 | } |
| 484 | const revisions = new Map(parseDiffFileRevisions(result.stdout)); |
| 485 | for (const path of input.paths) { |
| 486 | if (!revisions.has(path)) revisions.set(path, ""); |
| 487 | } |
| 488 | return { revisions, complete: true }; |
| 489 | }), |
| 490 | getDiff: (input) => |
| 491 | request({ |
| 492 | ...input, |
| 493 | path: input.commit |
| 494 | ? `${repoPath(input)}/git/commits/${encodeURIComponent(input.commit)}.diff` |
| 495 | : `${pullPath(input)}.diff`, |
| 496 | }).pipe( |
| 497 | Effect.map((result) => ({ |
| 498 | patch: result.stdout, |
| 499 | truncated: result.stdoutTruncated, |
| 500 | nextCursor: null, |
| 501 | })), |
| 502 | ), |
| 503 | getDiffFileContents: Effect.fn("ForgejoPullRequestProvider.getDiffFileContents")( |
| 504 | function* (input) { |
| 505 | const pr = yield* getPull(input); |
| 506 | const commit = input.commit |
| 507 | ? yield* read( |
| 508 | { |
| 509 | ...input, |
| 510 | path: `${repoPath(input)}/git/commits/${encodeURIComponent(input.commit)}?files=false&verification=false`, |
| 511 | }, |
| 512 | ForgejoCommit, |
| 513 | ) |
| 514 | : null; |
| 515 | const oldRef = commit ? commit.parents[0]?.sha : pr.merge_base || pr.base.sha; |
| 516 | const newRef = input.commit ?? pr.head.sha; |
| 517 | const content = (repository: string, ref: string, path: string) => |
| 518 | read( |
| 519 | { |
| 520 | ...input, |
| 521 | repository, |
| 522 | path: `${repoPath({ ...input, repository })}/contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=${encodeURIComponent(ref)}`, |
| 523 | }, |
| 524 | Schema.Struct({ content: Schema.String, encoding: Schema.Literal("base64") }), |
| 525 | ).pipe(Effect.map((file) => Buffer.from(file.content, "base64").toString("utf8"))); |
| 526 | const [oldContents, newContents] = yield* Effect.all( |
| 527 | [ |
| 528 | input.changeType === "new" || !oldRef |
| 529 | ? Effect.succeed("") |
| 530 | : content(input.repository, oldRef, input.oldPath), |
| 531 | input.changeType === "deleted" |
| 532 | ? Effect.succeed("") |
| 533 | : content(pr.head.repo?.full_name ?? input.repository, newRef, input.newPath), |
| 534 | ], |
| 535 | { concurrency: 2 }, |
| 536 | ); |
| 537 | return { oldContents, newContents }; |
| 538 | }, |
| 539 | ), |
| 540 | runAction: (input) => { |
| 541 | switch (input.action) { |
| 542 | case "merge": |
| 543 | return Effect.gen(function* () { |
| 544 | const deleteBranch = (yield* getRepo(input)).default_delete_branch_after_merge ?? false; |
| 545 | yield* write({ |
| 546 | ...input, |
| 547 | path: `${pullPath(input)}/merge`, |
| 548 | method: "POST", |
| 549 | body: { |
| 550 | Do: |
| 551 | input.mergeMethod === "fast-forward" |
| 552 | ? "fast-forward-only" |
| 553 | : (input.mergeMethod ?? "merge"), |
| 554 | delete_branch_after_merge: deleteBranch, |
| 555 | }, |
| 556 | }).pipe( |
| 557 | Effect.catchTags({ |
| 558 | // Forgejo merges before deleting the branch, so a refused deletion still merged. |
| 559 | PullRequestProviderError: (error) => |
| 560 | deleteBranch |
| 561 | ? getPull(input).pipe( |
| 562 | Effect.mapError(() => error), |
| 563 | Effect.flatMap((pr) => (pr.merged ? Effect.void : Effect.fail(error))), |
| 564 | ) |
| 565 | : Effect.fail(error), |
| 566 | }), |
| 567 | ); |
| 568 | }); |
| 569 | case "close": |
| 570 | case "reopen": |
| 571 | return request({ |
| 572 | ...input, |
| 573 | path: pullPath(input), |
| 574 | method: "PATCH", |
| 575 | body: { state: input.action === "close" ? "closed" : "open" }, |
| 576 | }).pipe(Effect.map((result) => forgejoActionSummary(result.stdout))); |
| 577 | case "update-branch": |
| 578 | return write({ |
| 579 | ...input, |
| 580 | path: `${pullPath(input)}/update?style=${input.updateMethod ?? "merge"}`, |
| 581 | method: "POST", |
| 582 | }); |
| 583 | default: |
| 584 | return unsupported(input.action); |
| 585 | } |
| 586 | }, |
| 587 | updateChangeRequest: (input) => |
| 588 | write({ |
| 589 | ...input, |
| 590 | path: pullPath(input), |
| 591 | method: "PATCH", |
| 592 | body: { |
| 593 | ...(input.title === undefined ? {} : { title: input.title }), |
| 594 | ...(input.body === undefined ? {} : { body: input.body }), |
| 595 | }, |
| 596 | }), |
| 597 | comment: (input) => |
| 598 | write({ |
| 599 | ...input, |
| 600 | path: `${issuePath(input)}/comments`, |
| 601 | method: "POST", |
| 602 | body: { body: input.body }, |
| 603 | }), |
| 604 | updateComment: (input) => |
| 605 | write({ |
| 606 | ...input, |
| 607 | path: `${repoPath(input)}/issues/comments/${encodeURIComponent(input.commentId)}`, |
| 608 | method: "PATCH", |
| 609 | body: { body: input.body }, |
| 610 | }), |
| 611 | submitReview: Effect.fn("ForgejoPullRequestProvider.submitReview")(function* (input) { |
| 612 | const pr = yield* getPull(input); |
| 613 | yield* write({ |
| 614 | ...input, |
| 615 | path: `${pullPath(input)}/reviews`, |
| 616 | method: "POST", |
| 617 | body: { |
| 618 | event: |
| 619 | input.verdict === "approve" |
| 620 | ? "APPROVED" |
| 621 | : input.verdict === "request-changes" |
| 622 | ? "REQUEST_CHANGES" |
| 623 | : "COMMENT", |
| 624 | body: input.body, |
| 625 | commit_id: pr.head.sha, |
| 626 | comments: input.comments.map((comment) => { |
| 627 | const position = comment.position; |
| 628 | const old = |
| 629 | position.kind === "deleted" || |
| 630 | (position.kind === "context" && position.side === "left"); |
| 631 | return { |
| 632 | path: old ? (comment.oldPath ?? comment.path) : comment.path, |
| 633 | body: comment.body, |
| 634 | old_position: old ? position.oldLine : 0, |
| 635 | new_position: old ? 0 : position.newLine, |
| 636 | }; |
| 637 | }), |
| 638 | }, |
| 639 | }); |
| 640 | }), |
| 641 | listReviewerCandidates: Effect.fn("ForgejoPullRequestProvider.listReviewerCandidates")( |
| 642 | function* (input) { |
| 643 | // Unpaginated in Forgejo: paging it returns the full list on every page. |
| 644 | const [pr, users] = yield* Effect.all( |
| 645 | [ |
| 646 | getPull(input), |
| 647 | readArray({ ...input, path: `${repoPath(input)}/assignees` }, ForgejoUser), |
| 648 | ], |
| 649 | { concurrency: 2 }, |
| 650 | ); |
| 651 | return { |
| 652 | candidates: users |
| 653 | .filter((user) => user.login !== pr.user?.login) |
| 654 | .flatMap((user) => { |
| 655 | const actor = forgejoActor(user); |
| 656 | return actor |
| 657 | ? [ |
| 658 | { |
| 659 | ...actor, |
| 660 | id: user.login, |
| 661 | kind: "user" as const, |
| 662 | isRequested: |
| 663 | pr.requested_reviewers?.some((reviewer) => reviewer.login === user.login) ?? |
| 664 | false, |
| 665 | }, |
| 666 | ] |
| 667 | : []; |
| 668 | }), |
| 669 | truncated: false, |
| 670 | }; |
| 671 | }, |
| 672 | ), |
| 673 | setReviewerRequest: (input) => |
| 674 | write({ |
| 675 | ...input, |
| 676 | path: `${pullPath(input)}/requested_reviewers`, |
| 677 | method: input.requested ? "POST" : "DELETE", |
| 678 | body: { reviewers: input.reviewers.map((reviewer) => reviewer.id) }, |
| 679 | }), |
| 680 | listLabelCandidates: Effect.fn("ForgejoPullRequestProvider.listLabelCandidates")( |
| 681 | function* (input) { |
| 682 | const [pr, labels] = yield* Effect.all( |
| 683 | [getPull(input), page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel)], |
| 684 | { concurrency: 2 }, |
| 685 | ); |
| 686 | return { |
| 687 | candidates: labels.items.map((label) => ({ |
| 688 | name: label.name, |
| 689 | color: label.color ?? null, |
| 690 | description: label.description ?? null, |
| 691 | isApplied: pr.labels?.some((applied) => applied.id === label.id) ?? false, |
| 692 | })), |
| 693 | truncated: labels.truncated, |
| 694 | }; |
| 695 | }, |
| 696 | ), |
| 697 | listRepositoryLabels: Effect.fn("ForgejoPullRequestProvider.listRepositoryLabels")( |
| 698 | function* (input) { |
| 699 | const labels = yield* page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel); |
| 700 | return { |
| 701 | items: labels.items.map((label) => ({ name: label.name, color: label.color ?? null })), |
| 702 | truncated: labels.truncated, |
| 703 | }; |
| 704 | }, |
| 705 | ), |
| 706 | searchRepositoryAuthors: Effect.fn("ForgejoPullRequestProvider.searchRepositoryAuthors")( |
| 707 | function* (input) { |
| 708 | const query = input.query?.trim() ?? ""; |
| 709 | const actors = (users: ReadonlyArray<typeof ForgejoUser.Type>) => |
| 710 | users.flatMap((user) => { |
| 711 | const actor = forgejoActor(user); |
| 712 | return actor ? [actor] : []; |
| 713 | }); |
| 714 | // Before anything is typed the repository's own people stand in; a search reaches |
| 715 | // contributors from forks, who are never assignable. |
| 716 | if (query.length === 0) { |
| 717 | const users = yield* readArray( |
| 718 | { ...input, path: `${repoPath(input)}/assignees` }, |
| 719 | ForgejoUser, |
| 720 | ); |
| 721 | return { items: actors(users), truncated: false }; |
| 722 | } |
| 723 | const found = yield* readLinked( |
| 724 | { |
| 725 | ...input, |
| 726 | path: `users/search?${new URLSearchParams({ q: query, limit: String(USER_SEARCH_LIMIT) })}`, |
| 727 | }, |
| 728 | ForgejoUserSearch, |
| 729 | ); |
| 730 | const users = found.value.data ?? []; |
| 731 | // A server may cap pages below the limit asked for; its `link` header still says more. |
| 732 | return { |
| 733 | items: actors(users), |
| 734 | truncated: found.next || users.length >= USER_SEARCH_LIMIT, |
| 735 | }; |
| 736 | }, |
| 737 | ), |
| 738 | setLabels: Effect.fn("ForgejoPullRequestProvider.setLabels")(function* (input) { |
| 739 | const labels = yield* page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel); |
| 740 | const selected = labels.items.filter((label) => input.labels.includes(label.name)); |
| 741 | if (selected.length !== input.labels.length) |
| 742 | return yield* failure("setLabels", "One or more requested labels could not be found."); |
| 743 | if (input.applied) |
| 744 | yield* write({ |
| 745 | ...input, |
| 746 | path: `${issuePath(input)}/labels`, |
| 747 | method: "POST", |
| 748 | body: { labels: selected.map((label) => label.id) }, |
| 749 | }); |
| 750 | else |
| 751 | yield* Effect.forEach( |
| 752 | selected, |
| 753 | (label) => |
| 754 | write({ ...input, path: `${issuePath(input)}/labels/${label.id}`, method: "DELETE" }), |
| 755 | { concurrency: 1 }, |
| 756 | ); |
| 757 | }), |
| 758 | setReaction: Effect.fn("ForgejoPullRequestProvider.setReaction")(function* (input) { |
| 759 | let commentId = input.subjectId; |
| 760 | if (commentId?.startsWith("review:")) { |
| 761 | const reviewId = /^review:([1-9]\d*)$/.exec(commentId)?.[1]; |
| 762 | if (!reviewId) return yield* failure("setReaction", "Invalid Forgejo review ID."); |
| 763 | const review = yield* read( |
| 764 | { ...input, path: `${pullPath(input)}/reviews/${reviewId}` }, |
| 765 | ForgejoReview, |
| 766 | ); |
| 767 | commentId = reviewCommentId(review); |
| 768 | if (!commentId) |
| 769 | return yield* failure( |
| 770 | "setReaction", |
| 771 | "Forgejo did not return a comment ID for this review.", |
| 772 | ); |
| 773 | } |
| 774 | if (commentId && !/^[1-9]\d*$/.test(commentId)) |
| 775 | return yield* failure("setReaction", "Invalid Forgejo comment ID."); |
| 776 | yield* write({ |
| 777 | ...input, |
| 778 | path: commentId |
| 779 | ? `${repoPath(input)}/issues/comments/${commentId}/reactions` |
| 780 | : `${issuePath(input)}/reactions`, |
| 781 | method: input.reacted ? "POST" : "DELETE", |
| 782 | body: { content: FORGEJO_REACTIONS[input.content] }, |
| 783 | }); |
| 784 | }), |
| 785 | replyToThread: () => unsupported("thread replies"), |
| 786 | setThreadResolution: () => unsupported("thread resolution"), |
| 787 | }; |
| 788 | return provider; |
| 789 | }); |