-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse-config.ts
40 lines (31 loc) · 1004 Bytes
/
parse-config.ts
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
import fs from "fs";
import YAML from "yaml";
import { InvalidConfigError, validateConfig } from "./validate-config";
import { Config } from "./config.types";
export const parseEnv = (value: string): string => {
if (!process.env[value]) {
throw new InvalidConfigError(`Environment variable "${value}" not found.`);
}
return process.env[value]!;
};
export const parseConfig = (filePath: string): Config => {
const extensions = [".yml", ".yaml"];
let finalPath;
for (const ext of extensions) {
const pathWithExt = filePath.endsWith(ext) ? filePath : `${filePath}${ext}`;
if (fs.existsSync(pathWithExt)) {
finalPath = pathWithExt;
break;
}
}
if (!finalPath) {
throw new Error(
`Config file "${filePath}" not found with .yml or .yaml extension.`,
);
}
const file = fs
.readFileSync(finalPath, "utf8")
.replace(/\$\{(.+?)\}/g, (_, value) => parseEnv(value));
const config = YAML.parse(file);
return validateConfig(config);
};