Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Schema from "effect/Schema";
5import * as Result from "effect/Result";
6import * as Clock from "effect/Clock";
7import * as FileSystem from "effect/FileSystem";
8import * as Semaphore from "effect/Semaphore";
9import * as NodeOS from "node:os";
10// @effect-diagnostics-next-line nodeBuiltinImport:off - fj storage paths use explicit Windows and POSIX layouts, independently of this process's platform.
11import * as NodePath from "node:path";
12import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
13import { ChildProcessSpawner } from "effect/unstable/process";
14import { decodeJsonResult } from "@t3tools/shared/schemaJson";
15import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
16import * as VcsProcess from "../vcs/VcsProcess.ts";
17import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
18import type { SourceControlProviderContext } from "./SourceControlProvider.ts";
19
20const encodeApiBody = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
21
22export class ForgejoCliError extends Schema.TaggedError<ForgejoCliError>()("ForgejoCliError", {
23 command: Schema.Literals(["fj", "tea"]),
24 cwd: Schema.String,
25 detail: Schema.String,
26 reason: Schema.optional(
27 Schema.Literals([
28 "missing-cli",
29 "authentication",
30 "forbidden",
31 "not-found",
32 "rate-limit",
33 "invalid-response",
34 ]),
35 ),
36 httpStatus: Schema.optional(Schema.Int),
37 cause: Schema.optional(Schema.Defect()),
38}) {}
39
40export const ForgejoLoginSchema = Schema.Struct({
41 name: Schema.String,
42 url: Schema.String,
43 ssh_host: Schema.optional(Schema.String),
44 valid: Schema.optional(Schema.String),
45 user: Schema.String,
46 default: Schema.String,
47});
48
49export function parseForgejoLogins(raw: string) {
50 const decoded = decodeJsonResult(Schema.Array(ForgejoLoginSchema))(raw);
51 return Result.isSuccess(decoded) ? decoded.success : [];
52}
53
54export const ForgejoKeysSchema = Schema.Struct({
55 hosts: Schema.Record(
56 Schema.String,
57 Schema.Struct({
58 type: Schema.Literals(["Application", "OAuth"]),
59 token: Schema.String,
60 }),
61 ),
62 aliases: Schema.optional(Schema.Record(Schema.String, Schema.String)),
63});
64
65const parseForgejoKeys = decodeJsonResult(ForgejoKeysSchema);
66
67/** Matches fj's directories::ProjectDirs, including its pre-0.6 organization name. */
68function forgejoKeysPaths(input: {
69 readonly platform: string;
70 readonly home: string;
71 readonly dataHome?: string;
72 readonly appData?: string;
73}) {
74 if (input.platform === "darwin")
75 return ["forgejo-cli", "Cyborus"].map((organization) =>
76 NodePath.join(
77 input.home,
78 "Library",
79 "Application Support",
80 `${organization}.forgejo-cli`,
81 "keys.json",
82 ),
83 );
84 if (input.platform === "win32")
85 return ["forgejo-cli", "Cyborus"].map((organization) =>
86 NodePath.win32.join(
87 input.appData || NodePath.win32.join(input.home, "AppData", "Roaming"),
88 organization,
89 "forgejo-cli",
90 "data",
91 "keys.json",
92 ),
93 );
94 return [
95 NodePath.join(
96 input.dataHome && NodePath.isAbsolute(input.dataHome)
97 ? input.dataHome
98 : NodePath.join(input.home, ".local", "share"),
99 "forgejo-cli",
100 "keys.json",
101 ),
102 ];
103}
104
105export interface ForgejoRepositoryInput {
106 readonly cwd: string;
107 readonly context?: SourceControlProviderContext;
108 readonly repository?: string;
109 readonly reference?: string;
110 readonly host?: string;
111}
112
113export interface ForgejoRepository {
114 readonly command?: "fj" | "tea";
115 readonly login: string;
116 readonly repository: string;
117 readonly baseUrl: string;
118}
119
120export interface ForgejoApiInput extends ForgejoRepositoryInput {
121 readonly path: string;
122 readonly method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
123 readonly body?: unknown;
124}
125
126export class ForgejoCli extends Context.Service<
127 ForgejoCli,
128 {
129 readonly execute: (input: {
130 readonly command?: "fj" | "tea";
131 readonly cwd: string;
132 readonly args: ReadonlyArray<string>;
133 readonly stdin?: string;
134 readonly timeoutMs?: number;
135 readonly maxOutputBytes?: number;
136 }) => Effect.Effect<VcsProcess.VcsProcessOutput, ForgejoCliError>;
137 readonly listLogins?: (input: {
138 readonly cwd: string;
139 readonly command: "fj" | "tea";
140 readonly remoteUrl?: string;
141 }) => Effect.Effect<ReturnType<typeof parseForgejoLogins>, ForgejoCliError>;
142 readonly getAccount?: (input: {
143 readonly cwd: string;
144 readonly baseUrl: string;
145 }) => Effect.Effect<string, ForgejoCliError>;
146 readonly resolveRepository: (
147 input: ForgejoRepositoryInput,
148 ) => Effect.Effect<ForgejoRepository, ForgejoCliError>;
149 readonly api: (
150 input: ForgejoApiInput,
151 ) => Effect.Effect<VcsProcess.VcsProcessOutput, ForgejoCliError>;
152 }
153>()("t3/sourceControl/ForgejoCli") {}
154
155export function parseForgejoRemote(value: string) {
156 if (/^(?:https?|ssh):\/\//i.test(value)) {
157 try {
158 const url = new URL(value);
159 return {
160 host: url.host.toLowerCase(),
161 hostname: url.hostname.toLowerCase(),
162 ssh: url.protocol === "ssh:",
163 path: url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/, ""),
164 };
165 } catch {
166 return null;
167 }
168 }
169 // SCP remotes may omit the username; URL treats these as a custom scheme.
170 const ssh = /^(?:[^@/]+@)?([^:/]+):([^/].*)$/.exec(value);
171 return ssh?.[1] && ssh[2]
172 ? {
173 host: ssh[1].toLowerCase(),
174 hostname: ssh[1].toLowerCase(),
175 ssh: true,
176 path: ssh[2].replace(/\.git$/, ""),
177 }
178 : null;
179}
180
181export function matchForgejoLogin(
182 logins: ReturnType<typeof parseForgejoLogins>,
183 remote: NonNullable<ReturnType<typeof parseForgejoRemote>>,
184 requestedHost?: string,
185 hostOnly = false,
186) {
187 const matches = [
188 ...new Map(
189 logins
190 .filter((login) => {
191 const url = parseForgejoRemote(login.url);
192 if (!url) return false;
193 if (requestedHost !== undefined && url.host !== requestedHost.toLowerCase()) return false;
194 return remote.ssh
195 ? login.ssh_host?.toLowerCase() === remote.host ||
196 login.ssh_host?.toLowerCase() === remote.hostname ||
197 url.hostname === remote.hostname
198 : url.host === remote.host &&
199 ((hostOnly && !remote.path) ||
200 !url.path ||
201 remote.path === url.path ||
202 remote.path.startsWith(`${url.path}/`));
203 })
204 .map((login) => [login.name, login]),
205 ).values(),
206 ];
207 return matches.length === 1
208 ? matches[0]
209 : new Set(matches.map((login) => login.url)).size === 1
210 ? matches.find((login) => login.default === "true")
211 : undefined;
212}
213
214export const make = Effect.gen(function* () {
215 const process = yield* VcsProcess.VcsProcess;
216 const fileSystem = yield* FileSystem.FileSystem;
217 const httpClient = yield* HttpClient.HttpClient;
218 const authLock = yield* Semaphore.make(1);
219 const authenticated = new Map<string, { token: string; time: number }>();
220 const execute: ForgejoCli["Service"]["execute"] = (input) =>
221 process
222 .run({
223 ...input,
224 operation: "ForgejoCli.execute",
225 command: input.command ?? "tea",
226 timeoutMs: input.timeoutMs ?? 30_000,
227 })
228 .pipe(
229 Effect.mapError(
230 (cause) =>
231 new ForgejoCliError({
232 command: input.command ?? "tea",
233 cwd: input.cwd,
234 ...(input.command === "fj" ? {} : { cause }),
235 ...(cause._tag === "VcsProcessSpawnError"
236 ? { reason: "missing-cli" as const }
237 : cause._tag === "VcsProcessExitError" && cause.failureKind === "authentication"
238 ? { reason: "authentication" as const }
239 : {}),
240 detail:
241 cause._tag === "VcsProcessSpawnError"
242 ? "Install Forgejo CLI (`fj` 0.6 or later) or Gitea CLI (`tea` 0.16 or later) and retry."
243 : cause._tag === "VcsProcessExitError" && cause.failureKind === "authentication"
244 ? "Authenticate this server with `fj auth login`, `fj auth add-token`, or `tea login add`."
245 : "Forgejo CLI command failed.",
246 }),
247 ),
248 );
249
250 const readKeys = Effect.fn("ForgejoCli.readKeys")(function* (cwd: string) {
251 for (const path of forgejoKeysPaths({
252 platform: yield* HostProcessPlatform,
253 home: NodeOS.homedir(),
254 ...(globalThis.process.env.XDG_DATA_HOME
255 ? { dataHome: globalThis.process.env.XDG_DATA_HOME }
256 : {}),
257 ...(globalThis.process.env.APPDATA ? { appData: globalThis.process.env.APPDATA } : {}),
258 })) {
259 const exists = yield* fileSystem.exists(path).pipe(
260 Effect.mapError(
261 () =>
262 new ForgejoCliError({
263 command: "fj",
264 cwd,
265 reason: "authentication",
266 detail: "Could not read fj authentication storage.",
267 }),
268 ),
269 );
270 if (!exists) continue;
271 const raw = yield* fileSystem.readFileString(path).pipe(
272 Effect.mapError(
273 () =>
274 new ForgejoCliError({
275 command: "fj",
276 cwd,
277 reason: "authentication",
278 detail: "Could not read fj authentication storage.",
279 }),
280 ),
281 );
282 const decoded = parseForgejoKeys(raw);
283 if (Result.isFailure(decoded))
284 return yield* new ForgejoCliError({
285 command: "fj",
286 cwd,
287 reason: "authentication",
288 detail: "fj authentication storage is invalid. Authenticate again with fj.",
289 });
290 return decoded.success;
291 }
292 const empty: typeof ForgejoKeysSchema.Type = { hosts: {}, aliases: {} };
293 return empty;
294 });
295
296 const publicLogins = (
297 keys: typeof ForgejoKeysSchema.Type,
298 remoteUrl?: string,
299 ): ReturnType<typeof parseForgejoLogins> => {
300 const remote = remoteUrl ? parseForgejoRemote(remoteUrl) : null;
301 return Object.keys(keys.hosts).flatMap((host) => {
302 const url = parseForgejoRemote(`https://${host}`);
303 // fj 0.6 drops URL mounts during whoami and OAuth renewal; tea supports them.
304 if (!url || url.path) return [];
305 // fj omits the scheme in storage. Only an explicit matching HTTP remote opts into HTTP.
306 const scheme =
307 remote && !remote.ssh && remote.host === url.host && /^http:\/\//i.test(remoteUrl ?? "")
308 ? "http"
309 : "https";
310 const login = { name: host, url: `${scheme}://${host}`, user: "", default: "false" };
311 const aliases = Object.entries(keys.aliases ?? {})
312 .filter(([, target]) => target === host)
313 .map(([alias]) => ({ ...login, ssh_host: alias }));
314 return aliases.length ? aliases : [login];
315 });
316 };
317
318 const listLogins: NonNullable<ForgejoCli["Service"]["listLogins"]> = Effect.fn(
319 "ForgejoCli.listLogins",
320 )(function* (input) {
321 if (input.command === "fj") {
322 const keys = yield* readKeys(input.cwd).pipe(Effect.result);
323 if (Result.isFailure(keys)) {
324 // Stale credentials from an uninstalled fj must not disable an available tea login.
325 const available = yield* execute({ command: "fj", cwd: input.cwd, args: ["version"] }).pipe(
326 Effect.result,
327 );
328 if (Result.isFailure(available) && available.failure.reason === "missing-cli") return [];
329 return yield* keys.failure;
330 }
331 return publicLogins(keys.success, input.remoteUrl);
332 }
333 return parseForgejoLogins(
334 (yield* execute({ cwd: input.cwd, args: ["login", "list", "--output", "json"] })).stdout,
335 );
336 });
337
338 const requestFj = Effect.fn("ForgejoCli.requestFj")(
339 function* (input: {
340 readonly cwd: string;
341 readonly baseUrl: string;
342 readonly token: string;
343 readonly path: string;
344 readonly method?: ForgejoApiInput["method"];
345 readonly body?: string;
346 }) {
347 const base = new URL(`${input.baseUrl}/api/v1/`);
348 const url = new URL(input.path, base);
349 if (
350 url.origin !== base.origin ||
351 !url.pathname.startsWith(base.pathname) ||
352 url.username ||
353 url.password
354 )
355 return yield* new ForgejoCliError({
356 command: "fj",
357 cwd: input.cwd,
358 detail: "Invalid Forgejo API path.",
359 });
360 let request = HttpClientRequest.make(input.method ?? "GET")(url.toString()).pipe(
361 HttpClientRequest.setHeader("Authorization", `token ${input.token}`),
362 );
363 if (input.body !== undefined)
364 request = request.pipe(HttpClientRequest.bodyText(input.body, "application/json"));
365 const response = yield* httpClient
366 .execute(request)
367 .pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }));
368 const status = response.status;
369 if (status < 200 || status >= 300)
370 return yield* new ForgejoCliError({
371 command: "fj",
372 cwd: input.cwd,
373 httpStatus: status,
374 ...(status === 401
375 ? { reason: "authentication" as const }
376 : status === 403
377 ? { reason: "forbidden" as const }
378 : status === 404
379 ? { reason: "not-found" as const }
380 : status === 429
381 ? { reason: "rate-limit" as const }
382 : {}),
383 detail:
384 status === 404
385 ? "Forgejo repository or pull request was not found."
386 : `Forgejo API request failed (HTTP ${status}). Check this server's fj credentials and permissions.`,
387 });
388 const body =
389 status === 204 || status === 205
390 ? { text: "", truncated: false, invalidUtf8: false }
391 : yield* collectUint8StreamText({
392 stream: response.stream,
393 maxBytes: 8 * 1024 * 1024,
394 });
395 if (body.truncated || body.invalidUtf8)
396 return yield* new ForgejoCliError({
397 command: "fj",
398 cwd: input.cwd,
399 reason: "invalid-response",
400 detail: "Forgejo returned an oversized or invalid response.",
401 });
402 return {
403 exitCode: ChildProcessSpawner.ExitCode(0),
404 stdout: body.text,
405 stderr: `HTTP/1.1 ${status}\n${response.headers.link ? `link: ${response.headers.link}\n` : ""}`,
406 stdoutTruncated: false,
407 stderrTruncated: false,
408 };
409 },
410 (effect, input) =>
411 effect.pipe(
412 Effect.timeout(30_000),
413 Effect.mapError((error) =>
414 error._tag === "ForgejoCliError"
415 ? error
416 : new ForgejoCliError({
417 command: "fj",
418 cwd: input.cwd,
419 detail: "Forgejo API request failed or timed out.",
420 }),
421 ),
422 ),
423 );
424
425 const authenticateFj = Effect.fn("ForgejoCli.authenticateFj")(function* (
426 cwd: string,
427 login: typeof ForgejoLoginSchema.Type,
428 ) {
429 const keys = yield* readKeys(cwd);
430 const token = keys.hosts[login.name]?.token;
431 const now = yield* Clock.currentTimeMillis;
432 const cached = authenticated.get(login.url);
433 if (token && cached?.token === token && now - cached.time < 30_000) return token;
434 yield* execute({ command: "fj", cwd, args: ["--host", login.url, "whoami"] });
435 // fj owns OAuth renewal. Re-read the file after it has refreshed an expired token.
436 const refreshed = (yield* readKeys(cwd)).hosts[login.name]?.token;
437 if (!refreshed)
438 return yield* new ForgejoCliError({
439 command: "fj",
440 cwd,
441 reason: "authentication",
442 detail: "fj has no credentials for this server. Authenticate again with fj.",
443 });
444 authenticated.set(login.url, { token: refreshed, time: now });
445 return refreshed;
446 }, authLock.withPermits(1));
447
448 const getAccount: NonNullable<ForgejoCli["Service"]["getAccount"]> = Effect.fn(
449 "ForgejoCli.getAccount",
450 )(function* (input) {
451 const logins = yield* listLogins({ cwd: input.cwd, command: "fj", remoteUrl: input.baseUrl });
452 const login = logins.find(
453 (item) => item.url.replace(/\/+$/, "") === input.baseUrl.replace(/\/+$/, ""),
454 );
455 if (!login)
456 return yield* new ForgejoCliError({
457 command: "fj",
458 cwd: input.cwd,
459 reason: "authentication",
460 detail: "fj has no credentials for this server.",
461 });
462 const token = yield* authenticateFj(input.cwd, login);
463 const currentUser = yield* requestFj({
464 cwd: input.cwd,
465 baseUrl: login.url.replace(/\/+$/, ""),
466 token,
467 path: "user",
468 });
469 const user = decodeJsonResult(Schema.Struct({ login: Schema.String }))(currentUser.stdout);
470 if (Result.isFailure(user) || !user.success.login.trim())
471 return yield* new ForgejoCliError({
472 command: "fj",
473 cwd: input.cwd,
474 reason: "invalid-response",
475 detail: "Forgejo returned an invalid account response.",
476 });
477 return user.success.login;
478 });
479
480 const resolveTarget = Effect.fn("ForgejoCli.resolveTarget")(function* (
481 input: ForgejoRepositoryInput,
482 hostOnly = false,
483 ) {
484 const referenceRemote = input.reference ? parseForgejoRemote(input.reference) : null;
485 let remoteUrl = [input.reference, input.repository, input.context?.remoteUrl].find(
486 (value) => value && parseForgejoRemote(value),
487 );
488 let remote =
489 referenceRemote ??
490 (input.repository ? parseForgejoRemote(input.repository) : null) ??
491 (input.context ? parseForgejoRemote(input.context.remoteUrl) : null);
492 if (!remote && (!input.repository || input.host)) {
493 const result = yield* process
494 .run({
495 operation: "ForgejoCli.remote",
496 command: "git",
497 args: input.host ? ["remote", "-v"] : ["remote", "get-url", "origin"],
498 cwd: input.cwd,
499 allowNonZeroExit: true,
500 })
501 .pipe(
502 Effect.mapError(
503 (cause) =>
504 new ForgejoCliError({
505 command: "tea",
506 cwd: input.cwd,
507 detail: "Could not resolve the Forgejo repository remote.",
508 cause,
509 }),
510 ),
511 );
512 if (input.host) {
513 const matchingUrls = [
514 ...new Set(
515 result.stdout.split("\n").flatMap((line) => {
516 const url = /^\S+\s+(https?:\/\/\S+)\s+\(fetch\)$/.exec(line.trim())?.[1];
517 return url && parseForgejoRemote(url)?.host === input.host?.toLowerCase()
518 ? [url]
519 : [];
520 }),
521 ),
522 ];
523 const origins = [...new Set(matchingUrls.map((url) => new URL(url).origin))];
524 remoteUrl =
525 matchingUrls.length === 1
526 ? matchingUrls[0]
527 : origins.length === 1
528 ? origins[0]
529 : undefined;
530 } else {
531 remoteUrl = result.stdout.trim();
532 }
533 remote = remoteUrl ? parseForgejoRemote(remoteUrl) : null;
534 }
535 if (
536 input.host &&
537 !remote?.ssh &&
538 remote?.host !== input.host.toLowerCase() &&
539 remote?.hostname !== input.host.toLowerCase()
540 )
541 remote = {
542 host: input.host.toLowerCase(),
543 hostname: input.host.split(":")[0] ?? input.host,
544 ssh: false,
545 path: remote?.path ?? "",
546 };
547 const schemeRemoteUrl = remote?.ssh ? input.context?.provider.baseUrl : remoteUrl;
548 const fjLogins = yield* listLogins({
549 cwd: input.cwd,
550 command: "fj",
551 ...(schemeRemoteUrl ? { remoteUrl: schemeRemoteUrl } : {}),
552 });
553 const requestedHost = input.host ?? input.context?.requestedHost;
554 const matchHostOnly = hostOnly || (!!input.host && !remote?.path);
555 const selectLogin = (logins: ReturnType<typeof parseForgejoLogins>) =>
556 remote
557 ? matchForgejoLogin(logins, remote, remote.ssh ? requestedHost : undefined, matchHostOnly)
558 : (logins.find((item) => item.default === "true") ??
559 (new Set(logins.map((item) => item.name)).size === 1 ? logins[0] : undefined));
560 let login = selectLogin(fjLogins);
561 let command: "fj" | "tea" = "fj";
562 if (
563 !login &&
564 fjLogins.some(
565 (item) =>
566 !remote ||
567 matchForgejoLogin([item], remote, remote.ssh ? requestedHost : undefined, matchHostOnly),
568 )
569 ) {
570 const available = yield* execute({ command: "fj", cwd: input.cwd, args: ["version"] }).pipe(
571 Effect.result,
572 );
573 if (Result.isSuccess(available))
574 return yield* new ForgejoCliError({
575 command: "fj",
576 cwd: input.cwd,
577 reason: "authentication",
578 detail: "Multiple fj logins match this repository. Specify its full server URL.",
579 });
580 if (available.failure.reason !== "missing-cli") return yield* available.failure;
581 }
582 if (login) {
583 const auth = yield* authenticateFj(input.cwd, login).pipe(Effect.result);
584 if (Result.isFailure(auth)) {
585 if (auth.failure.reason === "missing-cli") login = undefined;
586 else return yield* auth.failure;
587 }
588 }
589 if (!login) {
590 command = "tea";
591 login = selectLogin(yield* listLogins({ cwd: input.cwd, command: "tea" }));
592 }
593 if (!login)
594 return yield* new ForgejoCliError({
595 command: "tea",
596 cwd: input.cwd,
597 reason: "authentication",
598 detail:
599 "No matching Forgejo login. Use `fj auth login`, `fj auth add-token`, or `tea login add` for this server; choose a default when multiple tea accounts match.",
600 });
601 if (hostOnly)
602 return { command, login: login.name, repository: "", baseUrl: login.url.replace(/\/+$/, "") };
603 const path =
604 referenceRemote?.path ??
605 (input.repository && !parseForgejoRemote(input.repository)
606 ? input.repository
607 : remote?.path) ??
608 "";
609 const basePath = new URL(login.url).pathname.replace(/^\/+|\/+$/g, "");
610 const relativePath =
611 basePath && path.split("/").length > 2 && path.startsWith(`${basePath}/`)
612 ? path.slice(basePath.length + 1)
613 : path;
614 const repositoryPath = relativePath.replace(/\/pulls\/\d+.*$/, "").replace(/\.git$/, "");
615 if (command === "fj" && !repositoryPath.includes("/")) {
616 login = { ...login, user: yield* getAccount({ cwd: input.cwd, baseUrl: login.url }) };
617 }
618 const repository = repositoryPath.includes("/")
619 ? repositoryPath
620 : `${login.user}/${repositoryPath}`;
621 if (!/^[^/\s]+\/[^/\s]+$/.test(repository))
622 return yield* new ForgejoCliError({
623 command,
624 cwd: input.cwd,
625 detail: "Specify a Forgejo repository as owner/repository or its full server URL.",
626 });
627 return { command, login: login.name, repository, baseUrl: login.url.replace(/\/+$/, "") };
628 });
629 const resolveRepository = (input: ForgejoRepositoryInput) => resolveTarget(input);
630 const api = Effect.fn("ForgejoCli.api")(function* (input: ForgejoApiInput) {
631 const repository = yield* resolveTarget(
632 input,
633 input.path.replace(/^\/+/, "") === "user" && (!input.method || input.method === "GET"),
634 );
635 const stdin =
636 input.body === undefined
637 ? undefined
638 : yield* encodeApiBody(input.body).pipe(
639 Effect.mapError(
640 (cause) =>
641 new ForgejoCliError({
642 command: "tea",
643 cwd: input.cwd,
644 detail: "Could not encode the Forgejo request body.",
645 cause,
646 }),
647 ),
648 );
649 let path = input.path.replace(/^\/+/, "");
650 if (input.repository && input.repository !== repository.repository) {
651 // Repository identities retain the server mount path; API routes do not.
652 const prefix = `repos/${input.repository.split("/").map(encodeURIComponent).join("/")}`;
653 if (path === prefix || path.startsWith(`${prefix}/`) || path.startsWith(`${prefix}?`)) {
654 path = `repos/${repository.repository.split("/").map(encodeURIComponent).join("/")}${path.slice(prefix.length)}`;
655 }
656 }
657 if (repository.command === "fj") {
658 const token = (yield* readKeys(input.cwd)).hosts[repository.login]?.token;
659 if (!token)
660 return yield* new ForgejoCliError({
661 command: "fj",
662 cwd: input.cwd,
663 reason: "authentication",
664 detail: "fj has no credentials for this server.",
665 });
666 return yield* requestFj({
667 cwd: input.cwd,
668 baseUrl: repository.baseUrl,
669 token,
670 path,
671 ...(input.method === undefined ? {} : { method: input.method }),
672 ...(stdin === undefined ? {} : { body: stdin }),
673 });
674 }
675 const result = yield* execute({
676 cwd: input.cwd,
677 args: [
678 "api",
679 "--include",
680 "--login",
681 repository.login,
682 ...(repository.repository ? ["--repo", repository.repository] : []),
683 "--method",
684 input.method ?? "GET",
685 ...(input.body === undefined ? [] : ["--data", "@-"]),
686 `${repository.baseUrl}/api/v1/${path}`,
687 ],
688 ...(stdin === undefined ? {} : { stdin }),
689 });
690 // tea reports HTTP failures with exit code zero; use its response status.
691 const status = Number(/^HTTP\/\S+ (\d{3})/m.exec(result.stderr)?.[1]);
692 if (!status || status >= 400)
693 return yield* new ForgejoCliError({
694 command: "tea",
695 cwd: input.cwd,
696 ...(status ? { httpStatus: status } : {}),
697 ...(status === 401
698 ? { reason: "authentication" as const }
699 : status === 403
700 ? { reason: "forbidden" as const }
701 : status === 404
702 ? { reason: "not-found" as const }
703 : status === 429
704 ? { reason: "rate-limit" as const }
705 : {}),
706 detail:
707 status === 401 || status === 403
708 ? "Forgejo denied access. Check this server's `tea login` credentials and permissions."
709 : status === 404
710 ? "Forgejo repository or pull request was not found."
711 : status === 429
712 ? "Forgejo API rate limit exceeded."
713 : `Forgejo API request failed${status ? ` (HTTP ${status})` : " without an HTTP status"}.`,
714 });
715 return result;
716 });
717 return ForgejoCli.of({ execute, listLogins, getAccount, resolveRepository, api });
718});
719
720export const layer = Layer.effect(ForgejoCli, make);