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 // A configured fj account owns its requests, including authentication errors.
124 if (fj.status === "available" && (login || Result.isFailure(credentials))) {
125 if (login && fj.auth.status === "authenticated" && cli.getAccount) {
126 const account = yield* cli.getAccount({ cwd, baseUrl: login.url }).pipe(Effect.result);
127 return {
128 ...fj,
129 auth: Result.isSuccess(account)
130 ? providerAuth({
131 status: "authenticated",
132 account: account.success,
133 host: ForgejoCli.parseForgejoRemote(login.url)?.host,
134 })
135 : providerAuth({
136 status: "unknown",
137 detail: account.failure.detail,
138 host: ForgejoCli.parseForgejoRemote(login.url)?.host,
139 }),
140 };
141 }
142 return fj;
143 }
144 const tea = yield* probeSourceControlProvider({ cwd, process, spec: discovery });
145 return tea.status === "available" || fj.status === "missing" ? tea : fj;
146 }),
147 refineUnknownRemote: Effect.fn("ForgejoSourceControlProvider.refineUnknownRemote")(
148 function* (input: {
149 readonly cwd: string;
150 readonly context: SourceControlProvider.SourceControlProviderContext;
151 }) {
152 const remote = ForgejoCli.parseForgejoRemote(input.context.remoteUrl);
153 if (!remote) return null;
154 // Both CLIs claim Forgejo, so one failing does not stop the other from claiming the host.
155 let failure: ForgejoCli.ForgejoCliError | undefined;
156 for (const command of ["fj", "tea"] as const) {
157 const logins = yield* listLogins({
158 cwd: input.cwd,
159 command,
160 remoteUrl: input.context.remoteUrl,
161 }).pipe(
162 // A CLI that is not installed holds no login.
163 Effect.catchIf(
164 (error) => isMissingExecutable(error.cause),
165 () => Effect.succeed([]),
166 ),
167 Effect.result,
168 );
169 if (Result.isFailure(logins)) {
170 failure ??= logins.failure;
171 continue;
172 }
173 const login = ForgejoCli.matchForgejoLogin(
174 logins.success,
175 remote,
176 input.context.requestedHost,
177 );
178 if (login)
179 return {
180 kind: SourceControlProviderKind.make("forgejo"),
181 name: discovery.label,
182 baseUrl: login.url,
183 };
184 }
185 if (failure) return yield* failure;
186 return null;
187 },
188 ),
189 } satisfies SourceControlManagedCliDiscoverySpec;
190});
191
192/** HTTP paths can include an installation mount; Forgejo's API always names owner/repo. */
193export function repositoryNameFromRemoteUrl(url: string): string | null {
194 const path = SourceControlProvider.repositoryPathFromRemoteUrl(url);
195 return path === null || !/^https?:\/\//iu.test(url.trim())
196 ? path
197 : path.split("/").slice(-2).join("/");
198}
199
200/**
201 * A Forgejo remote's URL can't say which server it belongs to (an SSH alias, an installation
202 * mount), so the identity's browser URL comes from the login that serves it.
203 */
204const refineRepositoryIdentity: NonNullable<
205 SourceControlProvider.SourceControlProvider["Service"]["refineRepositoryIdentity"]
206> = Effect.fn("ForgejoSourceControlProvider.refineRepositoryIdentity")(function* ({
207 identity,
208 resolveContext,
209}) {
210 const remote = ForgejoCli.parseForgejoRemote(identity.locator.remoteUrl);
211 if (
212 !remote ||
213 !identity.rootPath ||
214 (identity.provider !== undefined &&
215 identity.provider !== "unknown" &&
216 identity.provider !== "forgejo")
217 )
218 return identity;
219 const context = yield* resolveContext({
220 cwd: identity.rootPath,
221 context: {
222 provider: { kind: SourceControlProviderKind.make("unknown"), name: "Unknown", baseUrl: "" },
223 remoteName: identity.locator.remoteName,
224 remoteUrl: identity.locator.remoteUrl,
225 },
226 });
227 if (context?.provider.kind !== "forgejo") return identity;
228 const baseUrl = context.provider.baseUrl.replace(/\/+$/, "");
229 const basePath = new URL(baseUrl).pathname.replace(/^\/+|\/+$/g, "");
230 const path =
231 !remote.ssh && basePath && remote.path.startsWith(`${basePath}/`)
232 ? remote.path.slice(basePath.length + 1)
233 : remote.path;
234 return {
235 ...identity,
236 provider: SourceControlProviderKind.make("forgejo"),
237 webUrl: `${baseUrl}/${path}`,
238 };
239});
240
241const RepositorySchema = Schema.Struct({
242 full_name: Schema.String,
243 clone_url: Schema.String,
244 ssh_url: Schema.String,
245 default_branch: Schema.optional(Schema.NullOr(Schema.String)),
246});
247const cloneUrls = (raw: typeof RepositorySchema.Type) => ({
248 nameWithOwner: raw.full_name,
249 url: raw.clone_url,
250 sshUrl: raw.ssh_url,
251});
252const repositoryPath = (repository: string) =>
253 `repos/${repository.split("/").map(encodeURIComponent).join("/")}`;
254
255export const make = Effect.gen(function* () {
256 const cli = yield* ForgejoCli.ForgejoCli;
257 const fs = yield* FileSystem.FileSystem;
258 const { process } = yield* SourceControlHost.SourceControlHost;
259 const request = <S extends Schema.Codec<unknown, unknown, never, never>>(
260 input: ForgejoCli.ForgejoApiInput,
261 schema: S,
262 ) =>
263 cli.api(input).pipe(
264 Effect.flatMap((result) =>
265 Schema.decodeEffect(Schema.fromJsonString(schema))(result.stdout).pipe(
266 Effect.mapError(
267 (cause) =>
268 new ForgejoCli.ForgejoCliError({
269 command: "tea",
270 cwd: input.cwd,
271 detail: "Forgejo API returned an invalid response.",
272 reason: "invalid-response",
273 cause,
274 }),
275 ),
276 ),
277 ),
278 );
279 const mapError = (operation: string, cwd: string) =>
280 Effect.mapError(
281 (cause: unknown) =>
282 new SourceControlProviderError({
283 provider: SourceControlProviderKind.make("forgejo"),
284 operation,
285 cwd,
286 ...(isForgejoCliError(cause) ? { command: cause.command } : {}),
287 detail: isForgejoCliError(cause) ? cause.detail : "Forgejo operation failed.",
288 cause,
289 }),
290 );
291 const getPull = Effect.fn("ForgejoSourceControlProvider.getPull")(function* (
292 input: Parameters<
293 SourceControlProvider.SourceControlProvider["Service"]["getChangeRequest"]
294 >[0],
295 ) {
296 const repo = yield* cli.resolveRepository(input);
297 const number = /(?:^#?|\/pulls\/)(\d+)(?:\/[^?#]*)?(?:[?#].*)?$/.exec(input.reference)?.[1];
298 if (!number)
299 return yield* new ForgejoCli.ForgejoCliError({
300 command: "tea",
301 cwd: input.cwd,
302 detail: "Specify a pull request number or Forgejo pull request URL.",
303 });
304 return yield* request(
305 { ...input, path: `${repositoryPath(repo.repository)}/pulls/${number}` },
306 ForgejoPullRequestSchema,
307 );
308 });
309 return SourceControlProvider.SourceControlProvider.of({
310 kind: SourceControlProviderKind.make("forgejo"),
311 repositoryNameFromRemoteUrl,
312 refineRepositoryIdentity,
313 listChangeRequests: (input) =>
314 Effect.gen(function* () {
315 const repo = yield* cli.resolveRepository(input);
316 const source = SourceControlProvider.sourceControlRefFromInput(input);
317 const branch = SourceControlProvider.sourceBranch(input);
318 const results: ReturnType<typeof toForgejoChangeRequest>[] = [];
319 const limit = input.limit ?? 20;
320 for (let page = 1; results.length < limit; page++) {
321 const items = yield* request(
322 {
323 ...input,
324 path: `${repositoryPath(repo.repository)}/pulls?state=${input.state === "merged" ? "closed" : input.state}&head=${encodeURIComponent(branch)}&sort=recentupdate&limit=50&page=${page}`,
325 },
326 Schema.Array(ForgejoPullRequestSchema),
327 );
328 for (const item of items) {
329 if (
330 item.head.ref !== branch ||
331 (source?.repository && item.head.repo?.full_name !== source.repository) ||
332 (source?.owner && item.head.repo?.owner.login !== source.owner)
333 )
334 continue;
335 const normalized = toForgejoChangeRequest(item);
336 if (input.state === "all" || normalized.state === input.state) results.push(normalized);
337 }
338 if (items.length === 0) break;
339 }
340 return results.slice(0, limit);
341 }).pipe(mapError("listChangeRequests", input.cwd)),
342 getChangeRequest: (input) =>
343 getPull(input).pipe(
344 Effect.map(toForgejoChangeRequest),
345 mapError("getChangeRequest", input.cwd),
346 ),
347 createChangeRequest: (input) =>
348 Effect.gen(function* () {
349 const repo = yield* cli.resolveRepository(input);
350 const source = SourceControlProvider.sourceControlRefFromInput(input);
351 const owner = source?.owner ?? source?.repository?.split("/")[0];
352 const head = SourceControlProvider.sourceBranch(input);
353 yield* cli.api({
354 ...input,
355 path: `${repositoryPath(input.target?.repository ?? repo.repository)}/pulls`,
356 method: "POST",
357 body: {
358 base: input.target?.refName ?? input.baseRefName,
359 head: owner ? `${owner}:${head}` : head,
360 title: input.title,
361 body: yield* fs.readFileString(input.bodyFile),
362 },
363 });
364 }).pipe(mapError("createChangeRequest", input.cwd)),
365 getRepositoryCloneUrls: (input) =>
366 Effect.gen(function* () {
367 const repo = yield* cli.resolveRepository(input);
368 return cloneUrls(
369 yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema),
370 );
371 }).pipe(mapError("getRepositoryCloneUrls", input.cwd)),
372 createRepository: (input) =>
373 Effect.gen(function* () {
374 const repo = yield* cli.resolveRepository(input);
375 const user = yield* request(
376 { ...input, path: "user" },
377 Schema.Struct({ login: Schema.String }),
378 );
379 const [owner, name] = repo.repository.split("/");
380 return cloneUrls(
381 yield* request(
382 {
383 ...input,
384 path:
385 owner === user.login
386 ? "user/repos"
387 : `orgs/${encodeURIComponent(owner ?? "")}/repos`,
388 method: "POST",
389 body: { name, private: input.visibility === "private", auto_init: false },
390 },
391 RepositorySchema,
392 ),
393 );
394 }).pipe(mapError("createRepository", input.cwd)),
395 getDefaultBranch: (input) =>
396 Effect.gen(function* () {
397 const repo = yield* cli.resolveRepository(input);
398 return (
399 (yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema))
400 .default_branch ?? null
401 );
402 }).pipe(mapError("getDefaultBranch", input.cwd)),
403 checkoutChangeRequest: (input) =>
404 Effect.gen(function* () {
405 const repo = yield* cli.resolveRepository(input);
406 const pull = yield* getPull(input);
407 if (repo.command === "fj") {
408 // fj checkout cannot target a repository outside the local remotes.
409 const urls = yield* request(
410 { ...input, path: repositoryPath(repo.repository) },
411 RepositorySchema,
412 );
413 const remote = input.context?.remoteUrl;
414 const useSsh = remote && ForgejoCli.parseForgejoRemote(remote)?.ssh;
415 yield* process.run({
416 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
417 command: "git",
418 cwd: input.cwd,
419 args: [
420 "fetch",
421 "--",
422 useSsh ? urls.ssh_url : urls.clone_url,
423 `refs/pull/${pull.number}/head`,
424 ],
425 });
426 const branch = `pulls/${pull.number}`;
427 const existing = yield* process.run({
428 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
429 command: "git",
430 cwd: input.cwd,
431 args: ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`],
432 allowNonZeroExit: true,
433 });
434 yield* process.run({
435 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
436 command: "git",
437 cwd: input.cwd,
438 args:
439 existing.exitCode === 0
440 ? ["checkout", branch]
441 : ["checkout", "-b", branch, "FETCH_HEAD"],
442 });
443 } else
444 yield* cli.execute({
445 cwd: input.cwd,
446 args: [
447 "pulls",
448 "checkout",
449 "--login",
450 repo.login,
451 "--repo",
452 repo.repository,
453 "--branch",
454 String(pull.number),
455 ],
456 });
457 if (input.force) {
458 // tea leaves an existing PR branch at its old tip. Keep dirty files safe
459 // while bringing the selected branch to the PR revision we fetched.
460 yield* process.run({
461 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
462 command: "git",
463 cwd: input.cwd,
464 args: ["reset", "--keep", pull.head.sha],
465 });
466 }
467 }).pipe(mapError("checkoutChangeRequest", input.cwd)),
468 });
469});