UNPKG

2.05 kBJavaScriptView Raw
1'use strict';
2
3const chalk = require('chalk');
4const cosmiconfig = require('cosmiconfig');
5const debug = require('./debug');
6const printDebug = debug.print;
7const exitCodes = require('./exit-codes');
8const knownProps = require('./config-properties');
9
10module.exports = {
11 /**
12 * Get JSON config.
13 *
14 * @param {string} file
15 * @returns {Object}
16 */
17 get(file) {
18 const explorer = cosmiconfig('yaspeller', {
19 searchPlaces: [
20 'package.json',
21 '.yaspellerrc',
22 '.yaspeller.json'
23 ]
24 });
25 let data;
26
27 printDebug('Get/check config.');
28
29 try {
30 if (file) {
31 data = explorer.loadSync(file).config;
32 } else {
33 const { config, filepath } = explorer.searchSync();
34 file = filepath;
35 data = config;
36 }
37
38 printDebug(`Using config: ${file}`);
39
40 this.checkProps(data, file);
41 } catch (e) {
42 console.error(chalk.red(e));
43 process.exit(exitCodes.ERROR_CONFIG);
44 }
45
46 return data || {};
47 },
48 /**
49 * Check properties in config.
50 *
51 * @param {*} obj
52 * @param {string|undefined} file
53 */
54 checkProps(obj, file) {
55 obj && Object.keys(obj).forEach(function(prop) {
56 if (knownProps[prop]) {
57 let needType = knownProps[prop].type;
58 let currentType = this._getType(obj[prop]);
59 if (currentType !== needType) {
60 console.error(chalk.red(
61 `The type for "${prop}" property should be ${knownProps[prop].type} in "${file}" config.`
62 ));
63 }
64 } else {
65 console.error(chalk.red(
66 `Unknown "${prop}" property in "${file}" config.`
67 ));
68 }
69 }, this);
70 },
71 _getType(value) {
72 return Array.isArray(value) ? 'array' : typeof value;
73 }
74};