import { randomUUID } from 'node:crypto'; import { lstat, open, readFile, rename, rm } from 'node:fs/promises'; import path from 'node:path'; /** * Sets values in the text of a .env file: an existing assignment, with or without `export`, is * replaced where it stands and its duplicates dropped; a new one is appended. */ export function setEnvValues(source, values) { const lines = source.split('\n'); if (lines.at(-1) === '') lines.pop(); for (const [key, value] of Object.entries(values)) { if (!/^[A-Z_][A-Z0-9_]*$/.test(key) || /[\r\n]/.test(String(value))) throw new Error(`Cannot write ${key} as a single-line setting`); const assigns = new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=`); const first = lines.findIndex(line => assigns.test(line)); if (first < 0) lines.push(`${key}=${value}`); else { lines[first] = `${key}=${value}`; for (let index = lines.length - 1; index > first; index--) if (assigns.test(lines[index])) lines.splice(index, 1); } } return `${lines.join('\n')}\n`; } /** * Replaces a private .env file whole or not at all: the new text goes to a temporary file beside * it (named like `.env.*.local`, which Git ignores) that then takes its place, unless the file * changed meanwhile. A crash leaves either the old file or the new one, never half of either. */ export async function replaceEnvFile(file, expected, next) { const temporary = path.join(path.dirname(file), `.env.update-${randomUUID()}.local`); const handle = await open(temporary, 'wx', 0o600); try { await handle.writeFile(next); await handle.sync(); } finally { await handle.close(); } try { const latest = await lstat(file); if (!latest.isFile() || (await readFile(file, 'utf8')) !== expected) throw new Error(`${file} changed while it was being updated; it was left as it was.`); await rename(temporary, file); } finally { await rm(temporary, { force: true }); } }