mirror of
https://github.com/ZTatman/myst.git
synced 2026-11-21 04:17:59 +00:00
refactor(cli): simplify verify, improve error messages, use env var names
- Use ENV_MAPPING from config.ts instead of inline object - Display env var names (SNAKE_CASE) not internal keys - Remove 'set' verbiage from display output - Improve forgejo-checks error messages with actionable descriptions - Fix tsconfig composites causing build issues
This commit is contained in:
parent
8a716964bb
commit
4c99fe71fa
4 changed files with 174 additions and 157 deletions
|
|
@ -3,13 +3,7 @@ import path from "node:path";
|
|||
import * as c from "yoctocolors";
|
||||
import * as p from "@clack/prompts";
|
||||
|
||||
import {
|
||||
ENV_MAPPING,
|
||||
MystEnvironmentVariables,
|
||||
parseEnvFile,
|
||||
validateDatabaseUrl,
|
||||
REQUIRED_KEYS,
|
||||
} from "../utils/config.js";
|
||||
import { ENV_MAPPING, parseEnvFile, REQUIRED_KEYS } from "../utils/config.js";
|
||||
import {
|
||||
checkForgejoReachability,
|
||||
checkForgejoApiAuthentication,
|
||||
|
|
@ -32,16 +26,20 @@ async function verifyCommand(opts: VerifyOptions): Promise<void> {
|
|||
p.intro(c.bold("myst config verify"));
|
||||
|
||||
const config = loadConfig();
|
||||
const results: CheckResult[] = collectResults(config);
|
||||
if (!config) {
|
||||
return;
|
||||
}
|
||||
|
||||
const missing = getMissingKeys(config);
|
||||
|
||||
if (isDiagnostic) {
|
||||
await displayDiagnosticResults(results, config);
|
||||
await runDiagnosticMode(config, missing);
|
||||
} else {
|
||||
await verifyResults(results, config);
|
||||
await runVerifyMode(config, missing);
|
||||
}
|
||||
}
|
||||
|
||||
function loadConfig(): Partial<MystEnvironmentVariables> {
|
||||
function loadConfig(): Record<string, string> | null {
|
||||
const envPath = path.join(process.cwd(), ".env");
|
||||
|
||||
try {
|
||||
|
|
@ -51,60 +49,125 @@ function loadConfig(): Partial<MystEnvironmentVariables> {
|
|||
if (err.code === "ENOENT") {
|
||||
p.cancel(`${c.red("Error:")} .env file not found in ${process.cwd()}`);
|
||||
process.exitCode = 1;
|
||||
return null;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function collectResults(
|
||||
config: Partial<MystEnvironmentVariables>,
|
||||
): CheckResult[] {
|
||||
const results: CheckResult[] = [];
|
||||
|
||||
function addResult(name: string, success: boolean, message?: string) {
|
||||
results.push({ name, success, ...(message !== undefined && { message }) });
|
||||
}
|
||||
|
||||
function getMissingKeys(config: Record<string, string>): string[] {
|
||||
const missing: string[] = [];
|
||||
for (const key of REQUIRED_KEYS) {
|
||||
if (!config[key]) {
|
||||
missing.push(key.replace(/(?<=[a-z])(?=[A-Z])/g, "_").toUpperCase());
|
||||
}
|
||||
}
|
||||
|
||||
if (missing.length > 0) {
|
||||
addResult("Required config", false, `Missing: ${missing.join(", ")}`);
|
||||
}
|
||||
|
||||
for (const [, configKey] of Object.entries(ENV_MAPPING)) {
|
||||
const value = config[configKey];
|
||||
addResult(`${configKey} set`, !!value, value ? "configured" : "missing");
|
||||
}
|
||||
|
||||
if (config.databaseUrl) {
|
||||
const isDbValid = validateDatabaseUrl(config.databaseUrl);
|
||||
addResult("Database URL format", isDbValid, isDbValid ? "valid" : "invalid");
|
||||
}
|
||||
|
||||
const isForgejoConfigured =
|
||||
config.forgejoBaseUrl && config.forgejoPat && config.forgejoBotUsername;
|
||||
|
||||
if (isForgejoConfigured) {
|
||||
addResult("Forgejo configured", true);
|
||||
}
|
||||
|
||||
return results;
|
||||
return missing;
|
||||
}
|
||||
|
||||
async function runForgejoChecks(config: Partial<MystEnvironmentVariables>): Promise<CheckResult[]> {
|
||||
async function runDiagnosticMode(
|
||||
config: Record<string, string>,
|
||||
missing: string[],
|
||||
): Promise<void> {
|
||||
const results: CheckResult[] = [];
|
||||
|
||||
if (missing.length > 0) {
|
||||
results.push({
|
||||
name: "Required config",
|
||||
success: false,
|
||||
message: `Missing: ${missing.join(", ")}`,
|
||||
});
|
||||
}
|
||||
|
||||
for (const [envKey, configKey] of Object.entries(ENV_MAPPING)) {
|
||||
const value = config[configKey];
|
||||
results.push({
|
||||
name: envKey,
|
||||
success: !!value,
|
||||
message: value ? "configured" : "missing",
|
||||
});
|
||||
}
|
||||
|
||||
const forgejoResults = await runForgejoChecks(config);
|
||||
const allResults = [...results, ...forgejoResults];
|
||||
|
||||
const lines = allResults.map((r) => {
|
||||
const icon = r.success ? c.green("✓") : c.red("✗");
|
||||
const msg = r.message ? ` ${r.message}` : "";
|
||||
return `${icon} ${r.name}${msg}`;
|
||||
});
|
||||
|
||||
p.note(lines.join("\n"), c.yellow("Results"));
|
||||
|
||||
const failures = allResults.filter((r) => !r.success);
|
||||
if (failures.length > 0) {
|
||||
p.outro(c.red(`${failures.length} issue(s) found`));
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
p.outro(c.green("All checks passed"));
|
||||
}
|
||||
|
||||
async function runVerifyMode(
|
||||
config: Record<string, string>,
|
||||
missing: string[],
|
||||
): Promise<void> {
|
||||
if (missing.length > 0) {
|
||||
p.cancel(
|
||||
`${c.red("Error:")} Missing required env variables: ${missing.join(", ")}`,
|
||||
);
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
const s = p.spinner();
|
||||
s.start("Verifying Forgejo configuration");
|
||||
|
||||
const forgejoResults = await runForgejoChecks(config);
|
||||
|
||||
const firstFailure = forgejoResults.find((r) => !r.success);
|
||||
if (firstFailure) {
|
||||
s.stop(firstFailure.message);
|
||||
p.cancel(`${c.red("✗")} ${firstFailure.name}: ${firstFailure.message}`);
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
if (forgejoResults.length === 0) {
|
||||
s.stop("No Forgejo configuration");
|
||||
p.cancel(`${c.red("Error:")} Forgejo not configured`);
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
s.stop("Verification complete");
|
||||
|
||||
const [reachability, auth, repoAccess] = forgejoResults;
|
||||
|
||||
p.note(
|
||||
[
|
||||
`${c.green("✓")} ${reachability.name}`,
|
||||
`${c.green("✓")} ${auth.name}: ${auth.message}`,
|
||||
`${c.green(repoAccess.success ? "✓" : "✗")} ${repoAccess.name}: ${repoAccess.message}`,
|
||||
].join("\n"),
|
||||
c.yellow("Results"),
|
||||
);
|
||||
|
||||
p.outro(c.green("Verification passed"));
|
||||
}
|
||||
|
||||
async function runForgejoChecks(
|
||||
config: Record<string, string>,
|
||||
): Promise<CheckResult[]> {
|
||||
const { forgejoBaseUrl, forgejoPat, forgejoBotUsername } = config;
|
||||
|
||||
if (!forgejoBaseUrl || !forgejoPat || !forgejoBotUsername) {
|
||||
return results;
|
||||
return [];
|
||||
}
|
||||
|
||||
const results: CheckResult[] = [];
|
||||
|
||||
const reachability = await checkForgejoReachability(forgejoBaseUrl);
|
||||
results.push(reachability);
|
||||
|
||||
|
|
@ -129,95 +192,13 @@ async function runForgejoChecks(config: Partial<MystEnvironmentVariables>): Prom
|
|||
return results;
|
||||
}
|
||||
|
||||
async function displayDiagnosticResults(
|
||||
results: CheckResult[],
|
||||
config: Partial<MystEnvironmentVariables>,
|
||||
): Promise<void> {
|
||||
const forgejoResults = await runForgejoChecks(config);
|
||||
const allResults = [...results, ...forgejoResults];
|
||||
|
||||
const lines = allResults.map((r) => {
|
||||
const icon = r.success ? c.green("✓") : c.red("✗");
|
||||
const msg = r.message ? ` ${r.message}` : "";
|
||||
return `${icon} ${r.name}${msg}`;
|
||||
});
|
||||
|
||||
p.note(lines.join("\n"), c.yellow("Results"));
|
||||
|
||||
const failures = allResults.filter((r) => !r.success);
|
||||
|
||||
if (failures.length > 0) {
|
||||
p.outro(c.red(`${failures.length} issue(s) found`));
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
p.outro(c.green("All checks passed"));
|
||||
}
|
||||
|
||||
async function verifyResults(
|
||||
results: CheckResult[],
|
||||
config: Partial<MystEnvironmentVariables>,
|
||||
): Promise<void> {
|
||||
const failures = results.filter((r) => !r.success);
|
||||
|
||||
if (failures.length > 0) {
|
||||
const msg = failures[0]?.message ?? "Unknown error";
|
||||
p.cancel(`${c.red("Error:")} ${msg}`);
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
const s = p.spinner();
|
||||
s.start("Verifying Forgejo configuration");
|
||||
|
||||
const forgejoResults = await runForgejoChecks(config);
|
||||
|
||||
const firstFailure = forgejoResults.find((r) => !r.success);
|
||||
|
||||
if (firstFailure) {
|
||||
s.stop(firstFailure.message);
|
||||
p.cancel(`${c.red("✗")} ${firstFailure.name}: ${firstFailure.message}`);
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
if (forgejoResults.length === 0) {
|
||||
s.stop("No Forgejo configuration");
|
||||
p.cancel(`${c.red("Error:")} Forgejo not configured`);
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
if (forgejoResults.length < 3) {
|
||||
s.stop("Incomplete Forgejo checks");
|
||||
p.cancel(`${c.red("Error:")} Could not complete all Forgejo checks`);
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
s.stop("Verification complete");
|
||||
|
||||
const reachability = forgejoResults[0]!;
|
||||
const auth = forgejoResults[1]!;
|
||||
const repoAccess = forgejoResults[2]!;
|
||||
|
||||
p.note(
|
||||
[
|
||||
`${c.green("✓")} ${reachability.name}`,
|
||||
`${c.green("✓")} ${auth.name}: ${auth.message}`,
|
||||
`${c.green(repoAccess.success ? "✓" : "✗")} ${repoAccess.name}: ${repoAccess.message}`,
|
||||
].join("\n"),
|
||||
c.yellow("Results"),
|
||||
);
|
||||
|
||||
p.outro(c.green("Verification passed"));
|
||||
}
|
||||
|
||||
export const commandConfig: CommandConfig = {
|
||||
description: "Verify Myst configuration and connection to Forgejo",
|
||||
options: {
|
||||
diagnostic: { type: "boolean", description: "Show diagnostic information for all checks" },
|
||||
diagnostic: {
|
||||
type: "boolean",
|
||||
description: "Show diagnostic information for all checks",
|
||||
},
|
||||
},
|
||||
handler: verifyCommand,
|
||||
};
|
||||
};
|
||||
|
|
|
|||
|
|
@ -25,29 +25,47 @@ async function fetchWithTimeout(
|
|||
return fetch(url, { ...init, signal: AbortSignal.timeout(TIMEOUT) });
|
||||
}
|
||||
|
||||
function getErrorMessage(error: unknown, context: string): string {
|
||||
if (error instanceof Error) {
|
||||
if (error.name === "TimeoutError") {
|
||||
return `${context}: connection timed out`;
|
||||
}
|
||||
if (error.message.includes("ECONNREFUSED")) {
|
||||
return `${context}: connection refused`;
|
||||
}
|
||||
if (error.message.includes("ENOTFOUND") || error.message.includes("getaddrinfo")) {
|
||||
return `${context}: host not found`;
|
||||
}
|
||||
return `${context}: ${error.message}`;
|
||||
}
|
||||
return `${context}: unknown error`;
|
||||
}
|
||||
|
||||
export async function checkForgejoReachability(
|
||||
baseUrl: string,
|
||||
): Promise<CheckResult> {
|
||||
try {
|
||||
const response = await fetchWithTimeout(baseUrl, { method: "GET" });
|
||||
if (response.ok) {
|
||||
return createCheckResult("Forgejo reachability", true);
|
||||
return createCheckResult("Forgejo reachability", true, "connected");
|
||||
}
|
||||
return createCheckResult(
|
||||
"Forgejo reachability",
|
||||
false,
|
||||
`HTTP ${response.status}`,
|
||||
`server returned ${response.status} ${response.statusText}`,
|
||||
);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
return createCheckResult("Forgejo reachability", false, message);
|
||||
return createCheckResult(
|
||||
"Forgejo reachability",
|
||||
false,
|
||||
getErrorMessage(error, "cannot reach server"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function checkForgejoApiAuthentication(
|
||||
baseUrl: string,
|
||||
pat: string,
|
||||
colorize = false,
|
||||
): Promise<CheckResult> {
|
||||
try {
|
||||
const response = await fetchWithTimeout(`${baseUrl}/api/v1/user`, {
|
||||
|
|
@ -61,7 +79,15 @@ export async function checkForgejoApiAuthentication(
|
|||
return createCheckResult(
|
||||
"Forgejo API token",
|
||||
false,
|
||||
"Invalid or expired token",
|
||||
"token is invalid or expired",
|
||||
);
|
||||
}
|
||||
|
||||
if (response.status === 403) {
|
||||
return createCheckResult(
|
||||
"Forgejo API token",
|
||||
false,
|
||||
"token lacks sufficient permissions",
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -69,24 +95,22 @@ export async function checkForgejoApiAuthentication(
|
|||
return createCheckResult(
|
||||
"Forgejo API token",
|
||||
false,
|
||||
`HTTP ${response.status}`,
|
||||
`server returned ${response.status}`,
|
||||
);
|
||||
}
|
||||
|
||||
const user = (await response.json()) as { login: string };
|
||||
let login = user.login;
|
||||
if (colorize) {
|
||||
const { default: c } = await import("yoctocolors");
|
||||
login = c.green(user.login);
|
||||
}
|
||||
return createCheckResult(
|
||||
"Forgejo API token",
|
||||
true,
|
||||
`Authenticated as ${login}`,
|
||||
`authenticated as ${user.login}`,
|
||||
);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
return createCheckResult("Forgejo API token", false, message);
|
||||
return createCheckResult(
|
||||
"Forgejo API token",
|
||||
false,
|
||||
getErrorMessage(error, "cannot connect to API"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -106,8 +130,20 @@ export async function checkRepoAccess(
|
|||
},
|
||||
);
|
||||
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
return createCheckResult(
|
||||
"Repo access",
|
||||
false,
|
||||
"token lacks permission to list repositories",
|
||||
);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
return createCheckResult("Repo access", false, `HTTP ${response.status}`);
|
||||
return createCheckResult(
|
||||
"Repo access",
|
||||
false,
|
||||
`server returned ${response.status}`,
|
||||
);
|
||||
}
|
||||
|
||||
const repos = (await response.json()) as { name: string }[];
|
||||
|
|
@ -115,17 +151,20 @@ export async function checkRepoAccess(
|
|||
return createCheckResult(
|
||||
"Repo access",
|
||||
true,
|
||||
`Found ${repos.length} repo(s)`,
|
||||
`found ${repos.length} repository`,
|
||||
);
|
||||
}
|
||||
|
||||
return createCheckResult(
|
||||
"Repo access",
|
||||
false,
|
||||
"No repos found (service account may not have repo access)",
|
||||
"no repositories found for user",
|
||||
);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
return createCheckResult("Repo access", false, message);
|
||||
return createCheckResult(
|
||||
"Repo access",
|
||||
false,
|
||||
getErrorMessage(error, "cannot list repositories"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,9 @@
|
|||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"rootDir": "src",
|
||||
"outDir": "dist",
|
||||
"outDir": "dist"
|
||||
},
|
||||
"references": [{ "path": "../shared" }],
|
||||
"include": ["src/**/*.ts"],
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,8 +9,6 @@
|
|||
"@myst/shared": ["packages/shared/src/index.ts"]
|
||||
},
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"exactOptionalPropertyTypes": true,
|
||||
"skipLibCheck": true,
|
||||
"declaration": true,
|
||||
"sourceMap": true,
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue