import assert from 'node:assert/strict'; import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; import test from 'node:test'; import { replaceEnvFile, setEnvValues } from './env-file.mjs'; test('sets values where they stand, exported or not, without duplicates, and appends new ones', () => { const source = '# Local settings\nexport WF_WEB_HOST=127.0.0.1\nDATABASE_URL=postgres://keep\nWF_WEB_HOST=::1\n'; assert.equal( setEnvValues(source, { WF_WEB_HOST: '0.0.0.0', WF_WEB_PORT: '3000' }), '# Local settings\nWF_WEB_HOST=0.0.0.0\nDATABASE_URL=postgres://keep\nWF_WEB_PORT=3000\n', ); assert.throws(() => setEnvValues('', { WF_TOKEN: 'one\nWF_DEV_AUTH_TOKEN=two' }), /single-line/); }); test('replaces the file whole, or leaves it as it was when it changed meanwhile', async t => { const directory = await mkdtemp(path.join(os.tmpdir(), 'wishforge-env-')); t.after(() => rm(directory, { recursive: true, force: true })); const file = path.join(directory, '.env.local'); await writeFile(file, 'A=1\n', { mode: 0o600 }); await replaceEnvFile(file, 'A=1\n', 'A=2\n'); assert.equal(await readFile(file, 'utf8'), 'A=2\n'); await assert.rejects(replaceEnvFile(file, 'A=1\n', 'A=3\n'), /changed while it was being updated/); assert.equal(await readFile(file, 'utf8'), 'A=2\n'); // No temporary copy of the secrets is left behind. assert.deepEqual(await readdir(directory), ['.env.local']); });