fix(tooling): harden database env loading
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
@@ -7,10 +7,34 @@ function resolveWorkspaceRoot() {
|
||||
return resolve(currentDir, "../../../");
|
||||
}
|
||||
|
||||
export function loadWorkspaceEnv() {
|
||||
const envPath = resolve(resolveWorkspaceRoot(), ".env");
|
||||
export function resolveWorkspaceEnvPaths(options: { workspaceRoot?: string; nodeEnv?: string | undefined } = {}) {
|
||||
const workspaceRoot = options.workspaceRoot ?? resolveWorkspaceRoot();
|
||||
const nodeEnv = options.nodeEnv ?? process.env.NODE_ENV;
|
||||
const candidates = [".env"];
|
||||
|
||||
if (nodeEnv) {
|
||||
candidates.push(`.env.${nodeEnv}`);
|
||||
}
|
||||
|
||||
candidates.push(".env.local");
|
||||
|
||||
if (nodeEnv) {
|
||||
candidates.push(`.env.${nodeEnv}.local`);
|
||||
}
|
||||
|
||||
return [...new Set(candidates.map((candidate) => resolve(workspaceRoot, candidate)))];
|
||||
}
|
||||
|
||||
export function loadWorkspaceEnv(options: { workspaceRoot?: string; nodeEnv?: string | undefined } = {}) {
|
||||
const envPaths = resolveWorkspaceEnvPaths(options);
|
||||
const originalKeys = new Set(Object.keys(process.env));
|
||||
const loadedPaths: string[] = [];
|
||||
|
||||
for (const envPath of envPaths) {
|
||||
if (!existsSync(envPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const contents = readFileSync(envPath, "utf8");
|
||||
|
||||
for (const rawLine of contents.split(/\r?\n/u)) {
|
||||
@@ -31,13 +55,15 @@ export function loadWorkspaceEnv() {
|
||||
(rawValue.startsWith("'") && rawValue.endsWith("'"));
|
||||
const value = quoted ? rawValue.slice(1, -1) : rawValue;
|
||||
|
||||
if (process.env[key] == null) {
|
||||
if (!originalKeys.has(key)) {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Leave environment untouched when .env is not present in the workspace.
|
||||
|
||||
loadedPaths.push(envPath);
|
||||
}
|
||||
|
||||
return loadedPaths;
|
||||
}
|
||||
|
||||
export function resolveWorkspacePath(...segments: string[]) {
|
||||
|
||||
Reference in New Issue
Block a user