-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathloadEnv.ts
More file actions
61 lines (52 loc) · 1.54 KB
/
loadEnv.ts
File metadata and controls
61 lines (52 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import path from "path";
import fs from "fs";
import dotenv from "dotenv";
import { resolveChainPath } from "./pathResolver";
export type LoadEnvOptions = {
envPath?: string;
envVars?: Record<string, string>;
env: string;
};
export function loadEnvironmentVariables(options: LoadEnvOptions) {
const cwd = process.cwd();
const env =
options.envPath ??
path.join(
resolveChainPath(),
`./src/core/environments/${options.env}/.env`
);
const envPath = path.isAbsolute(env) ? env : path.join(cwd, env);
if (fs.existsSync(envPath)) {
dotenv.config({ path: envPath });
console.log(`Loaded environment from ${envPath}`);
} else {
console.warn(`.env file not found at ${envPath}`);
}
if (options?.envVars !== undefined) {
Object.entries(options.envVars).forEach(([key, value]) => {
process.env[key] = value;
});
console.log(
`Loaded ${Object.keys(options.envVars).length} environment variables from arguments`
);
}
}
export function getRequiredEnv(key: string): string {
const value = process.env[key];
if (value === undefined) {
throw new Error(
`Required environment variable "${key}" is not defined. Please check your .env file or pass it as an argument.`
);
}
return value;
}
export function parseEnvArgs(args: string[]): Record<string, string> {
const envVars: Record<string, string> = {};
for (const arg of args) {
if (arg.includes("=")) {
const [key, value] = arg.split("=", 2);
envVars[key.trim()] = value.trim();
}
}
return envVars;
}