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