UNPKG

15 kBJavaScriptView Raw
1/**
2 * @fileoverview Config file operations. This file must be usable in the browser,
3 * so no Node-specific code can be here.
4 * @author Nicholas C. Zakas
5 */
6"use strict";
7
8//------------------------------------------------------------------------------
9// Requirements
10//------------------------------------------------------------------------------
11
12const minimatch = require("minimatch"),
13 path = require("path");
14
15const debug = require("debug")("eslint:config-ops");
16
17//------------------------------------------------------------------------------
18// Private
19//------------------------------------------------------------------------------
20
21const RULE_SEVERITY_STRINGS = ["off", "warn", "error"],
22 RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => {
23 map[value] = index;
24 return map;
25 }, {}),
26 VALID_SEVERITIES = [0, 1, 2, "off", "warn", "error"];
27
28//------------------------------------------------------------------------------
29// Public Interface
30//------------------------------------------------------------------------------
31
32module.exports = {
33
34 /**
35 * Creates an empty configuration object suitable for merging as a base.
36 * @returns {Object} A configuration object.
37 */
38 createEmptyConfig() {
39 return {
40 globals: {},
41 env: {},
42 rules: {},
43 parserOptions: {}
44 };
45 },
46
47 /**
48 * Creates an environment config based on the specified environments.
49 * @param {Object<string,boolean>} env The environment settings.
50 * @param {Environments} envContext The environment context.
51 * @returns {Object} A configuration object with the appropriate rules and globals
52 * set.
53 */
54 createEnvironmentConfig(env, envContext) {
55
56 const envConfig = this.createEmptyConfig();
57
58 if (env) {
59
60 envConfig.env = env;
61
62 Object.keys(env).filter(name => env[name]).forEach(name => {
63 const environment = envContext.get(name);
64
65 if (environment) {
66 debug(`Creating config for environment ${name}`);
67 if (environment.globals) {
68 Object.assign(envConfig.globals, environment.globals);
69 }
70
71 if (environment.parserOptions) {
72 Object.assign(envConfig.parserOptions, environment.parserOptions);
73 }
74 }
75 });
76 }
77
78 return envConfig;
79 },
80
81 /**
82 * Given a config with environment settings, applies the globals and
83 * ecmaFeatures to the configuration and returns the result.
84 * @param {Object} config The configuration information.
85 * @param {Environments} envContent env context.
86 * @returns {Object} The updated configuration information.
87 */
88 applyEnvironments(config, envContent) {
89 if (config.env && typeof config.env === "object") {
90 debug("Apply environment settings to config");
91 return this.merge(this.createEnvironmentConfig(config.env, envContent), config);
92 }
93
94 return config;
95 },
96
97 /**
98 * Merges two config objects. This will not only add missing keys, but will also modify values to match.
99 * @param {Object} target config object
100 * @param {Object} src config object. Overrides in this config object will take priority over base.
101 * @param {boolean} [combine] Whether to combine arrays or not
102 * @param {boolean} [isRule] Whether its a rule
103 * @returns {Object} merged config object.
104 */
105 merge: function deepmerge(target, src, combine, isRule) {
106
107 /*
108 * The MIT License (MIT)
109 *
110 * Copyright (c) 2012 Nicholas Fisher
111 *
112 * Permission is hereby granted, free of charge, to any person obtaining a copy
113 * of this software and associated documentation files (the "Software"), to deal
114 * in the Software without restriction, including without limitation the rights
115 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
116 * copies of the Software, and to permit persons to whom the Software is
117 * furnished to do so, subject to the following conditions:
118 *
119 * The above copyright notice and this permission notice shall be included in
120 * all copies or substantial portions of the Software.
121 *
122 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
123 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
124 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
125 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
126 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
127 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
128 * THE SOFTWARE.
129 */
130
131 /*
132 * This code is taken from deepmerge repo
133 * (https://github.com/KyleAMathews/deepmerge)
134 * and modified to meet our needs.
135 */
136 const array = Array.isArray(src) || Array.isArray(target);
137 let dst = array && [] || {};
138
139 if (array) {
140 const resolvedTarget = target || [];
141
142 // src could be a string, so check for array
143 if (isRule && Array.isArray(src) && src.length > 1) {
144 dst = dst.concat(src);
145 } else {
146 dst = dst.concat(resolvedTarget);
147 }
148 const resolvedSrc = typeof src === "object" ? src : [src];
149
150 Object.keys(resolvedSrc).forEach((_, i) => {
151 const e = resolvedSrc[i];
152
153 if (typeof dst[i] === "undefined") {
154 dst[i] = e;
155 } else if (typeof e === "object") {
156 if (isRule) {
157 dst[i] = e;
158 } else {
159 dst[i] = deepmerge(resolvedTarget[i], e, combine, isRule);
160 }
161 } else {
162 if (!combine) {
163 dst[i] = e;
164 } else {
165 if (dst.indexOf(e) === -1) {
166 dst.push(e);
167 }
168 }
169 }
170 });
171 } else {
172 if (target && typeof target === "object") {
173 Object.keys(target).forEach(key => {
174 dst[key] = target[key];
175 });
176 }
177 Object.keys(src).forEach(key => {
178 if (key === "overrides") {
179 dst[key] = (target[key] || []).concat(src[key] || []);
180 } else if (Array.isArray(src[key]) || Array.isArray(target[key])) {
181 dst[key] = deepmerge(target[key], src[key], key === "plugins" || key === "extends", isRule);
182 } else if (typeof src[key] !== "object" || !src[key] || key === "exported" || key === "astGlobals") {
183 dst[key] = src[key];
184 } else {
185 dst[key] = deepmerge(target[key] || {}, src[key], combine, key === "rules");
186 }
187 });
188 }
189
190 return dst;
191 },
192
193 /**
194 * Normalizes the severity value of a rule's configuration to a number
195 * @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally
196 * received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0),
197 * the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array
198 * whose first element is one of the above values. Strings are matched case-insensitively.
199 * @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0.
200 */
201 getRuleSeverity(ruleConfig) {
202 const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
203
204 if (severityValue === 0 || severityValue === 1 || severityValue === 2) {
205 return severityValue;
206 }
207
208 if (typeof severityValue === "string") {
209 return RULE_SEVERITY[severityValue.toLowerCase()] || 0;
210 }
211
212 return 0;
213 },
214
215 /**
216 * Converts old-style severity settings (0, 1, 2) into new-style
217 * severity settings (off, warn, error) for all rules. Assumption is that severity
218 * values have already been validated as correct.
219 * @param {Object} config The config object to normalize.
220 * @returns {void}
221 */
222 normalizeToStrings(config) {
223
224 if (config.rules) {
225 Object.keys(config.rules).forEach(ruleId => {
226 const ruleConfig = config.rules[ruleId];
227
228 if (typeof ruleConfig === "number") {
229 config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0];
230 } else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === "number") {
231 ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0];
232 }
233 });
234 }
235 },
236
237 /**
238 * Determines if the severity for the given rule configuration represents an error.
239 * @param {int|string|Array} ruleConfig The configuration for an individual rule.
240 * @returns {boolean} True if the rule represents an error, false if not.
241 */
242 isErrorSeverity(ruleConfig) {
243
244 let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
245
246 if (typeof severity === "string") {
247 severity = RULE_SEVERITY[severity.toLowerCase()] || 0;
248 }
249
250 return (typeof severity === "number" && severity === 2);
251 },
252
253 /**
254 * Checks whether a given config has valid severity or not.
255 * @param {number|string|Array} ruleConfig - The configuration for an individual rule.
256 * @returns {boolean} `true` if the configuration has valid severity.
257 */
258 isValidSeverity(ruleConfig) {
259 let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
260
261 if (typeof severity === "string") {
262 severity = severity.toLowerCase();
263 }
264 return VALID_SEVERITIES.indexOf(severity) !== -1;
265 },
266
267 /**
268 * Checks whether every rule of a given config has valid severity or not.
269 * @param {Object} config - The configuration for rules.
270 * @returns {boolean} `true` if the configuration has valid severity.
271 */
272 isEverySeverityValid(config) {
273 return Object.keys(config).every(ruleId => this.isValidSeverity(config[ruleId]));
274 },
275
276 /**
277 * Merges all configurations in a given config vector. A vector is an array of objects, each containing a config
278 * file path and a list of subconfig indices that match the current file path. All config data is assumed to be
279 * cached.
280 * @param {Array<Object>} vector list of config files and their subconfig indices that match the current file path
281 * @param {Object} configCache the config cache
282 * @returns {Object} config object
283 */
284 getConfigFromVector(vector, configCache) {
285
286 const cachedConfig = configCache.getMergedVectorConfig(vector);
287
288 if (cachedConfig) {
289 return cachedConfig;
290 }
291
292 debug("Using config from partial cache");
293
294 const subvector = Array.from(vector);
295 let nearestCacheIndex = subvector.length - 1,
296 partialCachedConfig;
297
298 while (nearestCacheIndex >= 0) {
299 partialCachedConfig = configCache.getMergedVectorConfig(subvector);
300 if (partialCachedConfig) {
301 break;
302 }
303 subvector.pop();
304 nearestCacheIndex--;
305 }
306
307 if (!partialCachedConfig) {
308 partialCachedConfig = {};
309 }
310
311 let finalConfig = partialCachedConfig;
312
313 // Start from entry immediately following nearest cached config (first uncached entry)
314 for (let i = nearestCacheIndex + 1; i < vector.length; i++) {
315 finalConfig = this.mergeVectorEntry(finalConfig, vector[i], configCache);
316 configCache.setMergedVectorConfig(vector.slice(0, i + 1), finalConfig);
317 }
318
319 return finalConfig;
320 },
321
322 /**
323 * Merges the config options from a single vector entry into the supplied config.
324 * @param {Object} config the base config to merge the vector entry's options into
325 * @param {Object} vectorEntry a single entry from a vector, consisting of a config file path and an array of
326 * matching override indices
327 * @param {Object} configCache the config cache
328 * @returns {Object} merged config object
329 */
330 mergeVectorEntry(config, vectorEntry, configCache) {
331 const vectorEntryConfig = Object.assign({}, configCache.getConfig(vectorEntry.filePath));
332 let mergedConfig = Object.assign({}, config),
333 overrides;
334
335 if (vectorEntryConfig.overrides) {
336 overrides = vectorEntryConfig.overrides.filter(
337 (override, overrideIndex) => vectorEntry.matchingOverrides.indexOf(overrideIndex) !== -1
338 );
339 } else {
340 overrides = [];
341 }
342
343 mergedConfig = this.merge(mergedConfig, vectorEntryConfig);
344
345 delete mergedConfig.overrides;
346
347 mergedConfig = overrides.reduce((lastConfig, override) => this.merge(lastConfig, override), mergedConfig);
348
349 if (mergedConfig.filePath) {
350 delete mergedConfig.filePath;
351 delete mergedConfig.baseDirectory;
352 } else if (mergedConfig.files) {
353 delete mergedConfig.files;
354 }
355
356 return mergedConfig;
357 },
358
359 /**
360 * Checks that the specified file path matches all of the supplied glob patterns.
361 * @param {string} filePath The file path to test patterns against
362 * @param {string|string[]} patterns One or more glob patterns, of which at least one should match the file path
363 * @param {string|string[]} [excludedPatterns] One or more glob patterns, of which none should match the file path
364 * @returns {boolean} True if all the supplied patterns match the file path, false otherwise
365 */
366 pathMatchesGlobs(filePath, patterns, excludedPatterns) {
367 const patternList = [].concat(patterns);
368 const excludedPatternList = [].concat(excludedPatterns || []);
369
370 patternList.concat(excludedPatternList).forEach(pattern => {
371 if (path.isAbsolute(pattern) || pattern.includes("..")) {
372 throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);
373 }
374 });
375
376 const opts = { matchBase: true };
377
378 return patternList.some(pattern => minimatch(filePath, pattern, opts)) &&
379 !excludedPatternList.some(excludedPattern => minimatch(filePath, excludedPattern, opts));
380 }
381};