forked from deprecate/metal-soy-critic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.ts
109 lines (86 loc) · 2.44 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import * as chalk from 'chalk';
import * as fs from 'fs';
import * as path from 'path';
import * as process from 'process';
const CONFIG_FILE_NAMES = [
'.soycriticrc',
'.soycriticrc.json',
];
export interface CallToImportConfig {
regex: string
replace: string
}
export interface ImplicitParamsMap {
[nameOrRegex: string]: string | Array<string>
}
export interface Config {
callToImport: Array<CallToImportConfig>
implicitParams: ImplicitParamsMap
}
export const DEFAULT_CONFIG: Config = {
callToImport: [{regex: '(.*)',replace: '{$1}'}],
implicitParams: {}
};
export function validateConfig(config: Config): Config {
if (!Array.isArray(config.callToImport)) {
throw new Error('callToImport is not a valid config array.');
}
for (const item of config.callToImport) {
if (!isRegex(item.regex)) {
throw new Error(`callToImport.regex "${item.regex}" is not a valid RegExp.`);
}
if (!isRegex(item.replace)) {
throw new Error(`callToImport.replace "${item.replace}" is not a valid replace string.`);
}
}
for (const key in config.implicitParams) {
if (!isRegex(key)) {
throw new Error(`"${key}" is not a valid RegExp.`);
}
}
return config;
}
export function convertConfig(config: any): Config {
if (config.callToImportRegex && config.callToImportReplace) {
config.callToImport = [
{
regex: config.callToImportRegex,
replace: config.callToImportReplace
}
];
console.log(chalk.yellow('CONFIG API HAS CHANGED, PLEASE UPDATE\n'));
console.log('\tYour callToImport configuration is outdated, update it to new API.\n');
}
return config;
}
export function readConfig(): Config {
const filePath = getConfigFilePath();
let config = {};
if (filePath) {
const buffer = fs.readFileSync(filePath);
config = JSON.parse(buffer.toString('utf8'));
}
config = convertConfig(config);
return validateConfig({...DEFAULT_CONFIG, ...config});
}
export function getConfigFilePath(): string | null {
let currentPath = process.cwd();
while (currentPath !== '/') {
for (const fileName of CONFIG_FILE_NAMES) {
const nextPath = path.join(currentPath, '/', fileName);
if (fs.existsSync(nextPath)) {
return nextPath;
}
}
currentPath = path.dirname(currentPath);
}
return null;
}
export function isRegex(regex: string): boolean {
try {
new RegExp(regex);
} catch(e) {
return false;
}
return true;
}