-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.ts
52 lines (45 loc) · 1.63 KB
/
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
41
42
43
44
45
46
47
48
49
50
51
52
import * as fs from 'fs';
import * as path from 'path';
import * as yaml from 'js-yaml';
import * as t from 'io-ts';
import { CONFIG_FILENAME } from './constants';
import { isLeft } from 'fp-ts/lib/Either';
import { Context } from './context';
import { ConfigError } from './errors';
const fsPromises = fs.promises;
const Target = t.type({
depends: t.array(t.string),
dependsExclude: t.union([t.array(t.string), t.undefined]),
output: t.string,
command: t.string,
});
export type Target = t.TypeOf<typeof Target>;
const Config = t.type({
targets: t.record(t.string, Target),
});
type Config = t.TypeOf<typeof Config>;
export const getTarget = (context: Context, config: Config): Target => {
const targetName = context.options.targetName;
if (typeof targetName === 'undefined') {
const firstTarget = Object.values(config.targets)[0];
if (typeof firstTarget === 'undefined') {
throw new ConfigError('No targets to default to');
}
return firstTarget;
}
const selectedTarget = config.targets[targetName];
if (typeof selectedTarget === 'undefined') {
throw new ConfigError(`Unknown target: ${targetName}`);
}
return selectedTarget;
};
export const loadConfig = async (context: Context): Promise<Config> => {
const configPath = path.join(context.dirpath, CONFIG_FILENAME);
const rawConfig = await fsPromises.readFile(configPath, 'utf8');
const unvalidatedConfig = yaml.safeLoad(rawConfig);
const isConfig = Config.decode(unvalidatedConfig);
if (isLeft(isConfig)) {
throw new ConfigError('Invalid config');
}
return isConfig.right;
};