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