/
Config.js
88 lines (73 loc) · 2.71 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
const debug = require('debug')('npm-package-json-lint:Config');
const cosmiconfig = require('cosmiconfig');
const configValidator = require('./config/ConfigValidator');
const cosmicConfigTransformer = require('./config/cosmicConfigTransformer');
const applyExtendsIfSpecified = require('./config/applyExtendsIfSpecified');
const applyOverrides = require('./config/applyOverrides');
const noRules = 0;
/**
* Config class
* @class
*/
class Config {
/**
* Constructor
*
* @param {string} cwd The current working directory.
* @param {Object} config The user passed config object.
* @param {string} configFile The user passed configFile path.
* @param {string} configBaseDirectory The base directory that config should be pulled from.
* @param {Object} rules Rules object
*/
constructor(cwd, config, configFile, configBaseDirectory, rules) {
if (config) {
this.config = applyExtendsIfSpecified(config, 'PassedConfig');
}
this.cwd = cwd;
this.configFile = configFile;
this.configBaseDirectory = configBaseDirectory;
this.rules = rules;
this.explorer = cosmiconfig('npmpackagejsonlint', {
transform: cosmicConfigTransformer.transform(cwd, configBaseDirectory)
});
}
/**
* Gets the config for a file.
*
* @param {string} filePath File path of the file being linted.
* @returns {Object} A config object.
* @memberof Config
*/
getConfigForFile(filePath) {
debug(`Getting config for ${filePath}`);
const filePathToSearch = filePath;
debug(`filePathToSearch: ${filePathToSearch}`);
let config;
if (typeof this.config === 'undefined') {
debug(`User passed config is undefined.`);
if (this.configFile) {
debug(`Config file specified, loading it.`);
config = this.explorer.loadSync(this.configFile);
} else {
debug(`Config file wasn't specified, searching for config.`);
config = this.explorer.searchSync(filePathToSearch);
}
} else {
debug(`User passed config is set, using it.`);
const configBeforeOverrides = this.config;
debug(`Applying overrides to config for ${filePath}`);
config = applyOverrides(this.cwd, filePath, configBeforeOverrides.rules, configBeforeOverrides.overrides);
debug(`Overrides applied for ${filePath}`);
}
if (!config) {
throw new Error(`No npm-package-json-lint configuration found.\n${filePathToSearch}`);
}
if (Object.keys(config).length === noRules) {
throw new Error(`No rules specified in configuration.\n${filePathToSearch}`);
}
debug(`Overrides applied for ${filePath}`);
configValidator.validateRules(config, 'cli', this.rules);
return config;
}
}
module.exports = Config;