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

ForgejoSourceControlProvider.ts

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