forked from jawj/zapatos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate-schema.ts
executable file
·51 lines (43 loc) · 1.58 KB
/
generate-schema.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
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env node
// ^^ this shebang is for the compiled JS file, not the TS source
/*
Zapatos: https://jawj.github.io/zapatos/
Copyright (C) 2020 George MacKerron
Released under the MIT licence: see LICENCE file
*/
import * as fs from 'fs';
import { generate } from "./generate";
import type { Config } from './generate/config';
const recursivelyInterpolateEnvVars = (obj: any): any =>
typeof obj === 'string' ?
obj.replace(/\{\{\s*([^}\s]+)\s*\}\}/g, (_0, name) => {
const e = process.env[name];
if (e === undefined) throw new Error(`Environment variable '${name}' is not set`);
return e;
}) :
Array.isArray(obj) ?
obj.map(item => recursivelyInterpolateEnvVars(item)) :
typeof obj === 'object' ?
Object.keys(obj).reduce<any>((memo, key) => {
memo[key] = recursivelyInterpolateEnvVars(obj[key]);
return memo;
}, {}) : obj;
void (async () => {
const
configFile = 'zapatosconfig.json',
configJSON = fs.existsSync(configFile) ? fs.readFileSync(configFile, { encoding: 'utf8' }) : '{}',
argsJSON = process.argv[2] ?? '{}';
let fileConfig;
try {
fileConfig = recursivelyInterpolateEnvVars(JSON.parse(configJSON));
} catch (err) {
throw new Error(`If present, zapatosconfig.ts must be a valid JSON file: ${err.message}`);
}
let argsConfig;
try {
argsConfig = recursivelyInterpolateEnvVars(JSON.parse(argsJSON));
} catch (err) {
throw new Error(`If present, the argument to Zapatos must be valid JSON: ${err.message}`);
}
await generate({ ...fileConfig, ...argsConfig } as Config);
})();