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: (input) =>
310 Effect.gen(function* () {
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 }).pipe(mapError("listChangeRequests", input.cwd)),
338 getChangeRequest: (input) =>
339 getPull(input).pipe(
340 Effect.map(toForgejoChangeRequest),
341 mapError("getChangeRequest", input.cwd),
342 ),
343 createChangeRequest: (input) =>
344 Effect.gen(function* () {
345 const repo = yield* cli.resolveRepository(input);
346 const source = SourceControlProvider.sourceControlRefFromInput(input);
347 const owner = source?.owner ?? source?.repository?.split("/")[0];
348 const head = SourceControlProvider.sourceBranch(input);
349 yield* cli.api({
350 ...input,
351 path: `${repositoryPath(input.target?.repository ?? repo.repository)}/pulls`,
352 method: "POST",
353 body: {
354 base: input.target?.refName ?? input.baseRefName,
355 head: owner ? `${owner}:${head}` : head,
356 title: input.title,
357 body: yield* fs.readFileString(input.bodyFile),
358 },
359 });
360 }).pipe(mapError("createChangeRequest", input.cwd)),
361 getRepositoryCloneUrls: (input) =>
362 Effect.gen(function* () {
363 const repo = yield* cli.resolveRepository(input);
364 return cloneUrls(
365 yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema),
366 );
367 }).pipe(mapError("getRepositoryCloneUrls", input.cwd)),
368 createRepository: (input) =>
369 Effect.gen(function* () {
370 const repo = yield* cli.resolveRepository(input);
371 const user = yield* request(
372 { ...input, path: "user" },
373 Schema.Struct({ login: Schema.String }),
374 );
375 const [owner, name] = repo.repository.split("/");
376 return cloneUrls(
377 yield* request(
378 {
379 ...input,
380 path:
381 owner === user.login
382 ? "user/repos"
383 : `orgs/${encodeURIComponent(owner ?? "")}/repos`,
384 method: "POST",
385 body: { name, private: input.visibility === "private", auto_init: false },
386 },
387 RepositorySchema,
388 ),
389 );
390 }).pipe(mapError("createRepository", input.cwd)),
391 getDefaultBranch: (input) =>
392 Effect.gen(function* () {
393 const repo = yield* cli.resolveRepository(input);
394 return (
395 (yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema))
396 .default_branch ?? null
397 );
398 }).pipe(mapError("getDefaultBranch", input.cwd)),
399 checkoutChangeRequest: (input) =>
400 Effect.gen(function* () {
401 const repo = yield* cli.resolveRepository(input);
402 const pull = yield* getPull(input);
403 if (repo.command === "fj") {
404 // fj checkout cannot target a repository outside the local remotes.
405 const urls = yield* request(
406 { ...input, path: repositoryPath(repo.repository) },
407 RepositorySchema,
408 );
409 const remote = input.context?.remoteUrl;
410 const useSsh = remote && ForgejoCli.parseForgejoRemote(remote)?.ssh;
411 yield* process.run({
412 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
413 command: "git",
414 cwd: input.cwd,
415 args: [
416 "fetch",
417 "--",
418 useSsh ? urls.ssh_url : urls.clone_url,
419 `refs/pull/${pull.number}/head`,
420 ],
421 });
422 const branch = `pulls/${pull.number}`;
423 const existing = yield* process.run({
424 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
425 command: "git",
426 cwd: input.cwd,
427 args: ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`],
428 allowNonZeroExit: true,
429 });
430 yield* process.run({
431 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
432 command: "git",
433 cwd: input.cwd,
434 args:
435 existing.exitCode === 0
436 ? ["checkout", branch]
437 : ["checkout", "-b", branch, "FETCH_HEAD"],
438 });
439 } else
440 yield* cli.execute({
441 cwd: input.cwd,
442 args: [
443 "pulls",
444 "checkout",
445 "--login",
446 repo.login,
447 "--repo",
448 repo.repository,
449 "--branch",
450 String(pull.number),
451 ],
452 });
453 if (input.force) {
454 // The sha comes from the server and git would read anything but a commit as an option.
455 if (!/^[0-9a-f]{7,64}$/i.test(pull.head.sha))
456 return yield* new ForgejoCli.ForgejoCliError({
457 command: repo.command ?? "tea",
458 cwd: input.cwd,
459 detail: "Forgejo reported a pull request head that is not a commit.",
460 reason: "invalid-response",
461 });
462 // tea leaves an existing PR branch at its old tip. Keep dirty files safe
463 // while bringing the selected branch to the PR revision we fetched.
464 yield* process.run({
465 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
466 command: "git",
467 cwd: input.cwd,
468 args: ["reset", "--keep", pull.head.sha],
469 });
470 }
471 }).pipe(mapError("checkoutChangeRequest", input.cwd)),
472 });
473});