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/**
197 * A Forgejo remote's URL can't say which server it belongs to (an SSH alias, an installation
198 * mount), so the identity's browser URL comes from the login that serves it.
199 */
200const refineRepositoryIdentity: NonNullable<
201 SourceControlProvider.SourceControlProvider["Service"]["refineRepositoryIdentity"]
202> = Effect.fn("ForgejoSourceControlProvider.refineRepositoryIdentity")(function* ({
203 identity,
204 resolveContext,
205}) {
206 const remote = ForgejoCli.parseForgejoRemote(identity.locator.remoteUrl);
207 if (
208 !remote ||
209 !identity.rootPath ||
210 (identity.provider !== undefined &&
211 identity.provider !== "unknown" &&
212 identity.provider !== "forgejo")
213 )
214 return identity;
215 const context = yield* resolveContext({
216 cwd: identity.rootPath,
217 context: {
218 provider: { kind: SourceControlProviderKind.make("unknown"), name: "Unknown", baseUrl: "" },
219 remoteName: identity.locator.remoteName,
220 remoteUrl: identity.locator.remoteUrl,
221 },
222 });
223 if (context?.provider.kind !== "forgejo") return identity;
224 const baseUrl = context.provider.baseUrl.replace(/\/+$/, "");
225 const basePath = new URL(baseUrl).pathname.replace(/^\/+|\/+$/g, "");
226 const path =
227 !remote.ssh && basePath && remote.path.startsWith(`${basePath}/`)
228 ? remote.path.slice(basePath.length + 1)
229 : remote.path;
230 return {
231 ...identity,
232 provider: SourceControlProviderKind.make("forgejo"),
233 webUrl: `${baseUrl}/${path}`,
234 };
235});
236
237const RepositorySchema = Schema.Struct({
238 full_name: Schema.String,
239 clone_url: Schema.String,
240 ssh_url: Schema.String,
241 default_branch: Schema.optional(Schema.NullOr(Schema.String)),
242});
243const cloneUrls = (raw: typeof RepositorySchema.Type) => ({
244 nameWithOwner: raw.full_name,
245 url: raw.clone_url,
246 sshUrl: raw.ssh_url,
247});
248const repositoryPath = (repository: string) =>
249 `repos/${repository.split("/").map(encodeURIComponent).join("/")}`;
250
251export const make = Effect.gen(function* () {
252 const cli = yield* ForgejoCli.ForgejoCli;
253 const fs = yield* FileSystem.FileSystem;
254 const { process } = yield* SourceControlHost.SourceControlHost;
255 const request = <S extends Schema.Codec<unknown, unknown, never, never>>(
256 input: ForgejoCli.ForgejoApiInput,
257 schema: S,
258 ) =>
259 cli.api(input).pipe(
260 Effect.flatMap((result) =>
261 Schema.decodeEffect(Schema.fromJsonString(schema))(result.stdout).pipe(
262 Effect.mapError(
263 (cause) =>
264 new ForgejoCli.ForgejoCliError({
265 command: "tea",
266 cwd: input.cwd,
267 detail: "Forgejo API returned an invalid response.",
268 reason: "invalid-response",
269 cause,
270 }),
271 ),
272 ),
273 ),
274 );
275 const mapError = (operation: string, cwd: string) =>
276 Effect.mapError(
277 (cause: unknown) =>
278 new SourceControlProviderError({
279 provider: SourceControlProviderKind.make("forgejo"),
280 operation,
281 cwd,
282 ...(isForgejoCliError(cause) ? { command: cause.command } : {}),
283 detail: isForgejoCliError(cause) ? cause.detail : "Forgejo operation failed.",
284 cause,
285 }),
286 );
287 const getPull = Effect.fn("ForgejoSourceControlProvider.getPull")(function* (
288 input: Parameters<
289 SourceControlProvider.SourceControlProvider["Service"]["getChangeRequest"]
290 >[0],
291 ) {
292 const repo = yield* cli.resolveRepository(input);
293 const number = /(?:^#?|\/pulls\/)(\d+)(?:\/[^?#]*)?(?:[?#].*)?$/.exec(input.reference)?.[1];
294 if (!number)
295 return yield* new ForgejoCli.ForgejoCliError({
296 command: "tea",
297 cwd: input.cwd,
298 detail: "Specify a pull request number or Forgejo pull request URL.",
299 });
300 return yield* request(
301 { ...input, path: `${repositoryPath(repo.repository)}/pulls/${number}` },
302 ForgejoPullRequestSchema,
303 );
304 });
305 return SourceControlProvider.SourceControlProvider.of({
306 kind: SourceControlProviderKind.make("forgejo"),
307 repositoryNameFromRemoteUrl,
308 refineRepositoryIdentity,
309 listChangeRequests: Effect.fn("ForgejoSourceControlProvider.listChangeRequests")(
310 function* (input) {
311 const repo = yield* cli.resolveRepository(input);
312 const source = SourceControlProvider.sourceControlRefFromInput(input);
313 const branch = SourceControlProvider.sourceBranch(input);
314 const results: ReturnType<typeof toForgejoChangeRequest>[] = [];
315 const limit = input.limit ?? 20;
316 for (let page = 1; results.length < limit; page++) {
317 const items = yield* request(
318 {
319 ...input,
320 path: `${repositoryPath(repo.repository)}/pulls?state=${input.state === "merged" ? "closed" : input.state}&head=${encodeURIComponent(branch)}&sort=recentupdate&limit=50&page=${page}`,
321 },
322 Schema.Array(ForgejoPullRequestSchema),
323 );
324 for (const item of items) {
325 if (
326 item.head.ref !== branch ||
327 (source?.repository && item.head.repo?.full_name !== source.repository) ||
328 (source?.owner && item.head.repo?.owner.login !== source.owner)
329 )
330 continue;
331 const normalized = toForgejoChangeRequest(item);
332 if (input.state === "all" || normalized.state === input.state) results.push(normalized);
333 }
334 if (items.length === 0) break;
335 }
336 return results.slice(0, limit);
337 },
338 (effect, input) => effect.pipe(mapError("listChangeRequests", input.cwd)),
339 ),
340 getChangeRequest: (input) =>
341 getPull(input).pipe(
342 Effect.map(toForgejoChangeRequest),
343 mapError("getChangeRequest", input.cwd),
344 ),
345 createChangeRequest: Effect.fn("ForgejoSourceControlProvider.createChangeRequest")(
346 function* (input) {
347 const repo = yield* cli.resolveRepository(input);
348 const source = SourceControlProvider.sourceControlRefFromInput(input);
349 const owner = source?.owner ?? source?.repository?.split("/")[0];
350 const head = SourceControlProvider.sourceBranch(input);
351 yield* cli.api({
352 ...input,
353 path: `${repositoryPath(input.target?.repository ?? repo.repository)}/pulls`,
354 method: "POST",
355 body: {
356 base: input.target?.refName ?? input.baseRefName,
357 head: owner ? `${owner}:${head}` : head,
358 title: input.title,
359 body: yield* fs.readFileString(input.bodyFile),
360 },
361 });
362 },
363 (effect, input) => effect.pipe(mapError("createChangeRequest", input.cwd)),
364 ),
365 getRepositoryCloneUrls: Effect.fn("ForgejoSourceControlProvider.getRepositoryCloneUrls")(
366 function* (input) {
367 const repo = yield* cli.resolveRepository(input);
368 return cloneUrls(
369 yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema),
370 );
371 },
372 (effect, input) => effect.pipe(mapError("getRepositoryCloneUrls", input.cwd)),
373 ),
374 createRepository: Effect.fn("ForgejoSourceControlProvider.createRepository")(
375 function* (input) {
376 const repo = yield* cli.resolveRepository(input);
377 const user = yield* request(
378 { ...input, path: "user" },
379 Schema.Struct({ login: Schema.String }),
380 );
381 const [owner, name] = repo.repository.split("/");
382 return cloneUrls(
383 yield* request(
384 {
385 ...input,
386 path:
387 owner === user.login
388 ? "user/repos"
389 : `orgs/${encodeURIComponent(owner ?? "")}/repos`,
390 method: "POST",
391 body: { name, private: input.visibility === "private", auto_init: false },
392 },
393 RepositorySchema,
394 ),
395 );
396 },
397 (effect, input) => effect.pipe(mapError("createRepository", input.cwd)),
398 ),
399 getDefaultBranch: Effect.fn("ForgejoSourceControlProvider.getDefaultBranch")(
400 function* (input) {
401 const repo = yield* cli.resolveRepository(input);
402 return (
403 (yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema))
404 .default_branch ?? null
405 );
406 },
407 (effect, input) => effect.pipe(mapError("getDefaultBranch", input.cwd)),
408 ),
409 checkoutChangeRequest: Effect.fn("ForgejoSourceControlProvider.checkoutChangeRequest")(
410 function* (input) {
411 const repo = yield* cli.resolveRepository(input);
412 const pull = yield* getPull(input);
413 if (repo.command === "fj") {
414 // fj checkout cannot target a repository outside the local remotes.
415 const urls = yield* request(
416 { ...input, path: repositoryPath(repo.repository) },
417 RepositorySchema,
418 );
419 const remote = input.context?.remoteUrl;
420 const useSsh = remote && ForgejoCli.parseForgejoRemote(remote)?.ssh;
421 yield* process.run({
422 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
423 command: "git",
424 cwd: input.cwd,
425 args: [
426 "fetch",
427 "--",
428 useSsh ? urls.ssh_url : urls.clone_url,
429 `refs/pull/${pull.number}/head`,
430 ],
431 });
432 const branch = `pulls/${pull.number}`;
433 const existing = yield* process.run({
434 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
435 command: "git",
436 cwd: input.cwd,
437 args: ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`],
438 allowNonZeroExit: true,
439 });
440 yield* process.run({
441 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
442 command: "git",
443 cwd: input.cwd,
444 args:
445 existing.exitCode === 0
446 ? ["checkout", branch]
447 : ["checkout", "-b", branch, "FETCH_HEAD"],
448 });
449 } else
450 yield* cli.execute({
451 cwd: input.cwd,
452 args: [
453 "pulls",
454 "checkout",
455 "--login",
456 repo.login,
457 "--repo",
458 repo.repository,
459 "--branch",
460 String(pull.number),
461 ],
462 });
463 if (input.force) {
464 // The sha comes from the server and git would read anything but a commit as an option.
465 if (!/^[0-9a-f]{7,64}$/i.test(pull.head.sha))
466 return yield* new ForgejoCli.ForgejoCliError({
467 command: repo.command ?? "tea",
468 cwd: input.cwd,
469 detail: "Forgejo reported a pull request head that is not a commit.",
470 reason: "invalid-response",
471 });
472 // tea leaves an existing PR branch at its old tip. Keep dirty files safe
473 // while bringing the selected branch to the PR revision we fetched.
474 yield* process.run({
475 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
476 command: "git",
477 cwd: input.cwd,
478 args: ["reset", "--keep", pull.head.sha],
479 });
480 }
481 },
482 (effect, input) => effect.pipe(mapError("checkoutChangeRequest", input.cwd)),
483 ),
484 });
485});