UNPKG

@dotenc/cli

Version:

🔐 Secure, encrypted environment variables that live in your codebase

47 lines (46 loc) 2 kB
import { spawn } from "node:child_process"; import { existsSync } from "node:fs"; import fs from "node:fs/promises"; import path from "node:path"; import { decrypt } from "../helpers/crypto.js"; import { getKey } from "../helpers/key.js"; import { parseEnv } from "../helpers/parseEnv.js"; export const runCommand = async (command, args, options) => { // Get the environment const environmentArg = options.env || process.env.DOTENC_ENV; if (!environmentArg) { console.error('No environment provided. Use -e or set DOTENC_ENV to the environment you want to run the command in.\nTo start a new environment, use "dotenc init [environment]".'); return; } const environments = environmentArg.split(","); const decryptedEnvs = await Promise.all(environments.map(async (environment, index) => { const environmentFilePath = path.join(process.cwd(), `.env.${environment}.enc`); if (!existsSync(environmentFilePath)) { console.error(`Environment file not found: ${environmentFilePath}`); return; } const key = await getKey(environment, index); const content = await decrypt(key, environmentFilePath); const decryptedEnv = parseEnv(content); return decryptedEnv; })); const decryptedEnv = decryptedEnvs.reduce((acc, env) => { return { ...acc, ...env }; }, {}); // Get the local environment let localEnv = {}; const localEnvironmentFilePath = path.join(process.cwd(), ".env"); if (existsSync(localEnvironmentFilePath)) { const localEnvContent = await fs.readFile(localEnvironmentFilePath, "utf-8"); localEnv = parseEnv(localEnvContent); } // Merge the environment variables and run the command const mergedEnv = { ...process.env, ...decryptedEnv, ...localEnv }; const child = spawn(command, args, { env: mergedEnv, stdio: "inherit", }); child.on("exit", (code) => { process.exit(code); }); };