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
21// The registry shares a verdict among the HTTP remotes of one mount, the path before
22// `owner/repo`. A login mounted below it serves some of them and not others, so a verdict made
23// while one is listed is not settled. SSH matching ignores the path.
24function hasLoginBelowMount(
25 logins: ReturnType<typeof ForgejoCli.parseForgejoLogins>,
26 remote: NonNullable<ReturnType<typeof ForgejoCli.parseForgejoRemote>>,
27) {
28 if (remote.ssh) return false;
29 const mount = remote.path.split("/").slice(0, -2).join("/");
30 return logins.some((login) => {
31 const url = ForgejoCli.parseForgejoRemote(login.url);
32 return (
33 url?.host === remote.host &&
34 url.path !== "" &&
35 (mount === "" || url.path.startsWith(`${mount}/`))
36 );
37 });
38}
39
40export const discovery = {
41 type: "cli",
42 kind: SourceControlProviderKind.make("forgejo"),
43 label: "Forgejo / Gitea",
44 executable: "tea",
45 versionArgs: ["--version"],
46 authArgs: ["login", "status", "--output", "json"],
47 remoteRefinementArgs: ["login", "list", "--output", "json"],
48 parseAuth: (input) => {
49 const logins = ForgejoCli.parseForgejoLogins(input.stdout);
50 const login = logins.find((entry) => entry.default === "true") ?? logins[0];
51 return login
52 ? providerAuth({
53 status: login.valid === "true" ? "authenticated" : "unauthenticated",
54 account: login.user,
55 host: ForgejoCli.parseForgejoRemote(login.url)?.host,
56 })
57 : providerAuth({
58 status: "unauthenticated",
59 detail: "Run `tea login add` to authenticate a Forgejo or Gitea server.",
60 });
61 },
62 refineUnknownRemote: (input) => {
63 const remote = ForgejoCli.parseForgejoRemote(input.context.remoteUrl);
64 if (!remote) return { provider: null, settled: true };
65 // Output that is not a login list (a failed command, a config tea could not read) holds no
66 // answer, so only a list that decodes can settle.
67 const decoded = ForgejoCli.decodeForgejoLogins(input.auth.stdout);
68 const logins = Result.isSuccess(decoded) ? decoded.success : [];
69 const login = ForgejoCli.matchForgejoLogin(logins, remote, input.context.requestedHost);
70 return {
71 provider: login
72 ? {
73 kind: SourceControlProviderKind.make("forgejo"),
74 name: "Forgejo / Gitea",
75 baseUrl: login.url,
76 }
77 : null,
78 settled: Result.isSuccess(decoded) && !hasLoginBelowMount(logins, remote),
79 };
80 },
81 installHint:
82 "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.",
83} satisfies SourceControlCliDiscoverySpec;
84
85export const makeDiscovery = Effect.gen(function* () {
86 const cli = yield* ForgejoCli.ForgejoCli;
87 const { process } = yield* SourceControlHost.SourceControlHost;
88 const listLogins = cli.listLogins;
89 if (!listLogins) return discovery;
90 return {
91 type: "managed-cli",
92 kind: SourceControlProviderKind.make("forgejo"),
93 label: discovery.label,
94 installHint: discovery.installHint,
95 probe: Effect.fn("ForgejoSourceControlProvider.discovery")(function* (cwd: string) {
96 const remoteUrl = yield* process
97 .run({
98 operation: "source-control.discovery.remote",
99 command: "git",
100 args: ["remote", "get-url", "origin"],
101 cwd,
102 allowNonZeroExit: true,
103 timeoutMs: 5_000,
104 maxOutputBytes: 8_000,
105 })
106 .pipe(
107 Effect.map((result) => result.stdout.trim()),
108 Effect.orElseSucceed(() => ""),
109 );
110 const credentials = yield* listLogins({ cwd, command: "fj", remoteUrl }).pipe(
111 // An fj that cannot run holds no login, so the probe falls back to tea.
112 Effect.catchIf(
113 (error) => error.reason === "missing-cli",
114 (): Effect.Effect<ReturnType<typeof ForgejoCli.parseForgejoLogins>> => Effect.succeed([]),
115 ),
116 Effect.result,
117 );
118 const logins = Result.isSuccess(credentials) ? credentials.success : [];
119 const remote = ForgejoCli.parseForgejoRemote(remoteUrl);
120 const login =
121 (remote && ForgejoCli.matchForgejoLogin(logins, remote)) ||
122 logins.find((entry) => entry.default === "true") ||
123 logins[0];
124 const fj = yield* probeSourceControlProvider({
125 cwd,
126 process,
127 spec: {
128 ...discovery,
129 executable: "fj",
130 versionArgs: ["version"],
131 authArgs: login ? ["--host", login.url, "whoami"] : ["auth", "list"],
132 parseAuth: (result) =>
133 Result.isFailure(credentials)
134 ? providerAuth({
135 status: "unknown",
136 detail: "Could not read fj authentication storage. Authenticate again with fj.",
137 })
138 : login && result.exitCode === 0
139 ? providerAuth({
140 status: "authenticated",
141 account: login.user,
142 host: ForgejoCli.parseForgejoRemote(login.url)?.host,
143 })
144 : providerAuth({
145 status: "unauthenticated",
146 detail:
147 "Authenticate this server with `fj --host <server-url> auth add-token`.",
148 }),
149 },
150 });
151 // A configured fj account owns its requests, including authentication errors.
152 if (fj.status === "available" && (login || Result.isFailure(credentials))) {
153 if (login && fj.auth.status === "authenticated" && cli.getAccount) {
154 const account = yield* cli.getAccount({ cwd, baseUrl: login.url }).pipe(Effect.result);
155 return {
156 ...fj,
157 auth: Result.isSuccess(account)
158 ? providerAuth({
159 status: "authenticated",
160 account: account.success,
161 host: ForgejoCli.parseForgejoRemote(login.url)?.host,
162 })
163 : providerAuth({
164 status: "unknown",
165 detail: account.failure.detail,
166 host: ForgejoCli.parseForgejoRemote(login.url)?.host,
167 }),
168 };
169 }
170 return fj;
171 }
172 const tea = yield* probeSourceControlProvider({ cwd, process, spec: discovery });
173 return tea.status === "available" || fj.status === "missing" ? tea : fj;
174 }),
175 refineUnknownRemote: Effect.fn("ForgejoSourceControlProvider.refineUnknownRemote")(
176 function* (input: {
177 readonly cwd: string;
178 readonly context: SourceControlProvider.SourceControlProviderContext;
179 }) {
180 const remote = ForgejoCli.parseForgejoRemote(input.context.remoteUrl);
181 if (!remote) return { provider: null, settled: true };
182 // fj goes first, so a tea claim after an fj that could not answer is not settled.
183 let settled = true;
184 for (const command of ["fj", "tea"] as const) {
185 const logins = yield* listLogins({
186 cwd: input.cwd,
187 command,
188 remoteUrl: input.context.remoteUrl,
189 }).pipe(Effect.result);
190 if (Result.isFailure(logins)) {
191 // Only a CLI that is not installed holds no login. A missing checkout or an fj that
192 // cannot run fails as `missing-cli` too; the spawn cause tells them apart.
193 settled &&= isMissingExecutable(logins.failure.cause);
194 continue;
195 }
196 settled &&= !hasLoginBelowMount(logins.success, remote);
197 const login = ForgejoCli.matchForgejoLogin(
198 logins.success,
199 remote,
200 input.context.requestedHost,
201 );
202 if (login)
203 return {
204 provider: {
205 kind: SourceControlProviderKind.make("forgejo"),
206 name: discovery.label,
207 baseUrl: login.url,
208 },
209 settled,
210 };
211 }
212 return { provider: null, settled };
213 },
214 ),
215 } satisfies SourceControlManagedCliDiscoverySpec;
216});
217
218/** HTTP paths can include an installation mount; Forgejo's API always names owner/repo. */
219export function repositoryNameFromRemoteUrl(url: string): string | null {
220 const path = SourceControlProvider.repositoryPathFromRemoteUrl(url);
221 return path === null || !/^https?:\/\//iu.test(url.trim())
222 ? path
223 : path.split("/").slice(-2).join("/");
224}
225
226/**
227 * A Forgejo remote's URL can't say which server it belongs to (an SSH alias, an installation
228 * mount), so the identity's browser URL comes from the login that serves it.
229 */
230const refineRepositoryIdentity: NonNullable<
231 SourceControlProvider.SourceControlProvider["Service"]["refineRepositoryIdentity"]
232> = Effect.fn("ForgejoSourceControlProvider.refineRepositoryIdentity")(function* ({
233 identity,
234 resolveContext,
235}) {
236 const remote = ForgejoCli.parseForgejoRemote(identity.locator.remoteUrl);
237 if (
238 !remote ||
239 !identity.rootPath ||
240 (identity.provider !== undefined &&
241 identity.provider !== "unknown" &&
242 identity.provider !== "forgejo")
243 )
244 return identity;
245 const context = yield* resolveContext({
246 cwd: identity.rootPath,
247 context: {
248 provider: { kind: SourceControlProviderKind.make("unknown"), name: "Unknown", baseUrl: "" },
249 remoteName: identity.locator.remoteName,
250 remoteUrl: identity.locator.remoteUrl,
251 },
252 });
253 if (context?.provider.kind !== "forgejo") return identity;
254 const baseUrl = context.provider.baseUrl.replace(/\/+$/, "");
255 const basePath = new URL(baseUrl).pathname.replace(/^\/+|\/+$/g, "");
256 const path =
257 !remote.ssh && basePath && remote.path.startsWith(`${basePath}/`)
258 ? remote.path.slice(basePath.length + 1)
259 : remote.path;
260 return {
261 ...identity,
262 provider: SourceControlProviderKind.make("forgejo"),
263 webUrl: `${baseUrl}/${path}`,
264 };
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 listChangeRequests: (input) =>
340 Effect.gen(function* () {
341 const repo = yield* cli.resolveRepository(input);
342 const source = SourceControlProvider.sourceControlRefFromInput(input);
343 const branch = SourceControlProvider.sourceBranch(input);
344 const results: ReturnType<typeof toForgejoChangeRequest>[] = [];
345 const limit = input.limit ?? 20;
346 for (let page = 1; results.length < limit; page++) {
347 const items = yield* request(
348 {
349 ...input,
350 path: `${repositoryPath(repo.repository)}/pulls?state=${input.state === "merged" ? "closed" : input.state}&head=${encodeURIComponent(branch)}&sort=recentupdate&limit=50&page=${page}`,
351 },
352 Schema.Array(ForgejoPullRequestSchema),
353 );
354 for (const item of items) {
355 if (
356 item.head.ref !== branch ||
357 (source?.repository && item.head.repo?.full_name !== source.repository) ||
358 (source?.owner && item.head.repo?.owner.login !== source.owner)
359 )
360 continue;
361 const normalized = toForgejoChangeRequest(item);
362 if (input.state === "all" || normalized.state === input.state) results.push(normalized);
363 }
364 if (items.length === 0) break;
365 }
366 return results.slice(0, limit);
367 }).pipe(mapError("listChangeRequests", input.cwd)),
368 getChangeRequest: (input) =>
369 getPull(input).pipe(
370 Effect.map(toForgejoChangeRequest),
371 mapError("getChangeRequest", input.cwd),
372 ),
373 createChangeRequest: (input) =>
374 Effect.gen(function* () {
375 const repo = yield* cli.resolveRepository(input);
376 const source = SourceControlProvider.sourceControlRefFromInput(input);
377 const owner = source?.owner ?? source?.repository?.split("/")[0];
378 const head = SourceControlProvider.sourceBranch(input);
379 yield* cli.api({
380 ...input,
381 path: `${repositoryPath(input.target?.repository ?? repo.repository)}/pulls`,
382 method: "POST",
383 body: {
384 base: input.target?.refName ?? input.baseRefName,
385 head: owner ? `${owner}:${head}` : head,
386 title: input.title,
387 body: yield* fs.readFileString(input.bodyFile),
388 },
389 });
390 }).pipe(mapError("createChangeRequest", input.cwd)),
391 getRepositoryCloneUrls: (input) =>
392 Effect.gen(function* () {
393 const repo = yield* cli.resolveRepository(input);
394 return cloneUrls(
395 yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema),
396 );
397 }).pipe(mapError("getRepositoryCloneUrls", input.cwd)),
398 createRepository: (input) =>
399 Effect.gen(function* () {
400 const repo = yield* cli.resolveRepository(input);
401 const user = yield* request(
402 { ...input, path: "user" },
403 Schema.Struct({ login: Schema.String }),
404 );
405 const [owner, name] = repo.repository.split("/");
406 return cloneUrls(
407 yield* request(
408 {
409 ...input,
410 path:
411 owner === user.login
412 ? "user/repos"
413 : `orgs/${encodeURIComponent(owner ?? "")}/repos`,
414 method: "POST",
415 body: { name, private: input.visibility === "private", auto_init: false },
416 },
417 RepositorySchema,
418 ),
419 );
420 }).pipe(mapError("createRepository", input.cwd)),
421 getDefaultBranch: (input) =>
422 Effect.gen(function* () {
423 const repo = yield* cli.resolveRepository(input);
424 return (
425 (yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema))
426 .default_branch ?? null
427 );
428 }).pipe(mapError("getDefaultBranch", input.cwd)),
429 checkoutChangeRequest: (input) =>
430 Effect.gen(function* () {
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 // tea leaves an existing PR branch at its old tip. Keep dirty files safe
485 // while bringing the selected branch to the PR revision we fetched.
486 yield* process.run({
487 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
488 command: "git",
489 cwd: input.cwd,
490 args: ["reset", "--keep", pull.head.sha],
491 });
492 }
493 }).pipe(mapError("checkoutChangeRequest", input.cwd)),
494 });
495});