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

ForgejoSourceControlProvider.ts

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