Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ForgejoSourceControlProvider.ts

506 lines19.3 KB

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