Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Schema from "effect/Schema";
5import * as Result from "effect/Result";
6import { SourceControlProviderError } from "@t3tools/contracts";
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
9import * as ForgejoCli from "./ForgejoCli.ts";
10import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
11import {
12 isMissingExecutable,
13 providerAuth,
14 probeSourceControlProvider,
15 type SourceControlCliDiscoverySpec,
16 type SourceControlManagedCliDiscoverySpec,
17} from "@t3tools/source-control-core/server/discovery";
18import { ForgejoPullRequestSchema, toForgejoChangeRequest } from "./forgejoPullRequests.ts";
19
20const isForgejoCliError = Schema.is(ForgejoCli.ForgejoCliError);
21
22export const discovery = {
23 type: "cli",
24 kind: SourceControlProviderKind.make("forgejo"),
25 label: "Forgejo / Gitea",
26 executable: "tea",
27 versionArgs: ["--version"],
28 authArgs: ["login", "status", "--output", "json"],
29 remoteRefinementArgs: () => ["login", "list", "--output", "json"],
30 parseAuth: (input) => {
31 const logins = ForgejoCli.parseForgejoLogins(input.stdout);
32 const login = logins.find((entry) => entry.default === "true") ?? logins[0];
33 return login
34 ? providerAuth({
35 status: login.valid === "true" ? "authenticated" : "unauthenticated",
36 account: login.user,
37 host: ForgejoCli.parseForgejoRemote(login.url)?.host,
38 })
39 : providerAuth({
40 status: "unauthenticated",
41 detail: "Run `tea login add` to authenticate a Forgejo or Gitea server.",
42 });
43 },
44 refineUnknownRemote: (input) => {
45 const remote = ForgejoCli.parseForgejoRemote(input.context.remoteUrl);
46 const login =
47 remote &&
48 ForgejoCli.matchForgejoLogin(
49 ForgejoCli.parseForgejoLogins(input.auth.stdout),
50 remote,
51 input.context.requestedHost,
52 );
53 return login
54 ? {
55 kind: SourceControlProviderKind.make("forgejo"),
56 name: "Forgejo / Gitea",
57 baseUrl: login.url,
58 }
59 : null;
60 },
61 installHint:
62 "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.",
63} satisfies SourceControlCliDiscoverySpec;
64
65export const makeDiscovery = Effect.gen(function* () {
66 const cli = yield* ForgejoCli.ForgejoCli;
67 const { process } = yield* SourceControlHost.SourceControlHost;
68 const listLogins = cli.listLogins;
69 if (!listLogins) return discovery;
70 return {
71 type: "managed-cli",
72 kind: SourceControlProviderKind.make("forgejo"),
73 label: discovery.label,
74 installHint: discovery.installHint,
75 probe: Effect.fn("ForgejoSourceControlProvider.discovery")(function* (cwd: string) {
76 const remoteUrl = yield* process
77 .run({
78 operation: "source-control.discovery.remote",
79 command: "git",
80 args: ["remote", "get-url", "origin"],
81 cwd,
82 allowNonZeroExit: true,
83 timeoutMs: 5_000,
84 maxOutputBytes: 8_000,
85 })
86 .pipe(
87 Effect.map((result) => result.stdout.trim()),
88 Effect.orElseSucceed(() => ""),
89 );
90 const credentials = yield* Effect.result(listLogins({ cwd, command: "fj", remoteUrl }));
91 const logins = Result.isSuccess(credentials) ? credentials.success : [];
92 const remote = ForgejoCli.parseForgejoRemote(remoteUrl);
93 const login =
94 (remote && ForgejoCli.matchForgejoLogin(logins, remote)) ||
95 logins.find((entry) => entry.default === "true") ||
96 logins[0];
97 const fj = yield* probeSourceControlProvider({
98 // fj reads the cwd repository even with --host and fails on an unborn branch.
99 cwd: yield* HostProcess.HomeDirectory,
100 process,
101 spec: {
102 ...discovery,
103 executable: "fj",
104 versionArgs: ["version"],
105 authArgs: login ? ["--host", login.url, "whoami"] : ["auth", "list"],
106 parseAuth: (result) =>
107 Result.isFailure(credentials)
108 ? providerAuth({
109 status: "unknown",
110 detail: "Could not read fj authentication storage. Authenticate again with fj.",
111 })
112 : login && result.exitCode === 0
113 ? providerAuth({
114 status: "authenticated",
115 account: login.user,
116 host: ForgejoCli.parseForgejoRemote(login.url)?.host,
117 })
118 : // fj prints this for transport failures (TLS, connect, DNS), never for a rejected token.
119 login && result.stderr.includes("error sending request for url")
120 ? providerAuth({
121 status: "unknown",
122 detail: `Could not reach ${login.url} to verify the fj login.`,
123 host: ForgejoCli.parseForgejoRemote(login.url)?.host,
124 })
125 : providerAuth({
126 status: "unauthenticated",
127 detail:
128 "Authenticate this server with `fj --host <server-url> auth add-token`.",
129 }),
130 },
131 });
132 if (fj.status === "available" && (login || Result.isFailure(credentials))) {
133 if (login && fj.auth.status === "authenticated" && cli.getAccount) {
134 const account = yield* cli.getAccount({ cwd, baseUrl: login.url }).pipe(Effect.result);
135 return {
136 ...fj,
137 auth: Result.isSuccess(account)
138 ? providerAuth({
139 status: "authenticated",
140 account: account.success,
141 host: ForgejoCli.parseForgejoRemote(login.url)?.host,
142 })
143 : providerAuth({
144 status: "unknown",
145 detail: account.failure.detail,
146 host: ForgejoCli.parseForgejoRemote(login.url)?.host,
147 }),
148 };
149 }
150 return fj;
151 }
152 const tea = yield* probeSourceControlProvider({ cwd, process, spec: discovery });
153 // Discovery keeps the install hint only for an absent executable; a slow or broken fj
154 // explains itself better than tea's install advice.
155 const fjAbsent = fj.status === "missing" && fj.installHint === discovery.installHint;
156 return tea.status === "available" || fjAbsent ? tea : fj;
157 }),
158 refineUnknownRemote: Effect.fn("ForgejoSourceControlProvider.refineUnknownRemote")(
159 function* (input: {
160 readonly cwd: string;
161 readonly context: SourceControlProvider.SourceControlProviderContext;
162 }) {
163 const remote = ForgejoCli.parseForgejoRemote(input.context.remoteUrl);
164 if (!remote) return null;
165 let failure: ForgejoCli.ForgejoCliError | undefined;
166 for (const command of ["fj", "tea"] as const) {
167 const logins = yield* listLogins({
168 cwd: input.cwd,
169 command,
170 remoteUrl: input.context.remoteUrl,
171 }).pipe(
172 Effect.catchIf(
173 (error) => isMissingExecutable(error.cause),
174 () => Effect.succeed([]),
175 ),
176 Effect.result,
177 );
178 if (Result.isFailure(logins)) {
179 failure ??= logins.failure;
180 continue;
181 }
182 const login = ForgejoCli.matchForgejoLogin(
183 logins.success,
184 remote,
185 input.context.requestedHost,
186 );
187 if (login)
188 return {
189 kind: SourceControlProviderKind.make("forgejo"),
190 name: discovery.label,
191 baseUrl: login.url,
192 };
193 }
194 if (failure) return yield* failure;
195 return null;
196 },
197 ),
198 } satisfies SourceControlManagedCliDiscoverySpec;
199});
200
201export function repositoryNameFromRemoteUrl(url: string): string | null {
202 const path = SourceControlProvider.repositoryPathFromRemoteUrl(url);
203 return path === null || !/^https?:\/\//iu.test(url.trim())
204 ? path
205 : path.split("/").slice(-2).join("/");
206}
207
208// Resolve browser URLs from the serving login to handle SSH aliases and mounts.
209const refineRepositoryIdentity: NonNullable<
210 SourceControlProvider.SourceControlProvider["Service"]["refineRepositoryIdentity"]
211> = Effect.fn("ForgejoSourceControlProvider.refineRepositoryIdentity")(function* ({
212 identity,
213 resolveContext,
214}) {
215 const remote = ForgejoCli.parseForgejoRemote(identity.locator.remoteUrl);
216 if (
217 !remote ||
218 !identity.rootPath ||
219 (identity.provider !== undefined &&
220 identity.provider !== "unknown" &&
221 identity.provider !== "forgejo")
222 )
223 return identity;
224 const context = yield* resolveContext({
225 cwd: identity.rootPath,
226 context: {
227 provider: { kind: SourceControlProviderKind.make("unknown"), name: "Unknown", baseUrl: "" },
228 remoteName: identity.locator.remoteName,
229 remoteUrl: identity.locator.remoteUrl,
230 },
231 });
232 if (context?.provider.kind !== "forgejo") return identity;
233 const baseUrl = context.provider.baseUrl.replace(/\/+$/, "");
234 const basePath = new URL(baseUrl).pathname.replace(/^\/+|\/+$/g, "");
235 const path =
236 !remote.ssh && basePath && remote.path.startsWith(`${basePath}/`)
237 ? remote.path.slice(basePath.length + 1)
238 : remote.path;
239 return {
240 ...identity,
241 provider: SourceControlProviderKind.make("forgejo"),
242 webUrl: `${baseUrl}/${path}`,
243 };
244});
245
246// An SSH remote names an alias rather than the web server, so the login that serves it says which.
247const resolveRemoteWebHost: NonNullable<
248 SourceControlProvider.SourceControlProvider["Service"]["resolveRemoteWebHost"]
249> = Effect.fn("ForgejoSourceControlProvider.resolveRemoteWebHost")(function* ({
250 cwd,
251 context,
252 resolveContext,
253}) {
254 if (!ForgejoCli.parseForgejoRemote(context.remoteUrl)?.ssh) return null;
255 const resolved = yield* resolveContext({
256 cwd,
257 context: {
258 ...context,
259 provider: { kind: SourceControlProviderKind.make("unknown"), name: "Unknown", baseUrl: "" },
260 },
261 });
262 return resolved?.provider.kind === "forgejo"
263 ? new URL(resolved.provider.baseUrl).host.toLowerCase()
264 : null;
265});
266
267const RepositorySchema = Schema.Struct({
268 full_name: Schema.String,
269 clone_url: Schema.String,
270 ssh_url: Schema.String,
271 default_branch: Schema.optional(Schema.NullOr(Schema.String)),
272});
273const cloneUrls = (raw: typeof RepositorySchema.Type) => ({
274 nameWithOwner: raw.full_name,
275 url: raw.clone_url,
276 sshUrl: raw.ssh_url,
277});
278const repositoryPath = (repository: string) =>
279 `repos/${repository.split("/").map(encodeURIComponent).join("/")}`;
280
281export const make = Effect.gen(function* () {
282 const cli = yield* ForgejoCli.ForgejoCli;
283 const fs = yield* FileSystem.FileSystem;
284 const { process } = yield* SourceControlHost.SourceControlHost;
285 const request = <S extends Schema.Codec<unknown, unknown, never, never>>(
286 input: ForgejoCli.ForgejoApiInput,
287 schema: S,
288 ) =>
289 cli.api(input).pipe(
290 Effect.flatMap((result) =>
291 Schema.decodeEffect(Schema.fromJsonString(schema))(result.stdout).pipe(
292 Effect.mapError(
293 (cause) =>
294 new ForgejoCli.ForgejoCliError({
295 command: "tea",
296 cwd: input.cwd,
297 detail: "Forgejo API returned an invalid response.",
298 reason: "invalid-response",
299 cause,
300 }),
301 ),
302 ),
303 ),
304 );
305 const mapError = (operation: string, cwd: string) =>
306 Effect.mapError(
307 (cause: unknown) =>
308 new SourceControlProviderError({
309 provider: SourceControlProviderKind.make("forgejo"),
310 operation,
311 cwd,
312 ...(isForgejoCliError(cause) ? { command: cause.command } : {}),
313 detail: isForgejoCliError(cause) ? cause.detail : "Forgejo operation failed.",
314 cause,
315 }),
316 );
317 const getPull = Effect.fn("ForgejoSourceControlProvider.getPull")(function* (
318 input: Parameters<
319 SourceControlProvider.SourceControlProvider["Service"]["getChangeRequest"]
320 >[0],
321 ) {
322 const repo = yield* cli.resolveRepository(input);
323 const number = /(?:^#?|\/pulls\/)(\d+)(?:\/[^?#]*)?(?:[?#].*)?$/.exec(input.reference)?.[1];
324 if (!number)
325 return yield* new ForgejoCli.ForgejoCliError({
326 command: "tea",
327 cwd: input.cwd,
328 detail: "Specify a pull request number or Forgejo pull request URL.",
329 });
330 return yield* request(
331 { ...input, path: `${repositoryPath(repo.repository)}/pulls/${number}` },
332 ForgejoPullRequestSchema,
333 );
334 });
335 return SourceControlProvider.SourceControlProvider.of({
336 kind: SourceControlProviderKind.make("forgejo"),
337 repositoryNameFromRemoteUrl,
338 refineRepositoryIdentity,
339 resolveRemoteWebHost,
340 listChangeRequests: Effect.fn("ForgejoSourceControlProvider.listChangeRequests")(
341 function* (input) {
342 const repo = yield* cli.resolveRepository(input);
343 const source = SourceControlProvider.sourceControlRefFromInput(input);
344 const branch = SourceControlProvider.sourceBranch(input);
345 const results: ReturnType<typeof toForgejoChangeRequest>[] = [];
346 const limit = input.limit ?? 20;
347 for (let page = 1; results.length < limit; page++) {
348 const items = yield* request(
349 {
350 ...input,
351 path: `${repositoryPath(repo.repository)}/pulls?state=${input.state === "merged" ? "closed" : input.state}&head=${encodeURIComponent(branch)}&sort=recentupdate&limit=50&page=${page}`,
352 },
353 Schema.Array(ForgejoPullRequestSchema),
354 );
355 for (const item of items) {
356 const normalized = toForgejoChangeRequest(item);
357 if (
358 normalized.headRefName !== branch ||
359 (source?.repository && item.head.repo?.full_name !== source.repository) ||
360 (source?.owner && item.head.repo?.owner.login !== source.owner)
361 )
362 continue;
363 if (input.state === "all" || normalized.state === input.state) results.push(normalized);
364 }
365 if (items.length === 0) break;
366 }
367 return results.slice(0, limit);
368 },
369 (effect, input) => effect.pipe(mapError("listChangeRequests", input.cwd)),
370 ),
371 getChangeRequest: Effect.fn("ForgejoSourceControlProvider.getChangeRequest")(function (input) {
372 return getPull(input).pipe(
373 Effect.map(toForgejoChangeRequest),
374 mapError("getChangeRequest", input.cwd),
375 );
376 }),
377 createChangeRequest: Effect.fn("ForgejoSourceControlProvider.createChangeRequest")(
378 function* (input) {
379 const repo = yield* cli.resolveRepository(input);
380 const source = SourceControlProvider.sourceControlRefFromInput(input);
381 const owner = source?.owner ?? source?.repository?.split("/")[0];
382 const head = SourceControlProvider.sourceBranch(input);
383 yield* cli.api({
384 ...input,
385 path: `${repositoryPath(input.target?.repository ?? repo.repository)}/pulls`,
386 method: "POST",
387 body: {
388 base: input.target?.refName ?? input.baseRefName,
389 head: owner ? `${owner}:${head}` : head,
390 title: input.title,
391 body: yield* fs.readFileString(input.bodyFile),
392 },
393 });
394 },
395 (effect, input) => effect.pipe(mapError("createChangeRequest", input.cwd)),
396 ),
397 getRepositoryCloneUrls: Effect.fn("ForgejoSourceControlProvider.getRepositoryCloneUrls")(
398 function* (input) {
399 const repo = yield* cli.resolveRepository(input);
400 return cloneUrls(
401 yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema),
402 );
403 },
404 (effect, input) => effect.pipe(mapError("getRepositoryCloneUrls", input.cwd)),
405 ),
406 createRepository: Effect.fn("ForgejoSourceControlProvider.createRepository")(
407 function* (input) {
408 const repo = yield* cli.resolveRepository(input);
409 const user = yield* request(
410 { ...input, path: "user" },
411 Schema.Struct({ login: Schema.String }),
412 );
413 const [owner, name] = repo.repository.split("/");
414 return cloneUrls(
415 yield* request(
416 {
417 ...input,
418 path:
419 owner === user.login
420 ? "user/repos"
421 : `orgs/${encodeURIComponent(owner ?? "")}/repos`,
422 method: "POST",
423 body: { name, private: input.visibility === "private", auto_init: false },
424 },
425 RepositorySchema,
426 ),
427 );
428 },
429 (effect, input) => effect.pipe(mapError("createRepository", input.cwd)),
430 ),
431 getDefaultBranch: Effect.fn("ForgejoSourceControlProvider.getDefaultBranch")(
432 function* (input) {
433 const repo = yield* cli.resolveRepository(input);
434 return (
435 (yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema))
436 .default_branch ?? null
437 );
438 },
439 (effect, input) => effect.pipe(mapError("getDefaultBranch", input.cwd)),
440 ),
441 checkoutChangeRequest: Effect.fn("ForgejoSourceControlProvider.checkoutChangeRequest")(
442 function* (input) {
443 const repo = yield* cli.resolveRepository(input);
444 const pull = yield* getPull(input);
445 if (repo.command === "fj") {
446 // fj checkout cannot target a repository outside the local remotes.
447 const urls = yield* request(
448 { ...input, path: repositoryPath(repo.repository) },
449 RepositorySchema,
450 );
451 const remote = input.context?.remoteUrl;
452 const useSsh = remote && ForgejoCli.parseForgejoRemote(remote)?.ssh;
453 yield* process.run({
454 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
455 command: "git",
456 cwd: input.cwd,
457 args: [
458 "fetch",
459 "--",
460 useSsh ? urls.ssh_url : urls.clone_url,
461 `refs/pull/${pull.number}/head`,
462 ],
463 });
464 const branch = `pulls/${pull.number}`;
465 const existing = yield* process.run({
466 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
467 command: "git",
468 cwd: input.cwd,
469 args: ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`],
470 allowNonZeroExit: true,
471 });
472 yield* process.run({
473 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
474 command: "git",
475 cwd: input.cwd,
476 args:
477 existing.exitCode === 0
478 ? ["checkout", branch]
479 : ["checkout", "-b", branch, "FETCH_HEAD"],
480 });
481 } else
482 yield* cli.execute({
483 cwd: input.cwd,
484 args: [
485 "pulls",
486 "checkout",
487 "--login",
488 repo.login,
489 "--repo",
490 repo.repository,
491 "--branch",
492 String(pull.number),
493 ],
494 });
495 if (input.force) {
496 // Non-commit server input could become git options.
497 if (!/^[0-9a-f]{7,64}$/i.test(pull.head.sha))
498 return yield* new ForgejoCli.ForgejoCliError({
499 command: repo.command ?? "tea",
500 cwd: input.cwd,
501 detail: "Forgejo reported a pull request head that is not a commit.",
502 reason: "invalid-response",
503 });
504 // tea leaves PR branches stale; `--keep` updates them without discarding dirty files.
505 yield* process.run({
506 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
507 command: "git",
508 cwd: input.cwd,
509 args: ["reset", "--keep", pull.head.sha],
510 });
511 }
512 },
513 (effect, input) => effect.pipe(mapError("checkoutChangeRequest", input.cwd)),
514 ),
515 });
516});