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

ForgejoSourceControlProvider.ts

636 lines25.4 KB

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