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

ForgejoSourceControlProvider.ts

388 lines15.1 KB

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 VcsProcess from "../vcs/VcsProcess.ts";
7import * as ForgejoCli from "./ForgejoCli.ts";
8import * as SourceControlProvider from "./SourceControlProvider.ts";
9import {
10 providerAuth,
11 probeSourceControlProvider,
12 type SourceControlCliDiscoverySpec,
13 type SourceControlManagedCliDiscoverySpec,
14} from "./SourceControlProviderDiscovery.ts";
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* VcsProcess.VcsProcess;
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 // Only the `gh` spec expands into several rows; every other spec answers with exactly one.
89 const [fj] = yield* probeSourceControlProvider({
90 cwd,
91 process,
92 spec: {
93 ...discovery,
94 executable: "fj",
95 versionArgs: ["version"],
96 authArgs: login ? ["--host", login.url, "whoami"] : ["auth", "list"],
97 parseAuth: (result) =>
98 Result.isFailure(credentials)
99 ? providerAuth({
100 status: "unknown",
101 detail: "Could not read fj authentication storage. Authenticate again with fj.",
102 })
103 : login && result.exitCode === 0
104 ? providerAuth({
105 status: "authenticated",
106 account: login.user,
107 host: ForgejoCli.parseForgejoRemote(login.url)?.host,
108 })
109 : providerAuth({
110 status: "unauthenticated",
111 detail:
112 "Authenticate this server with `fj --host <server-url> auth add-token`.",
113 }),
114 },
115 });
116 // A configured fj account owns its requests, including authentication errors.
117 if (fj!.status === "available" && (login || Result.isFailure(credentials))) {
118 if (login && fj!.auth.status === "authenticated" && cli.getAccount) {
119 const account = yield* cli.getAccount({ cwd, baseUrl: login.url }).pipe(Effect.result);
120 return {
121 ...fj!,
122 auth: Result.isSuccess(account)
123 ? providerAuth({
124 status: "authenticated",
125 account: account.success,
126 host: ForgejoCli.parseForgejoRemote(login.url)?.host,
127 })
128 : providerAuth({
129 status: "unknown",
130 detail: account.failure.detail,
131 host: ForgejoCli.parseForgejoRemote(login.url)?.host,
132 }),
133 };
134 }
135 return fj!;
136 }
137 const [tea] = yield* probeSourceControlProvider({ cwd, process, spec: discovery });
138 return tea!.status === "available" || fj!.status === "missing" ? tea! : fj!;
139 }),
140 refineUnknownRemote: Effect.fn("ForgejoSourceControlProvider.refineUnknownRemote")(
141 function* (input: {
142 readonly cwd: string;
143 readonly context: SourceControlProvider.SourceControlProviderContext;
144 }) {
145 const remote = ForgejoCli.parseForgejoRemote(input.context.remoteUrl);
146 if (!remote) return null;
147 for (const command of ["fj", "tea"] as const) {
148 const logins = yield* listLogins({
149 cwd: input.cwd,
150 command,
151 remoteUrl: input.context.remoteUrl,
152 }).pipe(Effect.orElseSucceed(() => []));
153 const login = ForgejoCli.matchForgejoLogin(logins, remote, input.context.requestedHost);
154 if (login) return { kind: "forgejo" as const, name: discovery.label, baseUrl: login.url };
155 }
156 return null;
157 },
158 ),
159 } satisfies SourceControlManagedCliDiscoverySpec;
160});
161​
162const RepositorySchema = Schema.Struct({
163 full_name: Schema.String,
164 clone_url: Schema.String,
165 ssh_url: Schema.String,
166 default_branch: Schema.optional(Schema.NullOr(Schema.String)),
167});
168const cloneUrls = (raw: typeof RepositorySchema.Type) => ({
169 nameWithOwner: raw.full_name,
170 url: raw.clone_url,
171 sshUrl: raw.ssh_url,
172});
173const repositoryPath = (repository: string) =>
174 `repos/${repository.split("/").map(encodeURIComponent).join("/")}`;
175​
176export const make = Effect.gen(function* () {
177 const cli = yield* ForgejoCli.ForgejoCli;
178 const fs = yield* FileSystem.FileSystem;
179 const process = yield* VcsProcess.VcsProcess;
180 const request = <S extends Schema.Codec<unknown, unknown, never, never>>(
181 input: ForgejoCli.ForgejoApiInput,
182 schema: S,
183 ) =>
184 cli.api(input).pipe(
185 Effect.flatMap((result) =>
186 Schema.decodeEffect(Schema.fromJsonString(schema))(result.stdout).pipe(
187 Effect.mapError(
188 (cause) =>
189 new ForgejoCli.ForgejoCliError({
190 command: "tea",
191 cwd: input.cwd,
192 detail: "Forgejo API returned an invalid response.",
193 reason: "invalid-response",
194 cause,
195 }),
196 ),
197 ),
198 ),
199 );
200 const mapError = (operation: string, cwd: string) =>
201 Effect.mapError(
202 (cause: unknown) =>
203 new SourceControlProviderError({
204 provider: "forgejo",
205 operation,
206 cwd,
207 ...(isForgejoCliError(cause) ? { command: cause.command } : {}),
208 detail: isForgejoCliError(cause) ? cause.detail : "Forgejo operation failed.",
209 cause,
210 }),
211 );
212 const getPull = Effect.fn("ForgejoSourceControlProvider.getPull")(function* (
213 input: Parameters<
214 SourceControlProvider.SourceControlProvider["Service"]["getChangeRequest"]
215 >[0],
216 ) {
217 const repo = yield* cli.resolveRepository(input);
218 const number = /(?:^#?|\/pulls\/)(\d+)(?:\/[^?#]*)?(?:[?#].*)?$/.exec(input.reference)?.[1];
219 if (!number)
220 return yield* new ForgejoCli.ForgejoCliError({
221 command: "tea",
222 cwd: input.cwd,
223 detail: "Specify a pull request number or Forgejo pull request URL.",
224 });
225 return yield* request(
226 { ...input, path: `${repositoryPath(repo.repository)}/pulls/${number}` },
227 ForgejoPullRequestSchema,
228 );
229 });
230 return SourceControlProvider.SourceControlProvider.of({
231 kind: "forgejo",
232 listChangeRequests: (input) =>
233 Effect.gen(function* () {
234 const repo = yield* cli.resolveRepository(input);
235 const source = SourceControlProvider.sourceControlRefFromInput(input);
236 const branch = SourceControlProvider.sourceBranch(input);
237 const results: ReturnType<typeof toForgejoChangeRequest>[] = [];
238 const limit = input.limit ?? 20;
239 for (let page = 1; results.length < limit; page++) {
240 const items = yield* request(
241 {
242 ...input,
243 path: `${repositoryPath(repo.repository)}/pulls?state=${input.state === "merged" ? "closed" : input.state}&sort=recentupdate&limit=50&page=${page}`,
244 },
245 Schema.Array(ForgejoPullRequestSchema),
246 );
247 for (const item of items) {
248 if (
249 item.head.ref !== branch ||
250 (source?.repository && item.head.repo?.full_name !== source.repository) ||
251 (source?.owner && item.head.repo?.owner.login !== source.owner)
252 )
253 continue;
254 const normalized = toForgejoChangeRequest(item);
255 if (input.state === "all" || normalized.state === input.state) results.push(normalized);
256 }
257 if (items.length === 0) break;
258 }
259 return results.slice(0, limit);
260 }).pipe(mapError("listChangeRequests", input.cwd)),
261 getChangeRequest: (input) =>
262 getPull(input).pipe(
263 Effect.map(toForgejoChangeRequest),
264 mapError("getChangeRequest", input.cwd),
265 ),
266 createChangeRequest: (input) =>
267 Effect.gen(function* () {
268 const repo = yield* cli.resolveRepository(input);
269 const source = SourceControlProvider.sourceControlRefFromInput(input);
270 const owner = source?.owner ?? source?.repository?.split("/")[0];
271 const head = SourceControlProvider.sourceBranch(input);
272 yield* cli.api({
273 ...input,
274 path: `${repositoryPath(input.target?.repository ?? repo.repository)}/pulls`,
275 method: "POST",
276 body: {
277 base: input.target?.refName ?? input.baseRefName,
278 head: owner ? `${owner}:${head}` : head,
279 title: input.title,
280 body: yield* fs.readFileString(input.bodyFile),
281 },
282 });
283 }).pipe(mapError("createChangeRequest", input.cwd)),
284 getRepositoryCloneUrls: (input) =>
285 Effect.gen(function* () {
286 const repo = yield* cli.resolveRepository(input);
287 return cloneUrls(
288 yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema),
289 );
290 }).pipe(mapError("getRepositoryCloneUrls", input.cwd)),
291 createRepository: (input) =>
292 Effect.gen(function* () {
293 const repo = yield* cli.resolveRepository(input);
294 const user = yield* request(
295 { ...input, path: "user" },
296 Schema.Struct({ login: Schema.String }),
297 );
298 const [owner, name] = repo.repository.split("/");
299 return cloneUrls(
300 yield* request(
301 {
302 ...input,
303 path:
304 owner === user.login
305 ? "user/repos"
306 : `orgs/${encodeURIComponent(owner ?? "")}/repos`,
307 method: "POST",
308 body: { name, private: input.visibility === "private", auto_init: false },
309 },
310 RepositorySchema,
311 ),
312 );
313 }).pipe(mapError("createRepository", input.cwd)),
314 getDefaultBranch: (input) =>
315 Effect.gen(function* () {
316 const repo = yield* cli.resolveRepository(input);
317 return (
318 (yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema))
319 .default_branch ?? null
320 );
321 }).pipe(mapError("getDefaultBranch", input.cwd)),
322 checkoutChangeRequest: (input) =>
323 Effect.gen(function* () {
324 const repo = yield* cli.resolveRepository(input);
325 const pull = yield* getPull(input);
326 if (repo.command === "fj") {
327 // fj checkout cannot target a repository outside the local remotes.
328 const urls = yield* request(
329 { ...input, path: repositoryPath(repo.repository) },
330 RepositorySchema,
331 );
332 const remote = input.context?.remoteUrl;
333 const useSsh = remote && ForgejoCli.parseForgejoRemote(remote)?.ssh;
334 yield* process.run({
335 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
336 command: "git",
337 cwd: input.cwd,
338 args: [
339 "fetch",
340 "--",
341 useSsh ? urls.ssh_url : urls.clone_url,
342 `refs/pull/${pull.number}/head`,
343 ],
344 });
345 const branch = `pulls/${pull.number}`;
346 const existing = yield* process.run({
347 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
348 command: "git",
349 cwd: input.cwd,
350 args: ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`],
351 allowNonZeroExit: true,
352 });
353 yield* process.run({
354 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
355 command: "git",
356 cwd: input.cwd,
357 args:
358 existing.exitCode === 0
359 ? ["checkout", branch]
360 : ["checkout", "-b", branch, "FETCH_HEAD"],
361 });
362 } else
363 yield* cli.execute({
364 cwd: input.cwd,
365 args: [
366 "pulls",
367 "checkout",
368 "--login",
369 repo.login,
370 "--repo",
371 repo.repository,
372 "--branch",
373 String(pull.number),
374 ],
375 });
376 if (input.force) {
377 // tea leaves an existing PR branch at its old tip. Keep dirty files safe
378 // while bringing the selected branch to the PR revision we fetched.
379 yield* process.run({
380 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
381 command: "git",
382 cwd: input.cwd,
383 args: ["reset", "--keep", pull.head.sha],
384 });
385 }
386 }).pipe(mapError("checkoutChangeRequest", input.cwd)),
387 });
388});