refactor(source-control): Forgejo lives in @t3tools/source-control-forgejo (#17581)
Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
28f11ed7a5
commit
f6e45028ef
31 files changed
+1632
-1303
No files matched your search
@@ -1,724 +0,0 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as NodeOS from "node:os";
|
||||
// @effect-diagnostics-next-line nodeBuiltinImport:off - fj storage paths use explicit Windows and POSIX layouts, independently of this process's platform.
|
||||
import * as NodePath from "node:path";
|
||||
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
|
||||
import { ChildProcessSpawner } from "effect/process";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
|
||||
import type { SourceControlProviderContext } from "@t3tools/source-control-core/server/SourceControlProvider";
|
||||
|
||||
const encodeApiBody = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
|
||||
|
||||
export class ForgejoCliError extends Schema.TaggedError<ForgejoCliError>()("ForgejoCliError", {
|
||||
command: Schema.Literals(["fj", "tea"]),
|
||||
cwd: Schema.String,
|
||||
detail: Schema.String,
|
||||
reason: Schema.optional(
|
||||
Schema.Literals([
|
||||
"missing-cli",
|
||||
"authentication",
|
||||
"forbidden",
|
||||
"not-found",
|
||||
"rate-limit",
|
||||
"invalid-response",
|
||||
]),
|
||||
),
|
||||
httpStatus: Schema.optional(Schema.Int),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {}
|
||||
|
||||
export const ForgejoLoginSchema = Schema.Struct({
|
||||
name: Schema.String,
|
||||
url: Schema.String,
|
||||
ssh_host: Schema.optional(Schema.String),
|
||||
valid: Schema.optional(Schema.String),
|
||||
user: Schema.String,
|
||||
default: Schema.String,
|
||||
});
|
||||
|
||||
export function parseForgejoLogins(raw: string) {
|
||||
const decoded = decodeJsonResult(Schema.Array(ForgejoLoginSchema))(raw);
|
||||
return Result.isSuccess(decoded) ? decoded.success : [];
|
||||
}
|
||||
|
||||
export const ForgejoKeysSchema = Schema.Struct({
|
||||
hosts: Schema.Record(
|
||||
Schema.String,
|
||||
Schema.Struct({
|
||||
type: Schema.Literals(["Application", "OAuth"]),
|
||||
token: Schema.String,
|
||||
}),
|
||||
),
|
||||
aliases: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
||||
});
|
||||
|
||||
const parseForgejoKeys = decodeJsonResult(ForgejoKeysSchema);
|
||||
|
||||
/** Matches fj's directories::ProjectDirs, including its pre-0.6 organization name. */
|
||||
function forgejoKeysPaths(input: {
|
||||
readonly platform: string;
|
||||
readonly home: string;
|
||||
readonly dataHome?: string;
|
||||
readonly appData?: string;
|
||||
}) {
|
||||
if (input.platform === "darwin")
|
||||
return ["forgejo-cli", "Cyborus"].map((organization) =>
|
||||
NodePath.join(
|
||||
input.home,
|
||||
"Library",
|
||||
"Application Support",
|
||||
`${organization}.forgejo-cli`,
|
||||
"keys.json",
|
||||
),
|
||||
);
|
||||
if (input.platform === "win32")
|
||||
return ["forgejo-cli", "Cyborus"].map((organization) =>
|
||||
NodePath.win32.join(
|
||||
input.appData || NodePath.win32.join(input.home, "AppData", "Roaming"),
|
||||
organization,
|
||||
"forgejo-cli",
|
||||
"data",
|
||||
"keys.json",
|
||||
),
|
||||
);
|
||||
return [
|
||||
NodePath.join(
|
||||
input.dataHome && NodePath.isAbsolute(input.dataHome)
|
||||
? input.dataHome
|
||||
: NodePath.join(input.home, ".local", "share"),
|
||||
"forgejo-cli",
|
||||
"keys.json",
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
export interface ForgejoRepositoryInput {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProviderContext;
|
||||
readonly repository?: string;
|
||||
readonly reference?: string;
|
||||
readonly host?: string;
|
||||
}
|
||||
|
||||
export interface ForgejoRepository {
|
||||
readonly command?: "fj" | "tea";
|
||||
readonly login: string;
|
||||
readonly repository: string;
|
||||
readonly baseUrl: string;
|
||||
}
|
||||
|
||||
export interface ForgejoApiInput extends ForgejoRepositoryInput {
|
||||
readonly path: string;
|
||||
readonly method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
||||
readonly body?: unknown;
|
||||
}
|
||||
|
||||
export class ForgejoCli extends Context.Service<
|
||||
ForgejoCli,
|
||||
{
|
||||
readonly execute: (input: {
|
||||
readonly command?: "fj" | "tea";
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly stdin?: string;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
}) => Effect.Effect<VcsProcess.VcsProcessOutput, ForgejoCliError>;
|
||||
readonly listLogins?: (input: {
|
||||
readonly cwd: string;
|
||||
readonly command: "fj" | "tea";
|
||||
readonly remoteUrl?: string;
|
||||
}) => Effect.Effect<ReturnType<typeof parseForgejoLogins>, ForgejoCliError>;
|
||||
readonly getAccount?: (input: {
|
||||
readonly cwd: string;
|
||||
readonly baseUrl: string;
|
||||
}) => Effect.Effect<string, ForgejoCliError>;
|
||||
readonly resolveRepository: (
|
||||
input: ForgejoRepositoryInput,
|
||||
) => Effect.Effect<ForgejoRepository, ForgejoCliError>;
|
||||
readonly api: (
|
||||
input: ForgejoApiInput,
|
||||
) => Effect.Effect<VcsProcess.VcsProcessOutput, ForgejoCliError>;
|
||||
}
|
||||
>()("t3/sourceControl/ForgejoCli") {}
|
||||
|
||||
export function parseForgejoRemote(value: string) {
|
||||
if (/^(?:https?|ssh):\/\//i.test(value)) {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return {
|
||||
host: url.host.toLowerCase(),
|
||||
hostname: url.hostname.toLowerCase(),
|
||||
ssh: url.protocol === "ssh:",
|
||||
path: url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/, ""),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
// SCP remotes may omit the username; URL treats these as a custom scheme.
|
||||
const ssh = /^(?:[^@/]+@)?([^:/]+):([^/].*)$/.exec(value);
|
||||
return ssh?.[1] && ssh[2]
|
||||
? {
|
||||
host: ssh[1].toLowerCase(),
|
||||
hostname: ssh[1].toLowerCase(),
|
||||
ssh: true,
|
||||
path: ssh[2].replace(/\.git$/, ""),
|
||||
}
|
||||
: null;
|
||||
}
|
||||
|
||||
export function matchForgejoLogin(
|
||||
logins: ReturnType<typeof parseForgejoLogins>,
|
||||
remote: NonNullable<ReturnType<typeof parseForgejoRemote>>,
|
||||
requestedHost?: string,
|
||||
hostOnly = false,
|
||||
) {
|
||||
const matches = [
|
||||
...new Map(
|
||||
logins
|
||||
.filter((login) => {
|
||||
const url = parseForgejoRemote(login.url);
|
||||
if (!url) return false;
|
||||
if (requestedHost !== undefined && url.host !== requestedHost.toLowerCase()) return false;
|
||||
return remote.ssh
|
||||
? login.ssh_host?.toLowerCase() === remote.host ||
|
||||
login.ssh_host?.toLowerCase() === remote.hostname ||
|
||||
url.hostname === remote.hostname
|
||||
: url.host === remote.host &&
|
||||
((hostOnly && !remote.path) ||
|
||||
!url.path ||
|
||||
remote.path === url.path ||
|
||||
remote.path.startsWith(`${url.path}/`));
|
||||
})
|
||||
.map((login) => [login.name, login]),
|
||||
).values(),
|
||||
];
|
||||
return matches.length === 1
|
||||
? matches[0]
|
||||
: new Set(matches.map((login) => login.url)).size === 1
|
||||
? matches.find((login) => login.default === "true")
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const authLock = yield* Semaphore.make(1);
|
||||
const authenticated = new Map<string, { token: string; time: number }>();
|
||||
const execute: ForgejoCli["Service"]["execute"] = (input) =>
|
||||
process
|
||||
.run({
|
||||
...input,
|
||||
operation: "ForgejoCli.execute",
|
||||
command: input.command ?? "tea",
|
||||
timeoutMs: input.timeoutMs ?? 30_000,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ForgejoCliError({
|
||||
command: input.command ?? "tea",
|
||||
cwd: input.cwd,
|
||||
...(input.command === "fj" ? {} : { cause }),
|
||||
...(cause._tag === "VcsProcessSpawnError"
|
||||
? { reason: "missing-cli" as const }
|
||||
: cause._tag === "VcsProcessExitError" && cause.failureKind === "authentication"
|
||||
? { reason: "authentication" as const }
|
||||
: {}),
|
||||
detail:
|
||||
cause._tag === "VcsProcessSpawnError"
|
||||
? "Install Forgejo CLI (`fj` 0.6 or later) or Gitea CLI (`tea` 0.16 or later) and retry."
|
||||
: cause._tag === "VcsProcessExitError" && cause.failureKind === "authentication"
|
||||
? "Authenticate this server with `fj auth login`, `fj auth add-token`, or `tea login add`."
|
||||
: "Forgejo CLI command failed.",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const readKeys = Effect.fn("ForgejoCli.readKeys")(function* (cwd: string) {
|
||||
for (const path of forgejoKeysPaths({
|
||||
platform: yield* HostProcessPlatform,
|
||||
home: NodeOS.homedir(),
|
||||
...(globalThis.process.env.XDG_DATA_HOME
|
||||
? { dataHome: globalThis.process.env.XDG_DATA_HOME }
|
||||
: {}),
|
||||
...(globalThis.process.env.APPDATA ? { appData: globalThis.process.env.APPDATA } : {}),
|
||||
})) {
|
||||
const exists = yield* fileSystem.exists(path).pipe(
|
||||
Effect.mapError(
|
||||
() =>
|
||||
new ForgejoCliError({
|
||||
command: "fj",
|
||||
cwd,
|
||||
reason: "authentication",
|
||||
detail: "Could not read fj authentication storage.",
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (!exists) continue;
|
||||
const raw = yield* fileSystem.readFileString(path).pipe(
|
||||
Effect.mapError(
|
||||
() =>
|
||||
new ForgejoCliError({
|
||||
command: "fj",
|
||||
cwd,
|
||||
reason: "authentication",
|
||||
detail: "Could not read fj authentication storage.",
|
||||
}),
|
||||
),
|
||||
);
|
||||
const decoded = parseForgejoKeys(raw);
|
||||
if (Result.isFailure(decoded))
|
||||
return yield* new ForgejoCliError({
|
||||
command: "fj",
|
||||
cwd,
|
||||
reason: "authentication",
|
||||
detail: "fj authentication storage is invalid. Authenticate again with fj.",
|
||||
});
|
||||
return decoded.success;
|
||||
}
|
||||
const empty: typeof ForgejoKeysSchema.Type = { hosts: {}, aliases: {} };
|
||||
return empty;
|
||||
});
|
||||
|
||||
const publicLogins = (
|
||||
keys: typeof ForgejoKeysSchema.Type,
|
||||
remoteUrl?: string,
|
||||
): ReturnType<typeof parseForgejoLogins> => {
|
||||
const remote = remoteUrl ? parseForgejoRemote(remoteUrl) : null;
|
||||
return Object.keys(keys.hosts).flatMap((host) => {
|
||||
const url = parseForgejoRemote(`https://${host}`);
|
||||
// fj 0.6 drops URL mounts during whoami and OAuth renewal; tea supports them.
|
||||
if (!url || url.path) return [];
|
||||
// fj omits the scheme in storage. Only an explicit matching HTTP remote opts into HTTP.
|
||||
const scheme =
|
||||
remote && !remote.ssh && remote.host === url.host && /^http:\/\//i.test(remoteUrl ?? "")
|
||||
? "http"
|
||||
: "https";
|
||||
const login = { name: host, url: `${scheme}://${host}`, user: "", default: "false" };
|
||||
const aliases = Object.entries(keys.aliases ?? {})
|
||||
.filter(([, target]) => target === host)
|
||||
.map(([alias]) => ({ ...login, ssh_host: alias }));
|
||||
return aliases.length ? aliases : [login];
|
||||
});
|
||||
};
|
||||
|
||||
const listLogins: NonNullable<ForgejoCli["Service"]["listLogins"]> = Effect.fn(
|
||||
"ForgejoCli.listLogins",
|
||||
)(function* (input) {
|
||||
if (input.command === "fj") {
|
||||
const keys = yield* readKeys(input.cwd).pipe(Effect.result);
|
||||
if (Result.isFailure(keys)) {
|
||||
// Stale credentials from an uninstalled fj must not disable an available tea login.
|
||||
const available = yield* execute({ command: "fj", cwd: input.cwd, args: ["version"] }).pipe(
|
||||
Effect.result,
|
||||
);
|
||||
if (Result.isFailure(available) && available.failure.reason === "missing-cli") return [];
|
||||
return yield* keys.failure;
|
||||
}
|
||||
return publicLogins(keys.success, input.remoteUrl);
|
||||
}
|
||||
return parseForgejoLogins(
|
||||
(yield* execute({ cwd: input.cwd, args: ["login", "list", "--output", "json"] })).stdout,
|
||||
);
|
||||
});
|
||||
|
||||
const requestFj = Effect.fn("ForgejoCli.requestFj")(
|
||||
function* (input: {
|
||||
readonly cwd: string;
|
||||
readonly baseUrl: string;
|
||||
readonly token: string;
|
||||
readonly path: string;
|
||||
readonly method?: ForgejoApiInput["method"];
|
||||
readonly body?: string;
|
||||
}) {
|
||||
const base = new URL(`${input.baseUrl}/api/v1/`);
|
||||
const url = new URL(input.path, base);
|
||||
if (
|
||||
url.origin !== base.origin ||
|
||||
!url.pathname.startsWith(base.pathname) ||
|
||||
url.username ||
|
||||
url.password
|
||||
)
|
||||
return yield* new ForgejoCliError({
|
||||
command: "fj",
|
||||
cwd: input.cwd,
|
||||
detail: "Invalid Forgejo API path.",
|
||||
});
|
||||
let request = HttpClientRequest.make(input.method ?? "GET")(url.toString()).pipe(
|
||||
HttpClientRequest.setHeader("Authorization", `token ${input.token}`),
|
||||
);
|
||||
if (input.body !== undefined)
|
||||
request = request.pipe(HttpClientRequest.bodyText(input.body, "application/json"));
|
||||
const response = yield* httpClient
|
||||
.execute(request)
|
||||
.pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }));
|
||||
const status = response.status;
|
||||
const body =
|
||||
status === 204 || status === 205
|
||||
? { text: "", truncated: false, invalidUtf8: false }
|
||||
: yield* collectUint8StreamText({
|
||||
stream: response.stream,
|
||||
maxBytes: 8 * 1024 * 1024,
|
||||
});
|
||||
if (body.truncated || body.invalidUtf8)
|
||||
return yield* new ForgejoCliError({
|
||||
command: "fj",
|
||||
cwd: input.cwd,
|
||||
reason: "invalid-response",
|
||||
detail: "Forgejo returned an oversized or invalid response.",
|
||||
});
|
||||
if (status < 200 || status >= 300) {
|
||||
const detail =
|
||||
status === 404
|
||||
? "Forgejo repository or pull request was not found."
|
||||
: body.text
|
||||
? `Forgejo API request failed (HTTP ${status}): ${body.text}`
|
||||
: `Forgejo API request failed (HTTP ${status}). Check this server's fj credentials and permissions.`;
|
||||
return yield* new ForgejoCliError({
|
||||
command: "fj",
|
||||
cwd: input.cwd,
|
||||
httpStatus: status,
|
||||
...(status === 401
|
||||
? { reason: "authentication" as const }
|
||||
: status === 403
|
||||
? { reason: "forbidden" as const }
|
||||
: status === 404
|
||||
? { reason: "not-found" as const }
|
||||
: status === 429
|
||||
? { reason: "rate-limit" as const }
|
||||
: {}),
|
||||
detail,
|
||||
});
|
||||
}
|
||||
return {
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout: body.text,
|
||||
stderr: `HTTP/1.1 ${status}\n${response.headers.link ? `link: ${response.headers.link}\n` : ""}`,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
},
|
||||
(effect, input) =>
|
||||
effect.pipe(
|
||||
Effect.timeout(30_000),
|
||||
Effect.mapError((error) =>
|
||||
error._tag === "ForgejoCliError"
|
||||
? error
|
||||
: new ForgejoCliError({
|
||||
command: "fj",
|
||||
cwd: input.cwd,
|
||||
detail: "Forgejo API request failed or timed out.",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const authenticateFj = Effect.fn("ForgejoCli.authenticateFj")(function* (
|
||||
cwd: string,
|
||||
login: typeof ForgejoLoginSchema.Type,
|
||||
) {
|
||||
const keys = yield* readKeys(cwd);
|
||||
const token = keys.hosts[login.name]?.token;
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const cached = authenticated.get(login.url);
|
||||
if (token && cached?.token === token && now - cached.time < 30_000) return token;
|
||||
yield* execute({ command: "fj", cwd, args: ["--host", login.url, "whoami"] });
|
||||
// fj owns OAuth renewal. Re-read the file after it has refreshed an expired token.
|
||||
const refreshed = (yield* readKeys(cwd)).hosts[login.name]?.token;
|
||||
if (!refreshed)
|
||||
return yield* new ForgejoCliError({
|
||||
command: "fj",
|
||||
cwd,
|
||||
reason: "authentication",
|
||||
detail: "fj has no credentials for this server. Authenticate again with fj.",
|
||||
});
|
||||
authenticated.set(login.url, { token: refreshed, time: now });
|
||||
return refreshed;
|
||||
}, authLock.withPermits(1));
|
||||
|
||||
const getAccount: NonNullable<ForgejoCli["Service"]["getAccount"]> = Effect.fn(
|
||||
"ForgejoCli.getAccount",
|
||||
)(function* (input) {
|
||||
const logins = yield* listLogins({ cwd: input.cwd, command: "fj", remoteUrl: input.baseUrl });
|
||||
const login = logins.find(
|
||||
(item) => item.url.replace(/\/+$/, "") === input.baseUrl.replace(/\/+$/, ""),
|
||||
);
|
||||
if (!login)
|
||||
return yield* new ForgejoCliError({
|
||||
command: "fj",
|
||||
cwd: input.cwd,
|
||||
reason: "authentication",
|
||||
detail: "fj has no credentials for this server.",
|
||||
});
|
||||
const token = yield* authenticateFj(input.cwd, login);
|
||||
const currentUser = yield* requestFj({
|
||||
cwd: input.cwd,
|
||||
baseUrl: login.url.replace(/\/+$/, ""),
|
||||
token,
|
||||
path: "user",
|
||||
});
|
||||
const user = decodeJsonResult(Schema.Struct({ login: Schema.String }))(currentUser.stdout);
|
||||
if (Result.isFailure(user) || !user.success.login.trim())
|
||||
return yield* new ForgejoCliError({
|
||||
command: "fj",
|
||||
cwd: input.cwd,
|
||||
reason: "invalid-response",
|
||||
detail: "Forgejo returned an invalid account response.",
|
||||
});
|
||||
return user.success.login;
|
||||
});
|
||||
|
||||
const resolveTarget = Effect.fn("ForgejoCli.resolveTarget")(function* (
|
||||
input: ForgejoRepositoryInput,
|
||||
hostOnly = false,
|
||||
) {
|
||||
const referenceRemote = input.reference ? parseForgejoRemote(input.reference) : null;
|
||||
let remoteUrl = [input.reference, input.repository, input.context?.remoteUrl].find(
|
||||
(value) => value && parseForgejoRemote(value),
|
||||
);
|
||||
let remote =
|
||||
referenceRemote ??
|
||||
(input.repository ? parseForgejoRemote(input.repository) : null) ??
|
||||
(input.context ? parseForgejoRemote(input.context.remoteUrl) : null);
|
||||
if (!remote && (!input.repository || input.host)) {
|
||||
const result = yield* process
|
||||
.run({
|
||||
operation: "ForgejoCli.remote",
|
||||
command: "git",
|
||||
args: input.host ? ["remote", "-v"] : ["remote", "get-url", "origin"],
|
||||
cwd: input.cwd,
|
||||
allowNonZeroExit: true,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ForgejoCliError({
|
||||
command: "tea",
|
||||
cwd: input.cwd,
|
||||
detail: "Could not resolve the Forgejo repository remote.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (input.host) {
|
||||
const matchingUrls = [
|
||||
...new Set(
|
||||
result.stdout.split("\n").flatMap((line) => {
|
||||
const url = /^\S+\s+(https?:\/\/\S+)\s+\(fetch\)$/.exec(line.trim())?.[1];
|
||||
return url && parseForgejoRemote(url)?.host === input.host?.toLowerCase()
|
||||
? [url]
|
||||
: [];
|
||||
}),
|
||||
),
|
||||
];
|
||||
const origins = [...new Set(matchingUrls.map((url) => new URL(url).origin))];
|
||||
remoteUrl =
|
||||
matchingUrls.length === 1
|
||||
? matchingUrls[0]
|
||||
: origins.length === 1
|
||||
? origins[0]
|
||||
: undefined;
|
||||
} else {
|
||||
remoteUrl = result.stdout.trim();
|
||||
}
|
||||
remote = remoteUrl ? parseForgejoRemote(remoteUrl) : null;
|
||||
}
|
||||
if (
|
||||
input.host &&
|
||||
!remote?.ssh &&
|
||||
remote?.host !== input.host.toLowerCase() &&
|
||||
remote?.hostname !== input.host.toLowerCase()
|
||||
)
|
||||
remote = {
|
||||
host: input.host.toLowerCase(),
|
||||
hostname: input.host.split(":")[0] ?? input.host,
|
||||
ssh: false,
|
||||
path: remote?.path ?? "",
|
||||
};
|
||||
const schemeRemoteUrl = remote?.ssh ? input.context?.provider.baseUrl : remoteUrl;
|
||||
const fjLogins = yield* listLogins({
|
||||
cwd: input.cwd,
|
||||
command: "fj",
|
||||
...(schemeRemoteUrl ? { remoteUrl: schemeRemoteUrl } : {}),
|
||||
});
|
||||
const requestedHost = input.host ?? input.context?.requestedHost;
|
||||
const matchHostOnly = hostOnly || (!!input.host && !remote?.path);
|
||||
const selectLogin = (logins: ReturnType<typeof parseForgejoLogins>) =>
|
||||
remote
|
||||
? matchForgejoLogin(logins, remote, remote.ssh ? requestedHost : undefined, matchHostOnly)
|
||||
: (logins.find((item) => item.default === "true") ??
|
||||
(new Set(logins.map((item) => item.name)).size === 1 ? logins[0] : undefined));
|
||||
let login = selectLogin(fjLogins);
|
||||
let command: "fj" | "tea" = "fj";
|
||||
if (
|
||||
!login &&
|
||||
fjLogins.some(
|
||||
(item) =>
|
||||
!remote ||
|
||||
matchForgejoLogin([item], remote, remote.ssh ? requestedHost : undefined, matchHostOnly),
|
||||
)
|
||||
) {
|
||||
const available = yield* execute({ command: "fj", cwd: input.cwd, args: ["version"] }).pipe(
|
||||
Effect.result,
|
||||
);
|
||||
if (Result.isSuccess(available))
|
||||
return yield* new ForgejoCliError({
|
||||
command: "fj",
|
||||
cwd: input.cwd,
|
||||
reason: "authentication",
|
||||
detail: "Multiple fj logins match this repository. Specify its full server URL.",
|
||||
});
|
||||
if (available.failure.reason !== "missing-cli") return yield* available.failure;
|
||||
}
|
||||
if (login) {
|
||||
const auth = yield* authenticateFj(input.cwd, login).pipe(Effect.result);
|
||||
if (Result.isFailure(auth)) {
|
||||
if (auth.failure.reason === "missing-cli") login = undefined;
|
||||
else return yield* auth.failure;
|
||||
}
|
||||
}
|
||||
if (!login) {
|
||||
command = "tea";
|
||||
login = selectLogin(yield* listLogins({ cwd: input.cwd, command: "tea" }));
|
||||
}
|
||||
if (!login)
|
||||
return yield* new ForgejoCliError({
|
||||
command: "tea",
|
||||
cwd: input.cwd,
|
||||
reason: "authentication",
|
||||
detail:
|
||||
"No matching Forgejo login. Use `fj auth login`, `fj auth add-token`, or `tea login add` for this server; choose a default when multiple tea accounts match.",
|
||||
});
|
||||
if (hostOnly)
|
||||
return { command, login: login.name, repository: "", baseUrl: login.url.replace(/\/+$/, "") };
|
||||
const path =
|
||||
referenceRemote?.path ??
|
||||
(input.repository && !parseForgejoRemote(input.repository)
|
||||
? input.repository
|
||||
: remote?.path) ??
|
||||
"";
|
||||
const basePath = new URL(login.url).pathname.replace(/^\/+|\/+$/g, "");
|
||||
const relativePath =
|
||||
basePath && path.split("/").length > 2 && path.startsWith(`${basePath}/`)
|
||||
? path.slice(basePath.length + 1)
|
||||
: path;
|
||||
const repositoryPath = relativePath.replace(/\/pulls\/\d+.*$/, "").replace(/\.git$/, "");
|
||||
if (command === "fj" && !repositoryPath.includes("/")) {
|
||||
login = { ...login, user: yield* getAccount({ cwd: input.cwd, baseUrl: login.url }) };
|
||||
}
|
||||
const repository = repositoryPath.includes("/")
|
||||
? repositoryPath
|
||||
: `${login.user}/${repositoryPath}`;
|
||||
if (!/^[^/\s]+\/[^/\s]+$/.test(repository))
|
||||
return yield* new ForgejoCliError({
|
||||
command,
|
||||
cwd: input.cwd,
|
||||
detail: "Specify a Forgejo repository as owner/repository or its full server URL.",
|
||||
});
|
||||
return { command, login: login.name, repository, baseUrl: login.url.replace(/\/+$/, "") };
|
||||
});
|
||||
const resolveRepository = (input: ForgejoRepositoryInput) => resolveTarget(input);
|
||||
const api = Effect.fn("ForgejoCli.api")(function* (input: ForgejoApiInput) {
|
||||
const repository = yield* resolveTarget(
|
||||
input,
|
||||
input.path.replace(/^\/+/, "") === "user" && (!input.method || input.method === "GET"),
|
||||
);
|
||||
const stdin =
|
||||
input.body === undefined
|
||||
? undefined
|
||||
: yield* encodeApiBody(input.body).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ForgejoCliError({
|
||||
command: "tea",
|
||||
cwd: input.cwd,
|
||||
detail: "Could not encode the Forgejo request body.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
let path = input.path.replace(/^\/+/, "");
|
||||
if (input.repository && input.repository !== repository.repository) {
|
||||
// Repository identities retain the server mount path; API routes do not.
|
||||
const prefix = `repos/${input.repository.split("/").map(encodeURIComponent).join("/")}`;
|
||||
if (path === prefix || path.startsWith(`${prefix}/`) || path.startsWith(`${prefix}?`)) {
|
||||
path = `repos/${repository.repository.split("/").map(encodeURIComponent).join("/")}${path.slice(prefix.length)}`;
|
||||
}
|
||||
}
|
||||
if (repository.command === "fj") {
|
||||
const token = (yield* readKeys(input.cwd)).hosts[repository.login]?.token;
|
||||
if (!token)
|
||||
return yield* new ForgejoCliError({
|
||||
command: "fj",
|
||||
cwd: input.cwd,
|
||||
reason: "authentication",
|
||||
detail: "fj has no credentials for this server.",
|
||||
});
|
||||
return yield* requestFj({
|
||||
cwd: input.cwd,
|
||||
baseUrl: repository.baseUrl,
|
||||
token,
|
||||
path,
|
||||
...(input.method === undefined ? {} : { method: input.method }),
|
||||
...(stdin === undefined ? {} : { body: stdin }),
|
||||
});
|
||||
}
|
||||
const result = yield* execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"api",
|
||||
"--include",
|
||||
"--login",
|
||||
repository.login,
|
||||
...(repository.repository ? ["--repo", repository.repository] : []),
|
||||
"--method",
|
||||
input.method ?? "GET",
|
||||
...(input.body === undefined ? [] : ["--data", "@-"]),
|
||||
`${repository.baseUrl}/api/v1/${path}`,
|
||||
],
|
||||
...(stdin === undefined ? {} : { stdin }),
|
||||
});
|
||||
// tea reports HTTP failures with exit code zero; use its response status.
|
||||
const status = Number(/^HTTP\/\S+ (\d{3})/m.exec(result.stderr)?.[1]);
|
||||
if (!status || status >= 400)
|
||||
return yield* new ForgejoCliError({
|
||||
command: "tea",
|
||||
cwd: input.cwd,
|
||||
...(status ? { httpStatus: status } : {}),
|
||||
...(status === 401
|
||||
? { reason: "authentication" as const }
|
||||
: status === 403
|
||||
? { reason: "forbidden" as const }
|
||||
: status === 404
|
||||
? { reason: "not-found" as const }
|
||||
: status === 429
|
||||
? { reason: "rate-limit" as const }
|
||||
: {}),
|
||||
detail:
|
||||
status === 401 || status === 403
|
||||
? "Forgejo denied access. Check this server's `tea login` credentials and permissions."
|
||||
: status === 404
|
||||
? "Forgejo repository or pull request was not found."
|
||||
: status === 429
|
||||
? "Forgejo API rate limit exceeded."
|
||||
: `Forgejo API request failed${status ? ` (HTTP ${status})` : " without an HTTP status"}.`,
|
||||
});
|
||||
return result;
|
||||
});
|
||||
return ForgejoCli.of({ execute, listLogins, getAccount, resolveRepository, api });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ForgejoCli, make);
|
||||
@@ -1,387 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Result from "effect/Result";
|
||||
import { SourceControlProviderError } from "@t3tools/contracts";
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as ForgejoCli from "./ForgejoCli.ts";
|
||||
import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
|
||||
import {
|
||||
providerAuth,
|
||||
probeSourceControlProvider,
|
||||
type SourceControlCliDiscoverySpec,
|
||||
type SourceControlManagedCliDiscoverySpec,
|
||||
} from "@t3tools/source-control-core/server/discovery";
|
||||
import { ForgejoPullRequestSchema, toForgejoChangeRequest } from "./forgejoPullRequests.ts";
|
||||
|
||||
const isForgejoCliError = Schema.is(ForgejoCli.ForgejoCliError);
|
||||
|
||||
export const discovery = {
|
||||
type: "cli",
|
||||
kind: "forgejo",
|
||||
label: "Forgejo / Gitea",
|
||||
executable: "tea",
|
||||
versionArgs: ["--version"],
|
||||
authArgs: ["login", "status", "--output", "json"],
|
||||
remoteRefinementArgs: ["login", "list", "--output", "json"],
|
||||
parseAuth: (input) => {
|
||||
const logins = ForgejoCli.parseForgejoLogins(input.stdout);
|
||||
const login = logins.find((entry) => entry.default === "true") ?? logins[0];
|
||||
return login
|
||||
? providerAuth({
|
||||
status: login.valid === "true" ? "authenticated" : "unauthenticated",
|
||||
account: login.user,
|
||||
host: ForgejoCli.parseForgejoRemote(login.url)?.host,
|
||||
})
|
||||
: providerAuth({
|
||||
status: "unauthenticated",
|
||||
detail: "Run `tea login add` to authenticate a Forgejo or Gitea server.",
|
||||
});
|
||||
},
|
||||
refineUnknownRemote: (input) => {
|
||||
const remote = ForgejoCli.parseForgejoRemote(input.context.remoteUrl);
|
||||
const login =
|
||||
remote &&
|
||||
ForgejoCli.matchForgejoLogin(
|
||||
ForgejoCli.parseForgejoLogins(input.auth.stdout),
|
||||
remote,
|
||||
input.context.requestedHost,
|
||||
);
|
||||
return login ? { kind: "forgejo", name: "Forgejo / Gitea", baseUrl: login.url } : null;
|
||||
},
|
||||
installHint:
|
||||
"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.",
|
||||
} satisfies SourceControlCliDiscoverySpec;
|
||||
|
||||
export const makeDiscovery = Effect.gen(function* () {
|
||||
const cli = yield* ForgejoCli.ForgejoCli;
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
const listLogins = cli.listLogins;
|
||||
if (!listLogins) return discovery;
|
||||
return {
|
||||
type: "managed-cli",
|
||||
kind: "forgejo",
|
||||
label: discovery.label,
|
||||
installHint: discovery.installHint,
|
||||
probe: Effect.fn("ForgejoSourceControlProvider.discovery")(function* (cwd: string) {
|
||||
const remoteUrl = yield* process
|
||||
.run({
|
||||
operation: "source-control.discovery.remote",
|
||||
command: "git",
|
||||
args: ["remote", "get-url", "origin"],
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 8_000,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.orElseSucceed(() => ""),
|
||||
);
|
||||
const credentials = yield* Effect.result(listLogins({ cwd, command: "fj", remoteUrl }));
|
||||
const logins = Result.isSuccess(credentials) ? credentials.success : [];
|
||||
const remote = ForgejoCli.parseForgejoRemote(remoteUrl);
|
||||
const login =
|
||||
(remote && ForgejoCli.matchForgejoLogin(logins, remote)) ||
|
||||
logins.find((entry) => entry.default === "true") ||
|
||||
logins[0];
|
||||
const fj = yield* probeSourceControlProvider({
|
||||
cwd,
|
||||
process,
|
||||
spec: {
|
||||
...discovery,
|
||||
executable: "fj",
|
||||
versionArgs: ["version"],
|
||||
authArgs: login ? ["--host", login.url, "whoami"] : ["auth", "list"],
|
||||
parseAuth: (result) =>
|
||||
Result.isFailure(credentials)
|
||||
? providerAuth({
|
||||
status: "unknown",
|
||||
detail: "Could not read fj authentication storage. Authenticate again with fj.",
|
||||
})
|
||||
: login && result.exitCode === 0
|
||||
? providerAuth({
|
||||
status: "authenticated",
|
||||
account: login.user,
|
||||
host: ForgejoCli.parseForgejoRemote(login.url)?.host,
|
||||
})
|
||||
: providerAuth({
|
||||
status: "unauthenticated",
|
||||
detail:
|
||||
"Authenticate this server with `fj --host <server-url> auth add-token`.",
|
||||
}),
|
||||
},
|
||||
});
|
||||
// A configured fj account owns its requests, including authentication errors.
|
||||
if (fj.status === "available" && (login || Result.isFailure(credentials))) {
|
||||
if (login && fj.auth.status === "authenticated" && cli.getAccount) {
|
||||
const account = yield* cli.getAccount({ cwd, baseUrl: login.url }).pipe(Effect.result);
|
||||
return {
|
||||
...fj,
|
||||
auth: Result.isSuccess(account)
|
||||
? providerAuth({
|
||||
status: "authenticated",
|
||||
account: account.success,
|
||||
host: ForgejoCli.parseForgejoRemote(login.url)?.host,
|
||||
})
|
||||
: providerAuth({
|
||||
status: "unknown",
|
||||
detail: account.failure.detail,
|
||||
host: ForgejoCli.parseForgejoRemote(login.url)?.host,
|
||||
}),
|
||||
};
|
||||
}
|
||||
return fj;
|
||||
}
|
||||
const tea = yield* probeSourceControlProvider({ cwd, process, spec: discovery });
|
||||
return tea.status === "available" || fj.status === "missing" ? tea : fj;
|
||||
}),
|
||||
refineUnknownRemote: Effect.fn("ForgejoSourceControlProvider.refineUnknownRemote")(
|
||||
function* (input: {
|
||||
readonly cwd: string;
|
||||
readonly context: SourceControlProvider.SourceControlProviderContext;
|
||||
}) {
|
||||
const remote = ForgejoCli.parseForgejoRemote(input.context.remoteUrl);
|
||||
if (!remote) return null;
|
||||
for (const command of ["fj", "tea"] as const) {
|
||||
const logins = yield* listLogins({
|
||||
cwd: input.cwd,
|
||||
command,
|
||||
remoteUrl: input.context.remoteUrl,
|
||||
}).pipe(Effect.orElseSucceed(() => []));
|
||||
const login = ForgejoCli.matchForgejoLogin(logins, remote, input.context.requestedHost);
|
||||
if (login) return { kind: "forgejo" as const, name: discovery.label, baseUrl: login.url };
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
} satisfies SourceControlManagedCliDiscoverySpec;
|
||||
});
|
||||
|
||||
const RepositorySchema = Schema.Struct({
|
||||
full_name: Schema.String,
|
||||
clone_url: Schema.String,
|
||||
ssh_url: Schema.String,
|
||||
default_branch: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
});
|
||||
const cloneUrls = (raw: typeof RepositorySchema.Type) => ({
|
||||
nameWithOwner: raw.full_name,
|
||||
url: raw.clone_url,
|
||||
sshUrl: raw.ssh_url,
|
||||
});
|
||||
const repositoryPath = (repository: string) =>
|
||||
`repos/${repository.split("/").map(encodeURIComponent).join("/")}`;
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const cli = yield* ForgejoCli.ForgejoCli;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
const request = <S extends Schema.Codec<unknown, unknown, never, never>>(
|
||||
input: ForgejoCli.ForgejoApiInput,
|
||||
schema: S,
|
||||
) =>
|
||||
cli.api(input).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
Schema.decodeEffect(Schema.fromJsonString(schema))(result.stdout).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ForgejoCli.ForgejoCliError({
|
||||
command: "tea",
|
||||
cwd: input.cwd,
|
||||
detail: "Forgejo API returned an invalid response.",
|
||||
reason: "invalid-response",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const mapError = (operation: string, cwd: string) =>
|
||||
Effect.mapError(
|
||||
(cause: unknown) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "forgejo",
|
||||
operation,
|
||||
cwd,
|
||||
...(isForgejoCliError(cause) ? { command: cause.command } : {}),
|
||||
detail: isForgejoCliError(cause) ? cause.detail : "Forgejo operation failed.",
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
const getPull = Effect.fn("ForgejoSourceControlProvider.getPull")(function* (
|
||||
input: Parameters<
|
||||
SourceControlProvider.SourceControlProvider["Service"]["getChangeRequest"]
|
||||
>[0],
|
||||
) {
|
||||
const repo = yield* cli.resolveRepository(input);
|
||||
const number = /(?:^#?|\/pulls\/)(\d+)(?:\/[^?#]*)?(?:[?#].*)?$/.exec(input.reference)?.[1];
|
||||
if (!number)
|
||||
return yield* new ForgejoCli.ForgejoCliError({
|
||||
command: "tea",
|
||||
cwd: input.cwd,
|
||||
detail: "Specify a pull request number or Forgejo pull request URL.",
|
||||
});
|
||||
return yield* request(
|
||||
{ ...input, path: `${repositoryPath(repo.repository)}/pulls/${number}` },
|
||||
ForgejoPullRequestSchema,
|
||||
);
|
||||
});
|
||||
return SourceControlProvider.SourceControlProvider.of({
|
||||
kind: "forgejo",
|
||||
listChangeRequests: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const repo = yield* cli.resolveRepository(input);
|
||||
const source = SourceControlProvider.sourceControlRefFromInput(input);
|
||||
const branch = SourceControlProvider.sourceBranch(input);
|
||||
const results: ReturnType<typeof toForgejoChangeRequest>[] = [];
|
||||
const limit = input.limit ?? 20;
|
||||
for (let page = 1; results.length < limit; page++) {
|
||||
const items = yield* request(
|
||||
{
|
||||
...input,
|
||||
path: `${repositoryPath(repo.repository)}/pulls?state=${input.state === "merged" ? "closed" : input.state}&sort=recentupdate&limit=50&page=${page}`,
|
||||
},
|
||||
Schema.Array(ForgejoPullRequestSchema),
|
||||
);
|
||||
for (const item of items) {
|
||||
if (
|
||||
item.head.ref !== branch ||
|
||||
(source?.repository && item.head.repo?.full_name !== source.repository) ||
|
||||
(source?.owner && item.head.repo?.owner.login !== source.owner)
|
||||
)
|
||||
continue;
|
||||
const normalized = toForgejoChangeRequest(item);
|
||||
if (input.state === "all" || normalized.state === input.state) results.push(normalized);
|
||||
}
|
||||
if (items.length === 0) break;
|
||||
}
|
||||
return results.slice(0, limit);
|
||||
}).pipe(mapError("listChangeRequests", input.cwd)),
|
||||
getChangeRequest: (input) =>
|
||||
getPull(input).pipe(
|
||||
Effect.map(toForgejoChangeRequest),
|
||||
mapError("getChangeRequest", input.cwd),
|
||||
),
|
||||
createChangeRequest: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const repo = yield* cli.resolveRepository(input);
|
||||
const source = SourceControlProvider.sourceControlRefFromInput(input);
|
||||
const owner = source?.owner ?? source?.repository?.split("/")[0];
|
||||
const head = SourceControlProvider.sourceBranch(input);
|
||||
yield* cli.api({
|
||||
...input,
|
||||
path: `${repositoryPath(input.target?.repository ?? repo.repository)}/pulls`,
|
||||
method: "POST",
|
||||
body: {
|
||||
base: input.target?.refName ?? input.baseRefName,
|
||||
head: owner ? `${owner}:${head}` : head,
|
||||
title: input.title,
|
||||
body: yield* fs.readFileString(input.bodyFile),
|
||||
},
|
||||
});
|
||||
}).pipe(mapError("createChangeRequest", input.cwd)),
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const repo = yield* cli.resolveRepository(input);
|
||||
return cloneUrls(
|
||||
yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema),
|
||||
);
|
||||
}).pipe(mapError("getRepositoryCloneUrls", input.cwd)),
|
||||
createRepository: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const repo = yield* cli.resolveRepository(input);
|
||||
const user = yield* request(
|
||||
{ ...input, path: "user" },
|
||||
Schema.Struct({ login: Schema.String }),
|
||||
);
|
||||
const [owner, name] = repo.repository.split("/");
|
||||
return cloneUrls(
|
||||
yield* request(
|
||||
{
|
||||
...input,
|
||||
path:
|
||||
owner === user.login
|
||||
? "user/repos"
|
||||
: `orgs/${encodeURIComponent(owner ?? "")}/repos`,
|
||||
method: "POST",
|
||||
body: { name, private: input.visibility === "private", auto_init: false },
|
||||
},
|
||||
RepositorySchema,
|
||||
),
|
||||
);
|
||||
}).pipe(mapError("createRepository", input.cwd)),
|
||||
getDefaultBranch: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const repo = yield* cli.resolveRepository(input);
|
||||
return (
|
||||
(yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema))
|
||||
.default_branch ?? null
|
||||
);
|
||||
}).pipe(mapError("getDefaultBranch", input.cwd)),
|
||||
checkoutChangeRequest: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const repo = yield* cli.resolveRepository(input);
|
||||
const pull = yield* getPull(input);
|
||||
if (repo.command === "fj") {
|
||||
// fj checkout cannot target a repository outside the local remotes.
|
||||
const urls = yield* request(
|
||||
{ ...input, path: repositoryPath(repo.repository) },
|
||||
RepositorySchema,
|
||||
);
|
||||
const remote = input.context?.remoteUrl;
|
||||
const useSsh = remote && ForgejoCli.parseForgejoRemote(remote)?.ssh;
|
||||
yield* process.run({
|
||||
operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
|
||||
command: "git",
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"fetch",
|
||||
"--",
|
||||
useSsh ? urls.ssh_url : urls.clone_url,
|
||||
`refs/pull/${pull.number}/head`,
|
||||
],
|
||||
});
|
||||
const branch = `pulls/${pull.number}`;
|
||||
const existing = yield* process.run({
|
||||
operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
|
||||
command: "git",
|
||||
cwd: input.cwd,
|
||||
args: ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`],
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
yield* process.run({
|
||||
operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
|
||||
command: "git",
|
||||
cwd: input.cwd,
|
||||
args:
|
||||
existing.exitCode === 0
|
||||
? ["checkout", branch]
|
||||
: ["checkout", "-b", branch, "FETCH_HEAD"],
|
||||
});
|
||||
} else
|
||||
yield* cli.execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"pulls",
|
||||
"checkout",
|
||||
"--login",
|
||||
repo.login,
|
||||
"--repo",
|
||||
repo.repository,
|
||||
"--branch",
|
||||
String(pull.number),
|
||||
],
|
||||
});
|
||||
if (input.force) {
|
||||
// tea leaves an existing PR branch at its old tip. Keep dirty files safe
|
||||
// while bringing the selected branch to the PR revision we fetched.
|
||||
yield* process.run({
|
||||
operation: "ForgejoSourceControlProvider.checkoutChangeRequest",
|
||||
command: "git",
|
||||
cwd: input.cwd,
|
||||
args: ["reset", "--keep", pull.head.sha],
|
||||
});
|
||||
}
|
||||
}).pipe(mapError("checkoutChangeRequest", input.cwd)),
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -19,7 +19,7 @@ import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as GitHubApi from "./GitHubApi.ts";
|
||||
import * as GitHubCredentials from "./GitHubCredentials.ts";
|
||||
import * as GitLabCli from "./GitLabCli.ts";
|
||||
import * as ForgejoCli from "./ForgejoCli.ts";
|
||||
import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
|
||||
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
|
||||
import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import * as AzureDevOpsSourceControlProvider from "./AzureDevOpsSourceControlPro
|
||||
import * as BitbucketSourceControlProvider from "./BitbucketSourceControlProvider.ts";
|
||||
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
|
||||
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
|
||||
import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts";
|
||||
import * as BuiltInDrivers from "./builtInDrivers.ts";
|
||||
import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
|
||||
import {
|
||||
probeSourceControlProvider,
|
||||
@@ -308,11 +308,18 @@ export const make = Effect.gen(function* () {
|
||||
const github = yield* GitHubSourceControlProvider.make;
|
||||
const githubDiscovery = yield* GitHubSourceControlProvider.makeDiscovery;
|
||||
const gitlab = yield* GitLabSourceControlProvider.make;
|
||||
const forgejo = yield* ForgejoSourceControlProvider.make;
|
||||
const forgejoDiscovery = yield* ForgejoSourceControlProvider.makeDiscovery;
|
||||
const bitbucket = yield* BitbucketSourceControlProvider.make;
|
||||
const bitbucketDiscovery = yield* BitbucketSourceControlProvider.makeDiscovery;
|
||||
const azureDevOps = yield* AzureDevOpsSourceControlProvider.make;
|
||||
const drivers = yield* Effect.forEach(BuiltInDrivers.BUILT_IN_SOURCE_CONTROL_DRIVERS, (driver) =>
|
||||
driver.make.pipe(
|
||||
Effect.map((instance): SourceControlProviderRegistration => ({
|
||||
kind: driver.kind,
|
||||
provider: instance.sourceControl,
|
||||
discovery: instance.discovery,
|
||||
})),
|
||||
),
|
||||
);
|
||||
return yield* makeWithProviders([
|
||||
{
|
||||
kind: "github",
|
||||
@@ -334,7 +341,7 @@ export const make = Effect.gen(function* () {
|
||||
provider: bitbucket,
|
||||
discovery: bitbucketDiscovery,
|
||||
},
|
||||
{ kind: "forgejo", provider: forgejo, discovery: forgejoDiscovery },
|
||||
...drivers,
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* The source control drivers this build ships with. Both registries, repository operations and
|
||||
* pull requests, iterate this list; a host with no driver here shows up as unsupported.
|
||||
*
|
||||
* Adding a host means writing its `@t3tools/source-control-<host>` package, adding its driver
|
||||
* here, and providing its services' layers in `layer` below.
|
||||
*
|
||||
* @module sourceControl/builtInDrivers
|
||||
*/
|
||||
import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
|
||||
import * as ForgejoDriver from "@t3tools/source-control-forgejo/server/driver";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
|
||||
|
||||
/** Ordered as the hosts appear in discovery, after the ones still built in the server. */
|
||||
export const BUILT_IN_SOURCE_CONTROL_DRIVERS = [ForgejoDriver.driver] as const;
|
||||
|
||||
/** The services the built-in drivers' packages own, plus the host port they all run against. */
|
||||
export const layer = ForgejoCli.layer.pipe(Layer.provideMerge(ServerSourceControlHost.layer));
|
||||
@@ -1,47 +0,0 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Option from "effect/Option";
|
||||
import type { ChangeRequest } from "@t3tools/contracts";
|
||||
|
||||
const Repository = Schema.Struct({
|
||||
full_name: Schema.String,
|
||||
owner: Schema.Struct({ login: Schema.String }),
|
||||
});
|
||||
const Branch = Schema.Struct({
|
||||
ref: Schema.String,
|
||||
sha: Schema.String,
|
||||
repo: Schema.NullOr(Repository),
|
||||
});
|
||||
export const ForgejoPullRequestSchema = Schema.Struct({
|
||||
number: Schema.Int,
|
||||
title: Schema.String,
|
||||
html_url: Schema.String,
|
||||
state: Schema.String,
|
||||
merged: Schema.Boolean,
|
||||
draft: Schema.optional(Schema.Boolean),
|
||||
base: Branch,
|
||||
head: Branch,
|
||||
closed_at: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
merged_at: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
updated_at: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
|
||||
});
|
||||
export function toForgejoChangeRequest(raw: typeof ForgejoPullRequestSchema.Type): ChangeRequest {
|
||||
return {
|
||||
provider: "forgejo",
|
||||
number: raw.number,
|
||||
title: raw.title,
|
||||
url: raw.html_url,
|
||||
state: raw.merged ? "merged" : raw.state === "closed" ? "closed" : "open",
|
||||
isDraft: raw.draft ?? /^(?:\[WIP\]|WIP:)/i.test(raw.title),
|
||||
baseRefName: raw.base.ref,
|
||||
headRefName: raw.head.ref,
|
||||
closedAt: raw.closed_at ?? null,
|
||||
mergedAt: raw.merged_at ?? null,
|
||||
updatedAt: raw.updated_at ?? Option.none(),
|
||||
isCrossRepository:
|
||||
raw.head.repo !== null &&
|
||||
raw.base.repo !== null &&
|
||||
raw.head.repo.full_name !== raw.base.repo.full_name,
|
||||
headRepositoryNameWithOwner: raw.head.repo?.full_name ?? null,
|
||||
headRepositoryOwnerLogin: raw.head.repo?.owner.login ?? null,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user