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: (input) =>
360 getPull(input).pipe(
361 Effect.map(toForgejoChangeRequest),
362 mapError("getChangeRequest", input.cwd),
363 ),
364 createChangeRequest: Effect.fn("ForgejoSourceControlProvider.createChangeRequest")(
365 function* (input) {
366 const repo = yield* cli.resolveRepository(input);
367 const source = SourceControlProvider.sourceControlRefFromInput(input);
368 const owner = source?.owner ?? source?.repository?.split("/")[0];
369 const head = SourceControlProvider.sourceBranch(input);
370 yield* cli.api({
371 ...input,
372 path: `${repositoryPath(input.target?.repository ?? repo.repository)}/pulls`,
373 method: "POST",
374 body: {
375 base: input.target?.refName ?? input.baseRefName,
376 head: owner ? `${owner}:${head}` : head,
377 title: input.title,
378 body: yield* fs.readFileString(input.bodyFile),
379 },
380 });
381 },
382 (effect, input) => effect.pipe(mapError("createChangeRequest", input.cwd)),
383 ),
384 getRepositoryCloneUrls: Effect.fn("ForgejoSourceControlProvider.getRepositoryCloneUrls")(
385 function* (input) {
386 const repo = yield* cli.resolveRepository(input);
387 return cloneUrls(
388 yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema),
389 );
390 },
391 (effect, input) => effect.pipe(mapError("getRepositoryCloneUrls", input.cwd)),
392 ),
393 createRepository: Effect.fn("ForgejoSourceControlProvider.createRepository")(
394 function* (input) {
395 const repo = yield* cli.resolveRepository(input);
396 const user = yield* request(
397 { ...input, path: "user" },
398 Schema.Struct({ login: Schema.String }),
399 );
400 const [owner, name] = repo.repository.split("/");
401 return cloneUrls(
402 yield* request(
403 {
404 ...input,
405 path:
406 owner === user.login
407 ? "user/repos"
408 : `orgs/${encodeURIComponent(owner ?? "")}/repos`,
409 method: "POST",
410 body: { name, private: input.visibility === "private", auto_init: false },
411 },
412 RepositorySchema,
413 ),
414 );
415 },
416 (effect, input) => effect.pipe(mapError("createRepository", input.cwd)),
417 ),
418 getDefaultBranch: Effect.fn("ForgejoSourceControlProvider.getDefaultBranch")(
419 function* (input) {
420 const repo = yield* cli.resolveRepository(input);
421 return (
422 (yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema))
423 .default_branch ?? null
424 );
425 },
426 (effect, input) => effect.pipe(mapError("getDefaultBranch", input.cwd)),
427 ),
428 checkoutChangeRequest: Effect.fn("ForgejoSourceControlProvider.checkoutChangeRequest")(
429 function* (input) {
430 const repo = yield* cli.resolveRepository(input);
431 const pull = yield* getPull(input);
432 if (repo.command === "fj") {
433 // fj checkout cannot target a repository outside the local remotes.
434 const urls = yield* request(
435 { ...input, path: repositoryPath(repo.repository) },
436 RepositorySchema,
437 );
438 const remote = input.context?.remoteUrl;
439 const useSsh = remote && ForgejoCli.parseForgejoRemote(remote)?.ssh;
440 yield* process.run({
441 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
442 command: "git",
443 cwd: input.cwd,
444 args: [
445 "fetch",
446 "--",
447 useSsh ? urls.ssh_url : urls.clone_url,
448 `refs/pull/${pull.number}/head`,
449 ],
450 });
451 const branch = `pulls/${pull.number}`;
452 const existing = yield* process.run({
453 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
454 command: "git",
455 cwd: input.cwd,
456 args: ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`],
457 allowNonZeroExit: true,
458 });
459 yield* process.run({
460 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
461 command: "git",
462 cwd: input.cwd,
463 args:
464 existing.exitCode === 0
465 ? ["checkout", branch]
466 : ["checkout", "-b", branch, "FETCH_HEAD"],
467 });
468 } else
469 yield* cli.execute({
470 cwd: input.cwd,
471 args: [
472 "pulls",
473 "checkout",
474 "--login",
475 repo.login,
476 "--repo",
477 repo.repository,
478 "--branch",
479 String(pull.number),
480 ],
481 });
482 if (input.force) {
483 // Non-commit server input could become git options.
484 if (!/^[0-9a-f]{7,64}$/i.test(pull.head.sha))
485 return yield* new ForgejoCli.ForgejoCliError({
486 command: repo.command ?? "tea",
487 cwd: input.cwd,
488 detail: "Forgejo reported a pull request head that is not a commit.",
489 reason: "invalid-response",
490 });
491 // tea leaves PR branches stale; `--keep` updates them without discarding dirty files.
492 yield* process.run({
493 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
494 command: "git",
495 cwd: input.cwd,
496 args: ["reset", "--keep", pull.head.sha],
497 });
498 }
499 },
500 (effect, input) => effect.pipe(mapError("checkoutChangeRequest", input.cwd)),
501 ),
502 });
503});