The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { SourceControlProviderKind } from "@t3tools/contracts"; |
| 2 | import * as Clock from "effect/Clock"; |
| 3 | import * as DateTime from "effect/DateTime"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as FileSystem from "effect/FileSystem"; |
| 6 | import * as Option from "effect/Option"; |
| 7 | import * as Schema from "effect/Schema"; |
| 8 | import * as Result from "effect/Result"; |
| 9 | import * as Semaphore from "effect/Semaphore"; |
| 10 | import { SourceControlProviderError } from "@t3tools/contracts"; |
| 11 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 12 | import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; |
| 13 | import * as ForgejoCli from "./ForgejoCli.ts"; |
| 14 | import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider"; |
| 15 | import { |
| 16 | isMissingExecutable, |
| 17 | providerAuth, |
| 18 | probeSourceControlProvider, |
| 19 | type SourceControlCliDiscoverySpec, |
| 20 | type SourceControlManagedCliDiscoverySpec, |
| 21 | } from "@t3tools/source-control-core/server/discovery"; |
| 22 | import { ForgejoPullRequestSchema, toForgejoChangeRequest } from "./forgejoPullRequests.ts"; |
| 23 | |
| 24 | const isForgejoCliError = Schema.is(ForgejoCli.ForgejoCliError); |
| 25 | |
| 26 | export const discovery = { |
| 27 | type: "cli", |
| 28 | kind: SourceControlProviderKind.make("forgejo"), |
| 29 | label: "Forgejo / Gitea", |
| 30 | executable: "tea", |
| 31 | versionArgs: ["--version"], |
| 32 | authArgs: ["login", "status", "--output", "json"], |
| 33 | remoteRefinementArgs: () => ["login", "list", "--output", "json"], |
| 34 | parseAuth: (input) => { |
| 35 | const logins = ForgejoCli.parseForgejoLogins(input.stdout); |
| 36 | const login = logins.find((entry) => entry.default === "true") ?? logins[0]; |
| 37 | return login |
| 38 | ? providerAuth({ |
| 39 | status: login.valid === "true" ? "authenticated" : "unauthenticated", |
| 40 | account: login.user, |
| 41 | host: ForgejoCli.parseForgejoRemote(login.url)?.host, |
| 42 | }) |
| 43 | : providerAuth({ |
| 44 | status: "unauthenticated", |
| 45 | detail: "Run `tea login add` to authenticate a Forgejo or Gitea server.", |
| 46 | }); |
| 47 | }, |
| 48 | refineUnknownRemote: (input) => { |
| 49 | const remote = ForgejoCli.parseForgejoRemote(input.context.remoteUrl); |
| 50 | const login = |
| 51 | remote && |
| 52 | ForgejoCli.matchForgejoLogin( |
| 53 | ForgejoCli.parseForgejoLogins(input.auth.stdout), |
| 54 | remote, |
| 55 | input.context.requestedHost, |
| 56 | ); |
| 57 | return login |
| 58 | ? { |
| 59 | kind: SourceControlProviderKind.make("forgejo"), |
| 60 | name: "Forgejo / Gitea", |
| 61 | baseUrl: login.url, |
| 62 | } |
| 63 | : null; |
| 64 | }, |
| 65 | installHint: |
| 66 | "Install `fj` 0.6 or later from https://codeberg.org/forgejo-contrib/forgejo-cli and run `fj --host <server-url> auth add-token`, or install `tea` 0.16 or later from https://gitea.com/gitea/tea and run `tea login add` for each Forgejo or Gitea server.", |
| 67 | } satisfies SourceControlCliDiscoverySpec; |
| 68 | |
| 69 | export const makeDiscovery = Effect.gen(function* () { |
| 70 | const cli = yield* ForgejoCli.ForgejoCli; |
| 71 | const { process } = yield* SourceControlHost.SourceControlHost; |
| 72 | const listLogins = cli.listLogins; |
| 73 | if (!listLogins) return discovery; |
| 74 | return { |
| 75 | type: "managed-cli", |
| 76 | kind: SourceControlProviderKind.make("forgejo"), |
| 77 | label: discovery.label, |
| 78 | installHint: discovery.installHint, |
| 79 | probe: Effect.fn("ForgejoSourceControlProvider.discovery")(function* (cwd: string) { |
| 80 | const remoteUrl = yield* process |
| 81 | .run({ |
| 82 | operation: "source-control.discovery.remote", |
| 83 | command: "git", |
| 84 | args: ["remote", "get-url", "origin"], |
| 85 | cwd, |
| 86 | allowNonZeroExit: true, |
| 87 | timeoutMs: 5_000, |
| 88 | maxOutputBytes: 8_000, |
| 89 | }) |
| 90 | .pipe( |
| 91 | Effect.map((result) => result.stdout.trim()), |
| 92 | Effect.orElseSucceed(() => ""), |
| 93 | ); |
| 94 | const credentials = yield* Effect.result(listLogins({ cwd, command: "fj", remoteUrl })); |
| 95 | const logins = Result.isSuccess(credentials) ? credentials.success : []; |
| 96 | const remote = ForgejoCli.parseForgejoRemote(remoteUrl); |
| 97 | const login = |
| 98 | (remote && ForgejoCli.matchForgejoLogin(logins, remote)) || |
| 99 | logins.find((entry) => entry.default === "true") || |
| 100 | logins[0]; |
| 101 | const fj = yield* probeSourceControlProvider({ |
| 102 | // fj reads the cwd repository even with --host and fails on an unborn branch. |
| 103 | cwd: yield* HostProcess.HomeDirectory, |
| 104 | process, |
| 105 | spec: { |
| 106 | ...discovery, |
| 107 | executable: "fj", |
| 108 | versionArgs: ["version"], |
| 109 | authArgs: login ? ["--host", login.url, "whoami"] : ["auth", "list"], |
| 110 | parseAuth: (result) => |
| 111 | Result.isFailure(credentials) |
| 112 | ? providerAuth({ |
| 113 | status: "unknown", |
| 114 | detail: "Could not read fj authentication storage. Authenticate again with fj.", |
| 115 | }) |
| 116 | : login && result.exitCode === 0 |
| 117 | ? providerAuth({ |
| 118 | status: "authenticated", |
| 119 | account: login.user, |
| 120 | host: ForgejoCli.parseForgejoRemote(login.url)?.host, |
| 121 | }) |
| 122 | : // fj prints this for transport failures (TLS, connect, DNS), never for a rejected token. |
| 123 | login && result.stderr.includes("error sending request for url") |
| 124 | ? providerAuth({ |
| 125 | status: "unknown", |
| 126 | detail: `Could not reach ${login.url} to verify the fj login.`, |
| 127 | host: ForgejoCli.parseForgejoRemote(login.url)?.host, |
| 128 | }) |
| 129 | : providerAuth({ |
| 130 | status: "unauthenticated", |
| 131 | detail: |
| 132 | "Authenticate this server with `fj --host <server-url> auth add-token`. For a server under a URL subpath, such as `https://example.com/forgejo`, use `tea login add` instead.", |
| 133 | }), |
| 134 | }, |
| 135 | }); |
| 136 | if (fj.status === "available" && (login || Result.isFailure(credentials))) { |
| 137 | if (login && fj.auth.status === "authenticated" && cli.getAccount) { |
| 138 | const account = yield* cli.getAccount({ cwd, baseUrl: login.url }).pipe(Effect.result); |
| 139 | return { |
| 140 | ...fj, |
| 141 | auth: Result.isSuccess(account) |
| 142 | ? providerAuth({ |
| 143 | status: "authenticated", |
| 144 | account: account.success, |
| 145 | host: ForgejoCli.parseForgejoRemote(login.url)?.host, |
| 146 | }) |
| 147 | : providerAuth({ |
| 148 | status: "unknown", |
| 149 | detail: account.failure.detail, |
| 150 | host: ForgejoCli.parseForgejoRemote(login.url)?.host, |
| 151 | }), |
| 152 | }; |
| 153 | } |
| 154 | return fj; |
| 155 | } |
| 156 | const tea = yield* probeSourceControlProvider({ cwd, process, spec: discovery }); |
| 157 | // Discovery keeps the install hint only for an absent executable; a slow or broken fj |
| 158 | // explains itself better than tea's install advice. |
| 159 | const fjAbsent = fj.status === "missing" && fj.installHint === discovery.installHint; |
| 160 | return tea.status === "available" || fjAbsent ? tea : fj; |
| 161 | }), |
| 162 | refineUnknownRemote: Effect.fn("ForgejoSourceControlProvider.refineUnknownRemote")( |
| 163 | function* (input: { |
| 164 | readonly cwd: string; |
| 165 | readonly context: SourceControlProvider.SourceControlProviderContext; |
| 166 | }) { |
| 167 | const remote = ForgejoCli.parseForgejoRemote(input.context.remoteUrl); |
| 168 | if (!remote) return null; |
| 169 | let failure: ForgejoCli.ForgejoCliError | undefined; |
| 170 | for (const command of ["fj", "tea"] as const) { |
| 171 | const logins = yield* listLogins({ |
| 172 | cwd: input.cwd, |
| 173 | command, |
| 174 | remoteUrl: input.context.remoteUrl, |
| 175 | }).pipe( |
| 176 | Effect.catchIf( |
| 177 | (error) => isMissingExecutable(error.cause), |
| 178 | () => Effect.succeed([]), |
| 179 | ), |
| 180 | Effect.result, |
| 181 | ); |
| 182 | if (Result.isFailure(logins)) { |
| 183 | failure ??= logins.failure; |
| 184 | continue; |
| 185 | } |
| 186 | const login = ForgejoCli.matchForgejoLogin( |
| 187 | logins.success, |
| 188 | remote, |
| 189 | input.context.requestedHost, |
| 190 | ); |
| 191 | if (login) |
| 192 | return { |
| 193 | kind: SourceControlProviderKind.make("forgejo"), |
| 194 | name: discovery.label, |
| 195 | baseUrl: login.url, |
| 196 | }; |
| 197 | } |
| 198 | if (failure) return yield* failure; |
| 199 | return null; |
| 200 | }, |
| 201 | ), |
| 202 | } satisfies SourceControlManagedCliDiscoverySpec; |
| 203 | }); |
| 204 | |
| 205 | export function repositoryNameFromRemoteUrl(url: string): string | null { |
| 206 | const path = SourceControlProvider.repositoryPathFromRemoteUrl(url); |
| 207 | return path === null || !/^https?:\/\//iu.test(url.trim()) |
| 208 | ? path |
| 209 | : path.split("/").slice(-2).join("/"); |
| 210 | } |
| 211 | |
| 212 | // Resolve browser URLs from the serving login to handle SSH aliases and mounts. |
| 213 | const refineRepositoryIdentity: NonNullable< |
| 214 | SourceControlProvider.SourceControlProvider["Service"]["refineRepositoryIdentity"] |
| 215 | > = Effect.fn("ForgejoSourceControlProvider.refineRepositoryIdentity")(function* ({ |
| 216 | identity, |
| 217 | resolveContext, |
| 218 | }) { |
| 219 | const remote = ForgejoCli.parseForgejoRemote(identity.locator.remoteUrl); |
| 220 | if ( |
| 221 | !remote || |
| 222 | !identity.rootPath || |
| 223 | (identity.provider !== undefined && |
| 224 | identity.provider !== "unknown" && |
| 225 | identity.provider !== "forgejo") |
| 226 | ) |
| 227 | return identity; |
| 228 | const context = yield* resolveContext({ |
| 229 | cwd: identity.rootPath, |
| 230 | context: { |
| 231 | provider: { kind: SourceControlProviderKind.make("unknown"), name: "Unknown", baseUrl: "" }, |
| 232 | remoteName: identity.locator.remoteName, |
| 233 | remoteUrl: identity.locator.remoteUrl, |
| 234 | }, |
| 235 | }); |
| 236 | if (context?.provider.kind !== "forgejo") return identity; |
| 237 | const baseUrl = context.provider.baseUrl.replace(/\/+$/, ""); |
| 238 | const basePath = new URL(baseUrl).pathname.replace(/^\/+|\/+$/g, ""); |
| 239 | const path = |
| 240 | !remote.ssh && basePath && remote.path.startsWith(`${basePath}/`) |
| 241 | ? remote.path.slice(basePath.length + 1) |
| 242 | : remote.path; |
| 243 | return { |
| 244 | ...identity, |
| 245 | provider: SourceControlProviderKind.make("forgejo"), |
| 246 | webUrl: `${baseUrl}/${path}`, |
| 247 | }; |
| 248 | }); |
| 249 | |
| 250 | // An SSH remote names an alias rather than the web server, so the login that serves it says which. |
| 251 | const resolveRemoteWebHost: NonNullable< |
| 252 | SourceControlProvider.SourceControlProvider["Service"]["resolveRemoteWebHost"] |
| 253 | > = Effect.fn("ForgejoSourceControlProvider.resolveRemoteWebHost")(function* ({ |
| 254 | cwd, |
| 255 | context, |
| 256 | resolveContext, |
| 257 | }) { |
| 258 | if (!ForgejoCli.parseForgejoRemote(context.remoteUrl)?.ssh) return null; |
| 259 | const resolved = yield* resolveContext({ |
| 260 | cwd, |
| 261 | context: { |
| 262 | ...context, |
| 263 | provider: { kind: SourceControlProviderKind.make("unknown"), name: "Unknown", baseUrl: "" }, |
| 264 | }, |
| 265 | }); |
| 266 | return resolved?.provider.kind === "forgejo" |
| 267 | ? new URL(resolved.provider.baseUrl).host.toLowerCase() |
| 268 | : null; |
| 269 | }); |
| 270 | |
| 271 | const RepositorySchema = Schema.Struct({ |
| 272 | full_name: Schema.String, |
| 273 | clone_url: Schema.String, |
| 274 | ssh_url: Schema.String, |
| 275 | default_branch: Schema.optional(Schema.NullOr(Schema.String)), |
| 276 | }); |
| 277 | const cloneUrls = (raw: typeof RepositorySchema.Type) => ({ |
| 278 | nameWithOwner: raw.full_name, |
| 279 | url: raw.clone_url, |
| 280 | sshUrl: raw.ssh_url, |
| 281 | }); |
| 282 | const repositoryPath = (repository: string) => |
| 283 | `repos/${repository.split("/").map(encodeURIComponent).join("/")}`; |
| 284 | |
| 285 | type ForgejoPull = typeof ForgejoPullRequestSchema.Type; |
| 286 | const updatedMillis = (pull: ForgejoPull) => |
| 287 | pull.updated_at?.pipe(Option.map(DateTime.toEpochMillis), Option.getOrUndefined); |
| 288 | // Renaming a fork or deleting a pull request moves nothing in the list, so it is re-read in full. |
| 289 | const UNFILTERED_PULLS_MAX_AGE_MS = 60 * 60_000; |
| 290 | /** Every pull request of a repository whose server ignores `head=` (Gitea, Forgejo before 16). */ |
| 291 | interface UnfilteredPulls { |
| 292 | readonly lock: Semaphore.Semaphore; |
| 293 | pulls: Map<number, ForgejoPull> | undefined; |
| 294 | /** The newest `updated_at` on the list's first page when it was last read. */ |
| 295 | newest: number | undefined; |
| 296 | scannedAt: number; |
| 297 | } |
| 298 | |
| 299 | export const make = Effect.gen(function* () { |
| 300 | const cli = yield* ForgejoCli.ForgejoCli; |
| 301 | const fs = yield* FileSystem.FileSystem; |
| 302 | const { process } = yield* SourceControlHost.SourceControlHost; |
| 303 | const request = <S extends Schema.Codec<unknown, unknown, never, never>>( |
| 304 | input: ForgejoCli.ForgejoApiInput, |
| 305 | schema: S, |
| 306 | ) => |
| 307 | cli.api(input).pipe( |
| 308 | Effect.flatMap((result) => |
| 309 | Schema.decodeEffect(Schema.fromJsonString(schema))(result.stdout).pipe( |
| 310 | Effect.mapError( |
| 311 | (cause) => |
| 312 | new ForgejoCli.ForgejoCliError({ |
| 313 | command: "tea", |
| 314 | cwd: input.cwd, |
| 315 | detail: "Forgejo API returned an invalid response.", |
| 316 | reason: "invalid-response", |
| 317 | cause, |
| 318 | }), |
| 319 | ), |
| 320 | ), |
| 321 | ), |
| 322 | ); |
| 323 | const mapError = (operation: string, cwd: string) => |
| 324 | Effect.mapError( |
| 325 | (cause: unknown) => |
| 326 | new SourceControlProviderError({ |
| 327 | provider: SourceControlProviderKind.make("forgejo"), |
| 328 | operation, |
| 329 | cwd, |
| 330 | ...(isForgejoCliError(cause) ? { command: cause.command } : {}), |
| 331 | detail: isForgejoCliError(cause) ? cause.detail : "Forgejo operation failed.", |
| 332 | cause, |
| 333 | }), |
| 334 | ); |
| 335 | const getPull = Effect.fn("ForgejoSourceControlProvider.getPull")(function* ( |
| 336 | input: Parameters< |
| 337 | SourceControlProvider.SourceControlProvider["Service"]["getChangeRequest"] |
| 338 | >[0], |
| 339 | ) { |
| 340 | const repo = yield* cli.resolveRepository(input); |
| 341 | const number = /(?:^#?|\/pulls\/)(\d+)(?:\/[^?#]*)?(?:[?#].*)?$/.exec(input.reference)?.[1]; |
| 342 | if (!number) |
| 343 | return yield* new ForgejoCli.ForgejoCliError({ |
| 344 | command: "tea", |
| 345 | cwd: input.cwd, |
| 346 | detail: "Specify a pull request number or Forgejo pull request URL.", |
| 347 | }); |
| 348 | return yield* request( |
| 349 | { ...input, path: `${repositoryPath(repo.repository)}/pulls/${number}` }, |
| 350 | ForgejoPullRequestSchema, |
| 351 | ); |
| 352 | }); |
| 353 | const unfilteredPulls = new Map<string, UnfilteredPulls>(); |
| 354 | // Call holding `state.lock`. The list is sorted newest update first, so after one full read |
| 355 | // everything that changed since sits ahead of the first pull request older than `newest`. |
| 356 | const readUnfilteredPulls = Effect.fn("ForgejoSourceControlProvider.readUnfilteredPulls")( |
| 357 | function* ( |
| 358 | input: ForgejoCli.ForgejoRepositoryInput, |
| 359 | repository: string, |
| 360 | state: UnfilteredPulls, |
| 361 | firstPage: ReadonlyArray<ForgejoPull> | undefined, |
| 362 | ) { |
| 363 | const now = yield* Clock.currentTimeMillis; |
| 364 | const since = |
| 365 | state.pulls && now - state.scannedAt < UNFILTERED_PULLS_MAX_AGE_MS |
| 366 | ? state.newest |
| 367 | : undefined; |
| 368 | const pulls = |
| 369 | since !== undefined && state.pulls ? state.pulls : new Map<number, ForgejoPull>(); |
| 370 | let newest = since; |
| 371 | for (let page = 1; ; page++) { |
| 372 | const items = |
| 373 | page === 1 && firstPage && !state.pulls |
| 374 | ? firstPage |
| 375 | : yield* request( |
| 376 | { |
| 377 | ...input, |
| 378 | path: `${repositoryPath(repository)}/pulls?state=all&sort=recentupdate&limit=50&page=${page}`, |
| 379 | }, |
| 380 | Schema.Array(ForgejoPullRequestSchema), |
| 381 | ); |
| 382 | const updated = items.flatMap((item) => updatedMillis(item) ?? []); |
| 383 | for (const item of items) pulls.set(item.number, item); |
| 384 | // Later pages can hold newer updates than a first page read before them, and a mark past |
| 385 | // the first page's would skip the updates that pushed them down. |
| 386 | if (page === 1 && updated.length > 0) newest = Math.max(...updated); |
| 387 | if (items.length === 0 || (since !== undefined && updated.some((at) => at < since))) break; |
| 388 | } |
| 389 | if (since === undefined) state.scannedAt = now; |
| 390 | state.pulls = pulls; |
| 391 | state.newest = newest; |
| 392 | return pulls; |
| 393 | }, |
| 394 | ); |
| 395 | return SourceControlProvider.SourceControlProvider.of({ |
| 396 | kind: SourceControlProviderKind.make("forgejo"), |
| 397 | repositoryNameFromRemoteUrl, |
| 398 | refineRepositoryIdentity, |
| 399 | resolveRemoteWebHost, |
| 400 | listChangeRequests: Effect.fn("ForgejoSourceControlProvider.listChangeRequests")( |
| 401 | function* (input) { |
| 402 | const repo = yield* cli.resolveRepository(input); |
| 403 | const source = SourceControlProvider.sourceControlRefFromInput(input); |
| 404 | const branch = SourceControlProvider.sourceBranch(input); |
| 405 | const limit = input.limit ?? 20; |
| 406 | const matching = (items: Iterable<ForgejoPull>) => { |
| 407 | const results: ReturnType<typeof toForgejoChangeRequest>[] = []; |
| 408 | for (const item of items) { |
| 409 | const normalized = toForgejoChangeRequest(item); |
| 410 | if ( |
| 411 | normalized.headRefName !== branch || |
| 412 | (source?.repository && item.head.repo?.full_name !== source.repository) || |
| 413 | (source?.owner && item.head.repo?.owner.login !== source.owner) |
| 414 | ) |
| 415 | continue; |
| 416 | if (input.state === "all" || normalized.state === input.state) results.push(normalized); |
| 417 | } |
| 418 | return results; |
| 419 | }; |
| 420 | const key = `${repo.baseUrl}\n${repo.repository}`; |
| 421 | let unfiltered = unfilteredPulls.get(key); |
| 422 | let firstPage: ReadonlyArray<ForgejoPull> | undefined; |
| 423 | if (!unfiltered) { |
| 424 | const results: ReturnType<typeof toForgejoChangeRequest>[] = []; |
| 425 | for (let page = 1; results.length < limit; page++) { |
| 426 | const items = yield* request( |
| 427 | { |
| 428 | ...input, |
| 429 | path: `${repositoryPath(repo.repository)}/pulls?state=${input.state === "merged" ? "closed" : input.state}&head=${encodeURIComponent(branch)}&sort=recentupdate&limit=50&page=${page}`, |
| 430 | }, |
| 431 | Schema.Array(ForgejoPullRequestSchema), |
| 432 | ); |
| 433 | // A deleted head branch keeps its name only in `label`. |
| 434 | if (items.some((item) => item.head.ref !== branch && item.head.label !== branch)) { |
| 435 | unfiltered = unfilteredPulls.get(key) ?? { |
| 436 | lock: Semaphore.makeUnsafe(1), |
| 437 | pulls: undefined, |
| 438 | newest: undefined, |
| 439 | scannedAt: 0, |
| 440 | }; |
| 441 | unfilteredPulls.set(key, unfiltered); |
| 442 | if (page === 1 && input.state === "all") firstPage = items; |
| 443 | break; |
| 444 | } |
| 445 | results.push(...matching(items)); |
| 446 | if (items.length === 0) break; |
| 447 | } |
| 448 | if (!unfiltered) return results.slice(0, limit); |
| 449 | } |
| 450 | const pulls = yield* unfiltered.lock.withPermits(1)( |
| 451 | readUnfilteredPulls(input, repo.repository, unfiltered, firstPage), |
| 452 | ); |
| 453 | const candidates = matching(pulls.values()).toSorted( |
| 454 | (left, right) => |
| 455 | Option.getOrElse(Option.map(right.updatedAt, DateTime.toEpochMillis), () => 0) - |
| 456 | Option.getOrElse(Option.map(left.updatedAt, DateTime.toEpochMillis), () => 0) || |
| 457 | right.number - left.number, |
| 458 | ); |
| 459 | // A deleted pull request leaves the list without moving anything in it, so a remembered |
| 460 | // match is read again before it is returned. |
| 461 | const results: ReturnType<typeof toForgejoChangeRequest>[] = []; |
| 462 | for (const candidate of candidates) { |
| 463 | if (results.length >= limit) break; |
| 464 | const current = yield* request( |
| 465 | { |
| 466 | ...input, |
| 467 | path: `${repositoryPath(repo.repository)}/pulls/${candidate.number}`, |
| 468 | }, |
| 469 | ForgejoPullRequestSchema, |
| 470 | ).pipe( |
| 471 | Effect.catchIf( |
| 472 | (error) => isForgejoCliError(error) && error.httpStatus === 404, |
| 473 | () => Effect.undefined, |
| 474 | ), |
| 475 | ); |
| 476 | if (current?.number !== candidate.number) { |
| 477 | pulls.delete(candidate.number); |
| 478 | continue; |
| 479 | } |
| 480 | // Not written back: a refresh may have stored a newer copy while this was read. |
| 481 | results.push(...matching([current])); |
| 482 | } |
| 483 | return results; |
| 484 | }, |
| 485 | (effect, input) => effect.pipe(mapError("listChangeRequests", input.cwd)), |
| 486 | ), |
| 487 | getChangeRequest: Effect.fn("ForgejoSourceControlProvider.getChangeRequest")(function (input) { |
| 488 | return getPull(input).pipe( |
| 489 | Effect.map(toForgejoChangeRequest), |
| 490 | mapError("getChangeRequest", input.cwd), |
| 491 | ); |
| 492 | }), |
| 493 | createChangeRequest: Effect.fn("ForgejoSourceControlProvider.createChangeRequest")( |
| 494 | function* (input) { |
| 495 | const repo = yield* cli.resolveRepository(input); |
| 496 | const source = SourceControlProvider.sourceControlRefFromInput(input); |
| 497 | const owner = source?.owner ?? source?.repository?.split("/")[0]; |
| 498 | const head = SourceControlProvider.sourceBranch(input); |
| 499 | yield* cli.api({ |
| 500 | ...input, |
| 501 | path: `${repositoryPath(input.target?.repository ?? repo.repository)}/pulls`, |
| 502 | method: "POST", |
| 503 | body: { |
| 504 | base: input.target?.refName ?? input.baseRefName, |
| 505 | head: owner ? `${owner}:${head}` : head, |
| 506 | title: input.title, |
| 507 | body: yield* fs.readFileString(input.bodyFile), |
| 508 | }, |
| 509 | }); |
| 510 | }, |
| 511 | (effect, input) => effect.pipe(mapError("createChangeRequest", input.cwd)), |
| 512 | ), |
| 513 | getRepositoryCloneUrls: Effect.fn("ForgejoSourceControlProvider.getRepositoryCloneUrls")( |
| 514 | function* (input) { |
| 515 | const repo = yield* cli.resolveRepository(input); |
| 516 | return cloneUrls( |
| 517 | yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema), |
| 518 | ); |
| 519 | }, |
| 520 | (effect, input) => effect.pipe(mapError("getRepositoryCloneUrls", input.cwd)), |
| 521 | ), |
| 522 | createRepository: Effect.fn("ForgejoSourceControlProvider.createRepository")( |
| 523 | function* (input) { |
| 524 | const repo = yield* cli.resolveRepository(input); |
| 525 | const user = yield* request( |
| 526 | { ...input, path: "user" }, |
| 527 | Schema.Struct({ login: Schema.String }), |
| 528 | ); |
| 529 | const [owner, name] = repo.repository.split("/"); |
| 530 | return cloneUrls( |
| 531 | yield* request( |
| 532 | { |
| 533 | ...input, |
| 534 | path: |
| 535 | owner === user.login |
| 536 | ? "user/repos" |
| 537 | : `orgs/${encodeURIComponent(owner ?? "")}/repos`, |
| 538 | method: "POST", |
| 539 | body: { name, private: input.visibility === "private", auto_init: false }, |
| 540 | }, |
| 541 | RepositorySchema, |
| 542 | ), |
| 543 | ); |
| 544 | }, |
| 545 | (effect, input) => effect.pipe(mapError("createRepository", input.cwd)), |
| 546 | ), |
| 547 | getDefaultBranch: Effect.fn("ForgejoSourceControlProvider.getDefaultBranch")( |
| 548 | function* (input) { |
| 549 | const repo = yield* cli.resolveRepository(input); |
| 550 | return ( |
| 551 | (yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema)) |
| 552 | .default_branch ?? null |
| 553 | ); |
| 554 | }, |
| 555 | (effect, input) => effect.pipe(mapError("getDefaultBranch", input.cwd)), |
| 556 | ), |
| 557 | checkoutChangeRequest: Effect.fn("ForgejoSourceControlProvider.checkoutChangeRequest")( |
| 558 | function* (input) { |
| 559 | const repo = yield* cli.resolveRepository(input); |
| 560 | const pull = yield* getPull(input); |
| 561 | if (repo.command === "fj") { |
| 562 | // fj checkout cannot target a repository outside the local remotes. |
| 563 | const urls = yield* request( |
| 564 | { ...input, path: repositoryPath(repo.repository) }, |
| 565 | RepositorySchema, |
| 566 | ); |
| 567 | const remote = input.context?.remoteUrl; |
| 568 | const useSsh = remote && ForgejoCli.parseForgejoRemote(remote)?.ssh; |
| 569 | yield* process.run({ |
| 570 | operation: "ForgejoSourceControlProvider.checkoutChangeRequest", |
| 571 | command: "git", |
| 572 | cwd: input.cwd, |
| 573 | args: [ |
| 574 | "fetch", |
| 575 | "--", |
| 576 | useSsh ? urls.ssh_url : urls.clone_url, |
| 577 | `refs/pull/${pull.number}/head`, |
| 578 | ], |
| 579 | }); |
| 580 | const branch = `pulls/${pull.number}`; |
| 581 | const existing = yield* process.run({ |
| 582 | operation: "ForgejoSourceControlProvider.checkoutChangeRequest", |
| 583 | command: "git", |
| 584 | cwd: input.cwd, |
| 585 | args: ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], |
| 586 | allowNonZeroExit: true, |
| 587 | }); |
| 588 | yield* process.run({ |
| 589 | operation: "ForgejoSourceControlProvider.checkoutChangeRequest", |
| 590 | command: "git", |
| 591 | cwd: input.cwd, |
| 592 | args: |
| 593 | existing.exitCode === 0 |
| 594 | ? ["checkout", branch] |
| 595 | : ["checkout", "-b", branch, "FETCH_HEAD"], |
| 596 | }); |
| 597 | } else |
| 598 | yield* cli.execute({ |
| 599 | cwd: input.cwd, |
| 600 | args: [ |
| 601 | "pulls", |
| 602 | "checkout", |
| 603 | "--login", |
| 604 | repo.login, |
| 605 | "--repo", |
| 606 | repo.repository, |
| 607 | "--branch", |
| 608 | String(pull.number), |
| 609 | ], |
| 610 | }); |
| 611 | if (input.force) { |
| 612 | // Non-commit server input could become git options. |
| 613 | if (!/^[0-9a-f]{7,64}$/i.test(pull.head.sha)) |
| 614 | return yield* new ForgejoCli.ForgejoCliError({ |
| 615 | command: repo.command ?? "tea", |
| 616 | cwd: input.cwd, |
| 617 | detail: "Forgejo reported a pull request head that is not a commit.", |
| 618 | reason: "invalid-response", |
| 619 | }); |
| 620 | // tea leaves PR branches stale; `--keep` updates them without discarding dirty files. |
| 621 | yield* process.run({ |
| 622 | operation: "ForgejoSourceControlProvider.checkoutChangeRequest", |
| 623 | command: "git", |
| 624 | cwd: input.cwd, |
| 625 | args: ["reset", "--keep", pull.head.sha], |
| 626 | }); |
| 627 | } |
| 628 | }, |
| 629 | (effect, input) => effect.pipe(mapError("checkoutChangeRequest", input.cwd)), |
| 630 | ), |
| 631 | }); |
| 632 | }); |