This repository has been archived by the owner on Apr 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 39
/
config.js
97 lines (89 loc) 路 2.65 KB
/
config.js
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
'use strict';
const chalk = require('chalk');
const cosmiconfig = require('cosmiconfig').cosmiconfigSync;
const debug = require('./debug');
const printDebug = debug.print;
const exitCodes = require('./exit-codes');
const knownProps = require('./config-properties');
const stripJsonComments = require('strip-json-comments');
const parseJson = require('parse-json');
const path = require('path');
function loadJson(filepath, content) {
try {
return parseJson(stripJsonComments(content));
} catch (err) {
err.message = `JSON Error in ${filepath}:\n${err.message}`;
throw err;
}
}
module.exports = {
/**
* Get JSON config.
*
* @param {string} file
* @returns {Object}
*/
get(file) {
const explorer = cosmiconfig('yaspeller', {
loaders: {
'.json': loadJson,
noExt: loadJson
},
searchPlaces: [
'package.json',
'.yaspellerrc',
'.yaspeller.json'
]
});
let data;
printDebug('Get/check config.');
try {
if (file) {
data = explorer.load(file).config;
} else {
const result = explorer.search();
if (result) {
file = result.filepath;
data = result.config;
}
}
if (file) {
printDebug(`Using config: ${file}`);
this.checkProps(data, file);
}
} catch (e) {
console.error(chalk.red(e));
process.exit(exitCodes.ERROR_CONFIG);
}
return {
relativePath: path.relative('./', file || '.yaspellerrc'),
data: data || {}
};
},
/**
* Check properties in config.
*
* @param {*} obj
* @param {string|undefined} file
*/
checkProps(obj, file) {
obj && Object.keys(obj).forEach(function(prop) {
if (knownProps[prop]) {
let needType = knownProps[prop].type;
let currentType = this._getType(obj[prop]);
if (currentType !== needType) {
console.error(chalk.red(
`The type for "${prop}" property should be ${knownProps[prop].type} in "${file}" config.`
));
}
} else {
console.error(chalk.red(
`Unknown "${prop}" property in "${file}" config.`
));
}
}, this);
},
_getType(value) {
return Array.isArray(value) ? 'array' : typeof value;
}
};