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 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 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
161const RepositorySchema = Schema.Struct({
162 full_name: Schema.String,
163 clone_url: Schema.String,
164 ssh_url: Schema.String,
165 default_branch: Schema.optional(Schema.NullOr(Schema.String)),
166});
167const cloneUrls = (raw: typeof RepositorySchema.Type) => ({
168 nameWithOwner: raw.full_name,
169 url: raw.clone_url,
170 sshUrl: raw.ssh_url,
171});
172const repositoryPath = (repository: string) =>
173 `repos/${repository.split("/").map(encodeURIComponent).join("/")}`;
174
175export const make = Effect.gen(function* () {
176 const cli = yield* ForgejoCli.ForgejoCli;
177 const fs = yield* FileSystem.FileSystem;
178 const process = yield* VcsProcess.VcsProcess;
179 const request = <S extends Schema.Codec<unknown, unknown, never, never>>(
180 input: ForgejoCli.ForgejoApiInput,
181 schema: S,
182 ) =>
183 cli.api(input).pipe(
184 Effect.flatMap((result) =>
185 Schema.decodeEffect(Schema.fromJsonString(schema))(result.stdout).pipe(
186 Effect.mapError(
187 (cause) =>
188 new ForgejoCli.ForgejoCliError({
189 command: "tea",
190 cwd: input.cwd,
191 detail: "Forgejo API returned an invalid response.",
192 reason: "invalid-response",
193 cause,
194 }),
195 ),
196 ),
197 ),
198 );
199 const mapError = (operation: string, cwd: string) =>
200 Effect.mapError(
201 (cause: unknown) =>
202 new SourceControlProviderError({
203 provider: "forgejo",
204 operation,
205 cwd,
206 ...(isForgejoCliError(cause) ? { command: cause.command } : {}),
207 detail: isForgejoCliError(cause) ? cause.detail : "Forgejo operation failed.",
208 cause,
209 }),
210 );
211 const getPull = Effect.fn("ForgejoSourceControlProvider.getPull")(function* (
212 input: Parameters<
213 SourceControlProvider.SourceControlProvider["Service"]["getChangeRequest"]
214 >[0],
215 ) {
216 const repo = yield* cli.resolveRepository(input);
217 const number = /(?:^#?|\/pulls\/)(\d+)(?:\/[^?#]*)?(?:[?#].*)?$/.exec(input.reference)?.[1];
218 if (!number)
219 return yield* new ForgejoCli.ForgejoCliError({
220 command: "tea",
221 cwd: input.cwd,
222 detail: "Specify a pull request number or Forgejo pull request URL.",
223 });
224 return yield* request(
225 { ...input, path: `${repositoryPath(repo.repository)}/pulls/${number}` },
226 ForgejoPullRequestSchema,
227 );
228 });
229 return SourceControlProvider.SourceControlProvider.of({
230 kind: "forgejo",
231 listChangeRequests: (input) =>
232 Effect.gen(function* () {
233 const repo = yield* cli.resolveRepository(input);
234 const source = SourceControlProvider.sourceControlRefFromInput(input);
235 const branch = SourceControlProvider.sourceBranch(input);
236 const results: ReturnType<typeof toForgejoChangeRequest>[] = [];
237 const limit = input.limit ?? 20;
238 for (let page = 1; results.length < limit; page++) {
239 const items = yield* request(
240 {
241 ...input,
242 path: `${repositoryPath(repo.repository)}/pulls?state=${input.state === "merged" ? "closed" : input.state}&sort=recentupdate&limit=50&page=${page}`,
243 },
244 Schema.Array(ForgejoPullRequestSchema),
245 );
246 for (const item of items) {
247 if (
248 item.head.ref !== branch ||
249 (source?.repository && item.head.repo?.full_name !== source.repository) ||
250 (source?.owner && item.head.repo?.owner.login !== source.owner)
251 )
252 continue;
253 const normalized = toForgejoChangeRequest(item);
254 if (input.state === "all" || normalized.state === input.state) results.push(normalized);
255 }
256 if (items.length === 0) break;
257 }
258 return results.slice(0, limit);
259 }).pipe(mapError("listChangeRequests", input.cwd)),
260 getChangeRequest: (input) =>
261 getPull(input).pipe(
262 Effect.map(toForgejoChangeRequest),
263 mapError("getChangeRequest", input.cwd),
264 ),
265 createChangeRequest: (input) =>
266 Effect.gen(function* () {
267 const repo = yield* cli.resolveRepository(input);
268 const source = SourceControlProvider.sourceControlRefFromInput(input);
269 const owner = source?.owner ?? source?.repository?.split("/")[0];
270 const head = SourceControlProvider.sourceBranch(input);
271 yield* cli.api({
272 ...input,
273 path: `${repositoryPath(input.target?.repository ?? repo.repository)}/pulls`,
274 method: "POST",
275 body: {
276 base: input.target?.refName ?? input.baseRefName,
277 head: owner ? `${owner}:${head}` : head,
278 title: input.title,
279 body: yield* fs.readFileString(input.bodyFile),
280 },
281 });
282 }).pipe(mapError("createChangeRequest", input.cwd)),
283 getRepositoryCloneUrls: (input) =>
284 Effect.gen(function* () {
285 const repo = yield* cli.resolveRepository(input);
286 return cloneUrls(
287 yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema),
288 );
289 }).pipe(mapError("getRepositoryCloneUrls", input.cwd)),
290 createRepository: (input) =>
291 Effect.gen(function* () {
292 const repo = yield* cli.resolveRepository(input);
293 const user = yield* request(
294 { ...input, path: "user" },
295 Schema.Struct({ login: Schema.String }),
296 );
297 const [owner, name] = repo.repository.split("/");
298 return cloneUrls(
299 yield* request(
300 {
301 ...input,
302 path:
303 owner === user.login
304 ? "user/repos"
305 : `orgs/${encodeURIComponent(owner ?? "")}/repos`,
306 method: "POST",
307 body: { name, private: input.visibility === "private", auto_init: false },
308 },
309 RepositorySchema,
310 ),
311 );
312 }).pipe(mapError("createRepository", input.cwd)),
313 getDefaultBranch: (input) =>
314 Effect.gen(function* () {
315 const repo = yield* cli.resolveRepository(input);
316 return (
317 (yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema))
318 .default_branch ?? null
319 );
320 }).pipe(mapError("getDefaultBranch", input.cwd)),
321 checkoutChangeRequest: (input) =>
322 Effect.gen(function* () {
323 const repo = yield* cli.resolveRepository(input);
324 const pull = yield* getPull(input);
325 if (repo.command === "fj") {
326 // fj checkout cannot target a repository outside the local remotes.
327 const urls = yield* request(
328 { ...input, path: repositoryPath(repo.repository) },
329 RepositorySchema,
330 );
331 const remote = input.context?.remoteUrl;
332 const useSsh = remote && ForgejoCli.parseForgejoRemote(remote)?.ssh;
333 yield* process.run({
334 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
335 command: "git",
336 cwd: input.cwd,
337 args: [
338 "fetch",
339 "--",
340 useSsh ? urls.ssh_url : urls.clone_url,
341 `refs/pull/${pull.number}/head`,
342 ],
343 });
344 const branch = `pulls/${pull.number}`;
345 const existing = yield* process.run({
346 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
347 command: "git",
348 cwd: input.cwd,
349 args: ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`],
350 allowNonZeroExit: true,
351 });
352 yield* process.run({
353 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
354 command: "git",
355 cwd: input.cwd,
356 args:
357 existing.exitCode === 0
358 ? ["checkout", branch]
359 : ["checkout", "-b", branch, "FETCH_HEAD"],
360 });
361 } else
362 yield* cli.execute({
363 cwd: input.cwd,
364 args: [
365 "pulls",
366 "checkout",
367 "--login",
368 repo.login,
369 "--repo",
370 repo.repository,
371 "--branch",
372 String(pull.number),
373 ],
374 });
375 if (input.force) {
376 // tea leaves an existing PR branch at its old tip. Keep dirty files safe
377 // while bringing the selected branch to the PR revision we fetched.
378 yield* process.run({
379 operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
380 command: "git",
381 cwd: input.cwd,
382 args: ["reset", "--keep", pull.head.sha],
383 });
384 }
385 }).pipe(mapError("checkoutChangeRequest", input.cwd)),
386 });
387});