refactor: simplify .env generation and remove unnecessary escaping

- Remove escapeEnvValue function (no longer needed)
- Simplify generateEnvFile to write plain KEY=value format
- Remove quote-stripping from parseEnvFile
- Move helper functions back to module level for cleaner code
- Use DATABASE_PROTOCOLS in validateDatabaseUrl
This commit is contained in:
ZTatman 2026-04-12 18:13:16 -04:00
parent a4ee1d95dc
commit 099d521288
2 changed files with 67 additions and 79 deletions

View file

@ -5,12 +5,10 @@ import * as c from "yoctocolors";
import * as p from "@clack/prompts"; import * as p from "@clack/prompts";
import { generateSecret } from "../../utils/crypto.js"; import { generateSecret } from "../../utils/crypto.js";
import { generateEnvFile, DATABASE_PROTOCOLS } from "../../utils/config.js"; import { generateEnvFile } from "../../utils/config.js";
import { CommandConfig } from "../../cli-router.js"; import { CommandConfig } from "../../cli-router.js";
async function init(opts: { output?: string }) { function normalizeHttpUrl(value: string): string {
// Helper functions scoped to init
function normalizeHttpUrl(value: string): string {
const trimmed = value.trim(); const trimmed = value.trim();
const hasProtocol = /^[a-z]+:\/\//i.test(trimmed); const hasProtocol = /^[a-z]+:\/\//i.test(trimmed);
const isNotHttp = !/^https?:\/\//i.test(trimmed); const isNotHttp = !/^https?:\/\//i.test(trimmed);
@ -20,12 +18,12 @@ async function init(opts: { output?: string }) {
} }
return hasProtocol ? trimmed : `https://${trimmed}`; return hasProtocol ? trimmed : `https://${trimmed}`;
} }
function validateHttpUrlOrHost( function validateHttpUrlOrHost(
value: string | undefined, value: string | undefined,
label: string, label: string,
): string | undefined { ): string | undefined {
if (!value?.trim()) return `${label} is required`; if (!value?.trim()) return `${label} is required`;
try { try {
@ -39,16 +37,16 @@ async function init(opts: { output?: string }) {
} }
return undefined; return undefined;
} }
function validatePostgresUrl(value: string | undefined): string | undefined { function validatePostgresUrl(value: string | undefined): string | undefined {
if (!value?.trim()) { if (!value?.trim()) {
return "Database URL is required"; return "Database URL is required";
} }
try { try {
const url = new URL(value); const url = new URL(value);
if (!DATABASE_PROTOCOLS.includes(url.protocol as "postgres:" | "postgresql:")) { if (url.protocol !== "postgres:" && url.protocol !== "postgresql:") {
return "Database URL must start with postgres:// or postgresql://"; return "Database URL must start with postgres:// or postgresql://";
} }
} catch { } catch {
@ -56,19 +54,9 @@ async function init(opts: { output?: string }) {
} }
return undefined; return undefined;
} }
async function writePrivateFile(
filePath: string,
content: string,
): Promise<void> {
await fs.writeFile(filePath, content, {
encoding: "utf8",
flag: "wx",
mode: 0o600,
});
}
async function init(opts: { output?: string }) {
p.intro(c.bold("myst config init")); p.intro(c.bold("myst config init"));
p.note( p.note(
[ [
@ -92,6 +80,7 @@ async function init(opts: { output?: string }) {
const outDir = opts.output ? path.dirname(opts.output) : process.cwd(); const outDir = opts.output ? path.dirname(opts.output) : process.cwd();
const envPath = opts.output || path.join(outDir, ".env"); const envPath = opts.output || path.join(outDir, ".env");
// Check if .env file already exists
let envExists = false; let envExists = false;
try { try {
await fs.stat(envPath); await fs.stat(envPath);
@ -100,6 +89,7 @@ async function init(opts: { output?: string }) {
// .env file does not exist // .env file does not exist
} }
// Handle existing .env file
if (envExists) { if (envExists) {
while (true) { while (true) {
const choice = await p.select({ const choice = await p.select({
@ -209,7 +199,11 @@ async function init(opts: { output?: string }) {
publicUrl, publicUrl,
}); });
await writePrivateFile(envPath, envContent); await fs.writeFile(envPath, envContent, {
encoding: "utf8",
flag: "wx",
mode: 0o600,
});
s.stop(c.yellow(`.env created at ${envPath}`)); s.stop(c.yellow(`.env created at ${envPath}`));
p.note( p.note(

View file

@ -57,38 +57,32 @@ export function validateDatabaseUrl(url: string | undefined): boolean {
if (!url) return false; if (!url) return false;
try { try {
const parsed = new URL(url); const parsed = new URL(url);
return DATABASE_PROTOCOLS.includes(parsed.protocol as "postgres:" | "postgresql:"); return DATABASE_PROTOCOLS.includes(
parsed.protocol as "postgres:" | "postgresql:",
);
} catch { } catch {
return false; return false;
} }
} }
function escapeEnvValue(value: string): string {
return `"${value
.replace(/\\/g, "\\\\")
.replace(/"/g, '\\"')
.replace(/\r?\n/g, "\\n")
.replace(/\$/g, "\\$")}"`;
}
export function generateEnvFile(options: MystEnvironmentVariables): string { export function generateEnvFile(options: MystEnvironmentVariables): string {
const lines = [ const lines = [
`# Public URL used for share links.`, `# Public URL used for share links.`,
`${ENV_MAPPING.MYST_PUBLIC_URL}=${escapeEnvValue(options.publicUrl)}`, `MYST_PUBLIC_URL=${options.publicUrl}`,
``, ``,
`# Private operator URL for the admin UI. Protect this upstream.`, `# Private operator URL for the admin UI. Protect this upstream.`,
`${ENV_MAPPING.MYST_ADMIN_URL}=${escapeEnvValue(options.adminUrl)}`, `MYST_ADMIN_URL=${options.adminUrl}`,
``, ``,
`# Myst's own Postgres database.`, `# Myst's own Postgres database.`,
`${ENV_MAPPING.DATABASE_URL}=${escapeEnvValue(options.databaseUrl)}`, `DATABASE_URL=${options.databaseUrl}`,
``, ``,
`# Existing Forgejo instance and operator-created PAT for the dedicated Forgejo user.`, `# Existing Forgejo instance and operator-created PAT for the dedicated Forgejo user.`,
`${ENV_MAPPING.FORGEJO_BASE_URL}=${escapeEnvValue(options.forgejoBaseUrl)}`, `FORGEJO_BASE_URL=${options.forgejoBaseUrl}`,
`${ENV_MAPPING.FORGEJO_BOT_USERNAME}=${escapeEnvValue(options.forgejoBotUsername)}`, `FORGEJO_BOT_USERNAME=${options.forgejoBotUsername}`,
`${ENV_MAPPING.FORGEJO_PAT}=${escapeEnvValue(options.forgejoPat)}`, `FORGEJO_PAT=${options.forgejoPat}`,
``, ``,
`# Secret used to sign or derive grant tokens.`, `# Secret used to sign or derive grant tokens.`,
`${ENV_MAPPING.GRANT_TOKEN_SECRET}=${escapeEnvValue(options.grantTokenSecret)}`, `GRANT_TOKEN_SECRET=${options.grantTokenSecret}`,
]; ];
return lines.join("\n"); return lines.join("\n");