Repository navigation
Expand file tree
/
Copy pathget-config.js
More file actions
509 lines (434 loc) · 15.2 KB
/
Copy pathget-config.js
File metadata and controls
509 lines (434 loc) · 15.2 KB
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
'use strict';
const path = require('path');
const resolve = require('resolve');
const chalk = require('chalk');
const micromatch = require('micromatch');
const findUp = require('find-up');
const defaultRules = require('./rules');
const defaultConfigurations = require('./config');
const DEPRECATED_RULES = require('./helpers/deprecated-rules');
const KNOWN_ROOT_PROPERTIES = new Set([
'extends',
'rules',
'pending',
'ignore',
'plugins',
'overrides',
]);
const SUPPORTED_OVERRIDE_KEYS = new Set(['files', 'rules']);
// Severity level definitions
const IGNORE_SEVERITY = 0;
const WARNING_SEVERITY = 1;
const ERROR_SEVERITY = 2;
const CONFIG_FILE_NAME = '.template-lintrc.js';
const ALLOWED_ERROR_CODES = new Set([
// resolve package error codes
'MODULE_NOT_FOUND',
// Yarn PnP Error Code
'QUALIFIED_PATH_RESOLUTION_FAILED',
]);
function requirePlugin(pluginName, fromConfigPath) {
let basedir = fromConfigPath === undefined ? process.cwd() : path.dirname(fromConfigPath);
// throws exception if not found
let pluginPath = resolve.sync(pluginName, { basedir });
return require(pluginPath); // eslint-disable-line import/no-dynamic-require
}
function resolveProjectConfig(options) {
let configPath;
if (options.configPath) {
configPath = path.resolve(process.cwd(), options.configPath);
try {
// Making sure that the filePath exists, before requiring it directly this is
// needed in order to ensure that we only squelch module missing errors for
// the config path itself (and not other files that the config path may
// require itself)
require.resolve(configPath);
} catch (error) {
let isModuleMissingError = ALLOWED_ERROR_CODES.has(error.code);
if (!isModuleMissingError) {
throw error;
}
throw new Error(
`The configuration file specified (${options.configPath}) could not be found. Aborting.`
);
}
} else if (options.configPath === false) {
// we are explicitly using `--no-config-path` flag
return {};
} else {
configPath = findUp.sync(CONFIG_FILE_NAME);
if (configPath === undefined) {
// we weren't given an explicit --config-path argument, and we couldn't
// find a relative .template-lintrc.js file, just use the default "empty" config
return {};
}
}
options.resolvedConfigPath = configPath;
return require(configPath); // eslint-disable-line import/no-dynamic-require
}
function forEachPluginConfiguration(plugins, callback) {
if (!plugins) {
return;
}
for (let pluginName in plugins) {
let pluginConfigurations = plugins[pluginName].configurations;
if (!pluginConfigurations) {
continue;
}
for (let configurationName in pluginConfigurations) {
let configuration = pluginConfigurations[configurationName];
callback(configuration, configurationName, pluginName);
}
}
}
function normalizeExtends(config, options) {
let logger = options.console || console;
let extendedList = [];
if (config.extends) {
if (typeof config.extends === 'string') {
extendedList = [config.extends];
} else if (Array.isArray(config.extends)) {
extendedList = config.extends.slice();
} else {
logger.log(chalk.yellow('config.extends should be string or array '));
}
}
return extendedList;
}
function ensureRootProperties(config, source) {
config.rules = Object.assign({}, source.rules || {});
config.pending = (source.pending || []).slice();
config.overrides = (source.overrides || []).slice();
config.ignore = (source.ignore || []).slice();
config.extends = source.extends;
}
function migrateRulesFromRoot(config, source, options) {
let logger = options.console || console;
let invalidKeysFound = [];
for (let key in source) {
if (!KNOWN_ROOT_PROPERTIES.has(key)) {
invalidKeysFound.push(key);
config.rules[key] = source[key];
}
}
if (invalidKeysFound.length > 0) {
logger.log(
chalk.yellow(
`
Rule configuration has been moved into a \`rules\` property.
Please update your \`${CONFIG_FILE_NAME}\` file.
The following rules have been migrated to the \`rules\`
property: ${invalidKeysFound}.
`
)
);
}
}
function processPlugins(plugins = [], options, checkForCircularReference) {
let logger = options.console || console;
let pluginsHash = {};
for (let plugin of plugins) {
let pluginName;
if (typeof plugin === 'string') {
pluginName = plugin;
// the second argument here should actually be the config file path for
// the _currently being processed_ config file (not neccesarily the one
// specified to the bin script)
plugin = requirePlugin(pluginName, options.resolvedConfigPath);
}
let errorMessage;
if (typeof plugin === 'object') {
if (plugin.name) {
if (!checkForCircularReference || !checkForCircularReference[plugin.name]) {
pluginsHash[plugin.name] = plugin;
}
} else if (pluginName) {
errorMessage = `Plugin (${pluginName}) has not defined the plugin \`name\` property`;
} else {
errorMessage = 'Inline plugin object has not defined the plugin `name` property';
}
} else if (pluginName) {
errorMessage = `Plugin (${pluginName}) did not return a plain object`;
} else {
errorMessage = 'Inline plugin is not a plain object';
}
if (errorMessage) {
logger.log(chalk.yellow(errorMessage));
}
}
forEachPluginConfiguration(pluginsHash, (configuration) => {
// process plugins recursively
Object.assign(pluginsHash, processPlugins(configuration.plugins, options, pluginsHash));
});
return pluginsHash;
}
function processLoadedRules(config, options) {
let loadedRules;
if (config.loadedRules) {
loadedRules = config.loadedRules;
} else {
// load all the default rules in `ember-template-lint`
loadedRules = Object.assign({}, defaultRules);
}
// load plugin rules
for (let pluginName in config.plugins) {
let pluginRules = config.plugins[pluginName].rules;
if (pluginRules) {
loadedRules = Object.assign(loadedRules, pluginRules);
}
}
forEachPluginConfiguration(config.plugins, (configuration) => {
let plugins = processPlugins(configuration.plugins, options, config.plugins);
// process plugins recursively
processLoadedRules({ plugins, loadedRules });
});
return loadedRules;
}
function processLoadedConfigurations(config, options) {
let loadedConfigurations;
if (config.loadedConfigurations) {
loadedConfigurations = config.loadedConfigurations;
} else {
// load all the default configurations in `ember-template-lint`
loadedConfigurations = Object.assign({}, defaultConfigurations);
}
forEachPluginConfiguration(config.plugins, (configuration, configurationName, pluginName) => {
let name = `${pluginName}:${configurationName}`;
loadedConfigurations[name] = configuration;
// load plugins recursively
let plugins = processPlugins(configuration.plugins, options, config.plugins);
processLoadedConfigurations({ plugins, loadedConfigurations }, options);
});
return loadedConfigurations;
}
function processExtends(config, options) {
let logger = options.console || console;
let extendedList = normalizeExtends(config, options);
if (extendedList) {
for (const extendName of extendedList) {
let configuration = config.loadedConfigurations[extendName];
if (configuration) {
// ignore loops
if (!configuration.loadedConfigurations) {
configuration.loadedConfigurations = config.loadedConfigurations;
// continue chaining `extends` from plugins until done
processExtends(configuration, options);
delete configuration.loadedConfigurations;
if (configuration.rules) {
config.rules = Object.assign({}, configuration.rules, config.rules);
} else {
logger.log(chalk.yellow(`Missing rules for extends: ${extendName}`));
}
}
} else {
logger.log(chalk.yellow(`Cannot find configuration for extends: ${extendName}`));
}
delete config.extends;
}
}
}
function processIgnores(config) {
config.ignore = config.ignore.map((pattern) => micromatch.matcher(pattern));
}
/**
* we were passed a rule, add the rule being passed in, to the config.
* ex:
* rule:severity
* no-implicit-this:["error", { "allow": ["some-helper"] }]
*/
function getRuleFromString(rule) {
const indexOfSeparator = rule.indexOf(':') + 1;
// we have to split based on the index of the first instance of the separator because the separator could exist in the second half of the rule
const name = rule.substring(0, indexOfSeparator - 1); // eslint-disable-line unicorn/prefer-string-slice
let ruleConfig = rule.substring(indexOfSeparator); // eslint-disable-line unicorn/prefer-string-slice
if (ruleConfig.startsWith('[')) {
try {
ruleConfig = JSON.parse(ruleConfig);
} catch {
throw new Error(`Error parsing specified \`--rule\` config ${rule} as JSON.`);
}
}
const config = determineRuleConfig(ruleConfig);
return { name, config };
}
function validateRules(rules, loadedRules, options) {
let logger = options.console || console;
let invalidKeysFound = [];
let deprecatedNamesFound = [];
for (let key in rules) {
if (!loadedRules[key]) {
const deprecation = DEPRECATED_RULES.get(key);
if (deprecation) {
deprecatedNamesFound.push({ oldName: key, newName: deprecation });
rules[deprecation] = rules[key];
delete rules[key];
} else {
invalidKeysFound.push(key);
}
}
}
if (invalidKeysFound.length > 0) {
logger.log(chalk.yellow(`Invalid rule configuration found: ${invalidKeysFound}`));
}
if (deprecatedNamesFound.length > 0) {
logger.log(
chalk.yellow(`Deprecated rule names found: ${JSON.stringify(deprecatedNamesFound, null, 4)}`)
);
}
}
function validateOverrides(config, options) {
if (config.overrides) {
for (let overrideConfig of config.overrides) {
// If there are keys in the object which are not yet supported by overrides functionality, throw an error.
let overrideKeys = Object.keys(overrideConfig);
let containsValidKeys = overrideKeys.every((item) => SUPPORTED_OVERRIDE_KEYS.has(item));
if (!containsValidKeys) {
throw new Error(
'Using `overrides` in `.template-lintrc.js` only supports `files` and `rules` sections. Please update your configuration.'
);
}
validateRules(overrideConfig.rules, config.loadedRules, options);
overrideConfig.rules = processRules(overrideConfig);
}
}
}
function _determineConfigForSeverity(config) {
switch (config) {
case 'off':
return { config: false, severity: IGNORE_SEVERITY };
case 'warn':
return { config: true, severity: WARNING_SEVERITY };
case 'error':
return { config: true, severity: ERROR_SEVERITY };
}
}
function statusForModule(type, config, options) {
let moduleId = options.moduleId;
let list = config[type];
let configPath = options.configPath || '';
if (!list) {
return false;
}
for (const item of list) {
let fullPathModuleId = path.resolve(process.cwd(), moduleId);
if (typeof item === 'function' && item(moduleId)) {
return true;
} else if (typeof item === 'string') {
let fullPathItem = path.resolve(process.cwd(), path.dirname(configPath), item);
if (fullPathModuleId === fullPathItem) {
return true;
}
} else if (item.moduleId) {
let fullPathItem = path.resolve(process.cwd(), path.dirname(configPath), item.moduleId);
if (fullPathModuleId === fullPathItem) {
return item;
}
}
}
return false;
}
/**
* Returns the config in conjunction with overrides configuration.
* @param {*} config
* @param {*} filePath
*/
function getConfigForFile(config, options) {
let filePath = options.filePath;
let configuredRules = config.rules;
let overrides = config.overrides;
let fileConfig = Object.assign({}, config, {
pendingStatus: statusForModule('pending', config, options),
shouldIgnore: statusForModule('ignore', config, options),
});
if (filePath && overrides) {
let overridesRules = {};
overrides.forEach((override) => {
const isFileMatch = override.files && micromatch.isMatch(filePath, override.files);
if (isFileMatch) {
overridesRules = Object.assign(overridesRules, override.rules);
}
});
// If there is an override present, then the overridden ruleset takes precedence.
fileConfig.rules = Object.assign({}, configuredRules, overridesRules);
}
return fileConfig;
}
function determineRuleConfig(ruleData) {
let ruleConfig = {
severity: ruleData === false ? IGNORE_SEVERITY : ERROR_SEVERITY,
config: ruleData,
};
let severityConfig;
// In case of {'no-implicit-this': 'off|warn|error'}
if (typeof ruleData === 'string') {
severityConfig = _determineConfigForSeverity(ruleData);
if (severityConfig) {
ruleConfig = severityConfig;
}
} else if (Array.isArray(ruleData)) {
// array of severity and custom rule config
let severity = ruleData[0];
severityConfig = _determineConfigForSeverity(severity);
if (severityConfig) {
ruleConfig.severity = severityConfig.severity;
ruleConfig.config = ruleData[1];
}
}
return ruleConfig;
}
/**
* Sets the severity and config on the rule object.
* Eg:
* {'no-implicit-this': 'warn'} -> {'no-implicit-this': { severity: 'warn', config: true }}
* { 'no-implicit-this': [ 'warn', { allow: [ 'fooData' ] } ] }
* would become:
* { 'no-implicit-this': { severity: 'warn', config: 'allow': [ 'fooData' ] } }
* {
* 'some-rule': 'lol', // -> { severity: 2, config: 'lol' }
* 'other-thing': ['wat', 'is', 'this'], // { severity: 2, config: ['wat', 'is', 'this'] }
* 'hmm-thing-here': { zomg: 'lol' }, // -> { severity: 2, config: { zomg: 'lol' } }
* 'another-thing-there': 'off', // -> { severity: 0, config: false }
* }
* @param {*} configData
*/
function processRules(config) {
let processedRules = Object.assign({}, config.rules);
for (let key in processedRules) {
let ruleData = processedRules[key];
processedRules[key] = determineRuleConfig(ruleData);
}
return processedRules;
}
function getProjectConfig(options) {
let source = options.config || resolveProjectConfig(options);
let config;
if (source._processed) {
config = source;
} else {
// don't mutate a `require`d object, you'll have a bad time
config = {};
ensureRootProperties(config, source);
migrateRulesFromRoot(config, source, options);
config.plugins = processPlugins(source.plugins, options);
config.loadedRules = processLoadedRules(config, options);
config.loadedConfigurations = processLoadedConfigurations(config, options);
processExtends(config, options);
processIgnores(config);
validateRules(config.rules, config.loadedRules, options);
validateOverrides(config, options);
config.rules = processRules(config);
config._processed = true;
}
return config;
}
module.exports = {
ERROR_SEVERITY,
IGNORE_SEVERITY,
WARNING_SEVERITY,
getConfigForFile,
getProjectConfig,
getRuleFromString,
resolveProjectConfig,
determineRuleConfig,
processRules,
};