/
get-config.ts
55 lines (46 loc) · 1.33 KB
/
get-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
53
54
55
import merge from 'merge';
import { ConfigOpts } from '@src/types';
import { cosmiconfigSync as configSync } from 'cosmiconfig';
import { readFileSync } from 'fs';
import { safeLoad } from 'js-yaml';
import { LintOpts } from 'sass-lint';
const defaultSearchPlaces = (moduleName: string) => [
'package.json',
`.${moduleName}rc`,
`.${moduleName}.json`,
`.${moduleName}.yaml`,
`.${moduleName}.yml`,
`${moduleName}.config.js`,
];
export function loadDefaults(): ConfigOpts {
// @ts-ignore
return safeLoad(
readFileSync(require.resolve('../config/default.yml'), {
encoding: 'utf8',
}),
);
}
export enum CONFIG_TYPE {
SASS_LINT = 'sass_lint',
SASS_LINT_AUTO_FIX = 'sass_lint_auto_fix',
}
export type ConfigType<T> = T extends CONFIG_TYPE.SASS_LINT
? LintOpts
: T extends CONFIG_TYPE.SASS_LINT_AUTO_FIX
? ConfigOpts
: any;
export function getConfig<T extends CONFIG_TYPE>(
moduleName: T,
filepath?: string,
): ConfigType<T> {
const explorer = configSync(moduleName, {
searchPlaces: defaultSearchPlaces(moduleName),
});
const resolvedConfig = filepath ? explorer.load(filepath) : explorer.search();
if (resolvedConfig) {
return resolvedConfig.config;
}
return {} as any;
}
export const mergeConfig = <A, B>(baseConfig: A, extendedConfig: B) =>
merge.recursive(true, baseConfig, extendedConfig);