]> git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/cli-engine/cli-engine.js
import eslint 7.28.0
[pve-eslint.git] / eslint / lib / cli-engine / cli-engine.js
1 /**
2 * @fileoverview Main CLI object.
3 * @author Nicholas C. Zakas
4 */
5
6 "use strict";
7
8 /*
9 * The CLI object should *not* call process.exit() directly. It should only return
10 * exit codes. This allows other programs to use the CLI object and still control
11 * when the program exits.
12 */
13
14 //------------------------------------------------------------------------------
15 // Requirements
16 //------------------------------------------------------------------------------
17
18 const fs = require("fs");
19 const path = require("path");
20 const defaultOptions = require("../../conf/default-cli-options");
21 const pkg = require("../../package.json");
22
23
24 const {
25 Legacy: {
26 ConfigOps,
27 naming,
28 CascadingConfigArrayFactory,
29 IgnorePattern,
30 getUsedExtractedConfigs,
31 ModuleResolver
32 }
33 } = require("@eslint/eslintrc");
34
35 const { FileEnumerator } = require("./file-enumerator");
36
37 const { Linter } = require("../linter");
38 const builtInRules = require("../rules");
39 const loadRules = require("./load-rules");
40 const hash = require("./hash");
41 const LintResultCache = require("./lint-result-cache");
42
43 const debug = require("debug")("eslint:cli-engine");
44 const validFixTypes = new Set(["problem", "suggestion", "layout"]);
45
46 //------------------------------------------------------------------------------
47 // Typedefs
48 //------------------------------------------------------------------------------
49
50 // For VSCode IntelliSense
51 /** @typedef {import("../shared/types").ConfigData} ConfigData */
52 /** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */
53 /** @typedef {import("../shared/types").LintMessage} LintMessage */
54 /** @typedef {import("../shared/types").ParserOptions} ParserOptions */
55 /** @typedef {import("../shared/types").Plugin} Plugin */
56 /** @typedef {import("../shared/types").RuleConf} RuleConf */
57 /** @typedef {import("../shared/types").Rule} Rule */
58 /** @typedef {ReturnType<CascadingConfigArrayFactory["getConfigArrayForFile"]>} ConfigArray */
59 /** @typedef {ReturnType<ConfigArray["extractConfig"]>} ExtractedConfig */
60
61 /**
62 * The options to configure a CLI engine with.
63 * @typedef {Object} CLIEngineOptions
64 * @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments.
65 * @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this CLIEngine instance
66 * @property {boolean} [cache] Enable result caching.
67 * @property {string} [cacheLocation] The cache file to use instead of .eslintcache.
68 * @property {string} [configFile] The configuration file to use.
69 * @property {string} [cwd] The value to use for the current working directory.
70 * @property {string[]} [envs] An array of environments to load.
71 * @property {string[]|null} [extensions] An array of file extensions to check.
72 * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean.
73 * @property {string[]} [fixTypes] Array of rule types to apply fixes for.
74 * @property {string[]} [globals] An array of global variables to declare.
75 * @property {boolean} [ignore] False disables use of .eslintignore.
76 * @property {string} [ignorePath] The ignore file to use instead of .eslintignore.
77 * @property {string|string[]} [ignorePattern] One or more glob patterns to ignore.
78 * @property {boolean} [useEslintrc] False disables looking for .eslintrc
79 * @property {string} [parser] The name of the parser to use.
80 * @property {ParserOptions} [parserOptions] An object of parserOption settings to use.
81 * @property {string[]} [plugins] An array of plugins to load.
82 * @property {Record<string,RuleConf>} [rules] An object of rules to use.
83 * @property {string[]} [rulePaths] An array of directories to load custom rules from.
84 * @property {boolean} [reportUnusedDisableDirectives] `true` adds reports for unused eslint-disable directives
85 * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file.
86 * @property {string} [resolvePluginsRelativeTo] The folder where plugins should be resolved from, defaulting to the CWD
87 */
88
89 /**
90 * A linting result.
91 * @typedef {Object} LintResult
92 * @property {string} filePath The path to the file that was linted.
93 * @property {LintMessage[]} messages All of the messages for the result.
94 * @property {number} errorCount Number of errors for the result.
95 * @property {number} warningCount Number of warnings for the result.
96 * @property {number} fixableErrorCount Number of fixable errors for the result.
97 * @property {number} fixableWarningCount Number of fixable warnings for the result.
98 * @property {string} [source] The source code of the file that was linted.
99 * @property {string} [output] The source code of the file that was linted, with as many fixes applied as possible.
100 */
101
102 /**
103 * Linting results.
104 * @typedef {Object} LintReport
105 * @property {LintResult[]} results All of the result.
106 * @property {number} errorCount Number of errors for the result.
107 * @property {number} warningCount Number of warnings for the result.
108 * @property {number} fixableErrorCount Number of fixable errors for the result.
109 * @property {number} fixableWarningCount Number of fixable warnings for the result.
110 * @property {DeprecatedRuleInfo[]} usedDeprecatedRules The list of used deprecated rules.
111 */
112
113 /**
114 * Private data for CLIEngine.
115 * @typedef {Object} CLIEngineInternalSlots
116 * @property {Map<string, Plugin>} additionalPluginPool The map for additional plugins.
117 * @property {string} cacheFilePath The path to the cache of lint results.
118 * @property {CascadingConfigArrayFactory} configArrayFactory The factory of configs.
119 * @property {(filePath: string) => boolean} defaultIgnores The default predicate function to check if a file ignored or not.
120 * @property {FileEnumerator} fileEnumerator The file enumerator.
121 * @property {ConfigArray[]} lastConfigArrays The list of config arrays that the last `executeOnFiles` or `executeOnText` used.
122 * @property {LintResultCache|null} lintResultCache The cache of lint results.
123 * @property {Linter} linter The linter instance which has loaded rules.
124 * @property {CLIEngineOptions} options The normalized options of this instance.
125 */
126
127 //------------------------------------------------------------------------------
128 // Helpers
129 //------------------------------------------------------------------------------
130
131 /** @type {WeakMap<CLIEngine, CLIEngineInternalSlots>} */
132 const internalSlotsMap = new WeakMap();
133
134 /**
135 * Determines if each fix type in an array is supported by ESLint and throws
136 * an error if not.
137 * @param {string[]} fixTypes An array of fix types to check.
138 * @returns {void}
139 * @throws {Error} If an invalid fix type is found.
140 */
141 function validateFixTypes(fixTypes) {
142 for (const fixType of fixTypes) {
143 if (!validFixTypes.has(fixType)) {
144 throw new Error(`Invalid fix type "${fixType}" found.`);
145 }
146 }
147 }
148
149 /**
150 * It will calculate the error and warning count for collection of messages per file
151 * @param {LintMessage[]} messages Collection of messages
152 * @returns {Object} Contains the stats
153 * @private
154 */
155 function calculateStatsPerFile(messages) {
156 return messages.reduce((stat, message) => {
157 if (message.fatal || message.severity === 2) {
158 stat.errorCount++;
159 if (message.fix) {
160 stat.fixableErrorCount++;
161 }
162 } else {
163 stat.warningCount++;
164 if (message.fix) {
165 stat.fixableWarningCount++;
166 }
167 }
168 return stat;
169 }, {
170 errorCount: 0,
171 warningCount: 0,
172 fixableErrorCount: 0,
173 fixableWarningCount: 0
174 });
175 }
176
177 /**
178 * It will calculate the error and warning count for collection of results from all files
179 * @param {LintResult[]} results Collection of messages from all the files
180 * @returns {Object} Contains the stats
181 * @private
182 */
183 function calculateStatsPerRun(results) {
184 return results.reduce((stat, result) => {
185 stat.errorCount += result.errorCount;
186 stat.warningCount += result.warningCount;
187 stat.fixableErrorCount += result.fixableErrorCount;
188 stat.fixableWarningCount += result.fixableWarningCount;
189 return stat;
190 }, {
191 errorCount: 0,
192 warningCount: 0,
193 fixableErrorCount: 0,
194 fixableWarningCount: 0
195 });
196 }
197
198 /**
199 * Processes an source code using ESLint.
200 * @param {Object} config The config object.
201 * @param {string} config.text The source code to verify.
202 * @param {string} config.cwd The path to the current working directory.
203 * @param {string|undefined} config.filePath The path to the file of `text`. If this is undefined, it uses `<text>`.
204 * @param {ConfigArray} config.config The config.
205 * @param {boolean} config.fix If `true` then it does fix.
206 * @param {boolean} config.allowInlineConfig If `true` then it uses directive comments.
207 * @param {boolean} config.reportUnusedDisableDirectives If `true` then it reports unused `eslint-disable` comments.
208 * @param {FileEnumerator} config.fileEnumerator The file enumerator to check if a path is a target or not.
209 * @param {Linter} config.linter The linter instance to verify.
210 * @returns {LintResult} The result of linting.
211 * @private
212 */
213 function verifyText({
214 text,
215 cwd,
216 filePath: providedFilePath,
217 config,
218 fix,
219 allowInlineConfig,
220 reportUnusedDisableDirectives,
221 fileEnumerator,
222 linter
223 }) {
224 const filePath = providedFilePath || "<text>";
225
226 debug(`Lint ${filePath}`);
227
228 /*
229 * Verify.
230 * `config.extractConfig(filePath)` requires an absolute path, but `linter`
231 * doesn't know CWD, so it gives `linter` an absolute path always.
232 */
233 const filePathToVerify = filePath === "<text>" ? path.join(cwd, filePath) : filePath;
234 const { fixed, messages, output } = linter.verifyAndFix(
235 text,
236 config,
237 {
238 allowInlineConfig,
239 filename: filePathToVerify,
240 fix,
241 reportUnusedDisableDirectives,
242
243 /**
244 * Check if the linter should adopt a given code block or not.
245 * @param {string} blockFilename The virtual filename of a code block.
246 * @returns {boolean} `true` if the linter should adopt the code block.
247 */
248 filterCodeBlock(blockFilename) {
249 return fileEnumerator.isTargetPath(blockFilename);
250 }
251 }
252 );
253
254 // Tweak and return.
255 const result = {
256 filePath,
257 messages,
258 ...calculateStatsPerFile(messages)
259 };
260
261 if (fixed) {
262 result.output = output;
263 }
264 if (
265 result.errorCount + result.warningCount > 0 &&
266 typeof result.output === "undefined"
267 ) {
268 result.source = text;
269 }
270
271 return result;
272 }
273
274 /**
275 * Returns result with warning by ignore settings
276 * @param {string} filePath File path of checked code
277 * @param {string} baseDir Absolute path of base directory
278 * @returns {LintResult} Result with single warning
279 * @private
280 */
281 function createIgnoreResult(filePath, baseDir) {
282 let message;
283 const isHidden = filePath.split(path.sep)
284 .find(segment => /^\./u.test(segment));
285 const isInNodeModules = baseDir && path.relative(baseDir, filePath).startsWith("node_modules");
286
287 if (isHidden) {
288 message = "File ignored by default. Use a negated ignore pattern (like \"--ignore-pattern '!<relative/path/to/filename>'\") to override.";
289 } else if (isInNodeModules) {
290 message = "File ignored by default. Use \"--ignore-pattern '!node_modules/*'\" to override.";
291 } else {
292 message = "File ignored because of a matching ignore pattern. Use \"--no-ignore\" to override.";
293 }
294
295 return {
296 filePath: path.resolve(filePath),
297 messages: [
298 {
299 fatal: false,
300 severity: 1,
301 message
302 }
303 ],
304 errorCount: 0,
305 warningCount: 1,
306 fixableErrorCount: 0,
307 fixableWarningCount: 0
308 };
309 }
310
311 /**
312 * Get a rule.
313 * @param {string} ruleId The rule ID to get.
314 * @param {ConfigArray[]} configArrays The config arrays that have plugin rules.
315 * @returns {Rule|null} The rule or null.
316 */
317 function getRule(ruleId, configArrays) {
318 for (const configArray of configArrays) {
319 const rule = configArray.pluginRules.get(ruleId);
320
321 if (rule) {
322 return rule;
323 }
324 }
325 return builtInRules.get(ruleId) || null;
326 }
327
328 /**
329 * Collect used deprecated rules.
330 * @param {ConfigArray[]} usedConfigArrays The config arrays which were used.
331 * @returns {IterableIterator<DeprecatedRuleInfo>} Used deprecated rules.
332 */
333 function *iterateRuleDeprecationWarnings(usedConfigArrays) {
334 const processedRuleIds = new Set();
335
336 // Flatten used configs.
337 /** @type {ExtractedConfig[]} */
338 const configs = [].concat(
339 ...usedConfigArrays.map(getUsedExtractedConfigs)
340 );
341
342 // Traverse rule configs.
343 for (const config of configs) {
344 for (const [ruleId, ruleConfig] of Object.entries(config.rules)) {
345
346 // Skip if it was processed.
347 if (processedRuleIds.has(ruleId)) {
348 continue;
349 }
350 processedRuleIds.add(ruleId);
351
352 // Skip if it's not used.
353 if (!ConfigOps.getRuleSeverity(ruleConfig)) {
354 continue;
355 }
356 const rule = getRule(ruleId, usedConfigArrays);
357
358 // Skip if it's not deprecated.
359 if (!(rule && rule.meta && rule.meta.deprecated)) {
360 continue;
361 }
362
363 // This rule was used and deprecated.
364 yield {
365 ruleId,
366 replacedBy: rule.meta.replacedBy || []
367 };
368 }
369 }
370 }
371
372 /**
373 * Checks if the given message is an error message.
374 * @param {LintMessage} message The message to check.
375 * @returns {boolean} Whether or not the message is an error message.
376 * @private
377 */
378 function isErrorMessage(message) {
379 return message.severity === 2;
380 }
381
382
383 /**
384 * return the cacheFile to be used by eslint, based on whether the provided parameter is
385 * a directory or looks like a directory (ends in `path.sep`), in which case the file
386 * name will be the `cacheFile/.cache_hashOfCWD`
387 *
388 * if cacheFile points to a file or looks like a file then in will just use that file
389 * @param {string} cacheFile The name of file to be used to store the cache
390 * @param {string} cwd Current working directory
391 * @returns {string} the resolved path to the cache file
392 */
393 function getCacheFile(cacheFile, cwd) {
394
395 /*
396 * make sure the path separators are normalized for the environment/os
397 * keeping the trailing path separator if present
398 */
399 const normalizedCacheFile = path.normalize(cacheFile);
400
401 const resolvedCacheFile = path.resolve(cwd, normalizedCacheFile);
402 const looksLikeADirectory = normalizedCacheFile.slice(-1) === path.sep;
403
404 /**
405 * return the name for the cache file in case the provided parameter is a directory
406 * @returns {string} the resolved path to the cacheFile
407 */
408 function getCacheFileForDirectory() {
409 return path.join(resolvedCacheFile, `.cache_${hash(cwd)}`);
410 }
411
412 let fileStats;
413
414 try {
415 fileStats = fs.lstatSync(resolvedCacheFile);
416 } catch {
417 fileStats = null;
418 }
419
420
421 /*
422 * in case the file exists we need to verify if the provided path
423 * is a directory or a file. If it is a directory we want to create a file
424 * inside that directory
425 */
426 if (fileStats) {
427
428 /*
429 * is a directory or is a file, but the original file the user provided
430 * looks like a directory but `path.resolve` removed the `last path.sep`
431 * so we need to still treat this like a directory
432 */
433 if (fileStats.isDirectory() || looksLikeADirectory) {
434 return getCacheFileForDirectory();
435 }
436
437 // is file so just use that file
438 return resolvedCacheFile;
439 }
440
441 /*
442 * here we known the file or directory doesn't exist,
443 * so we will try to infer if its a directory if it looks like a directory
444 * for the current operating system.
445 */
446
447 // if the last character passed is a path separator we assume is a directory
448 if (looksLikeADirectory) {
449 return getCacheFileForDirectory();
450 }
451
452 return resolvedCacheFile;
453 }
454
455 /**
456 * Convert a string array to a boolean map.
457 * @param {string[]|null} keys The keys to assign true.
458 * @param {boolean} defaultValue The default value for each property.
459 * @param {string} displayName The property name which is used in error message.
460 * @returns {Record<string,boolean>} The boolean map.
461 */
462 function toBooleanMap(keys, defaultValue, displayName) {
463 if (keys && !Array.isArray(keys)) {
464 throw new Error(`${displayName} must be an array.`);
465 }
466 if (keys && keys.length > 0) {
467 return keys.reduce((map, def) => {
468 const [key, value] = def.split(":");
469
470 if (key !== "__proto__") {
471 map[key] = value === void 0
472 ? defaultValue
473 : value === "true";
474 }
475
476 return map;
477 }, {});
478 }
479 return void 0;
480 }
481
482 /**
483 * Create a config data from CLI options.
484 * @param {CLIEngineOptions} options The options
485 * @returns {ConfigData|null} The created config data.
486 */
487 function createConfigDataFromOptions(options) {
488 const {
489 ignorePattern,
490 parser,
491 parserOptions,
492 plugins,
493 rules
494 } = options;
495 const env = toBooleanMap(options.envs, true, "envs");
496 const globals = toBooleanMap(options.globals, false, "globals");
497
498 if (
499 env === void 0 &&
500 globals === void 0 &&
501 (ignorePattern === void 0 || ignorePattern.length === 0) &&
502 parser === void 0 &&
503 parserOptions === void 0 &&
504 plugins === void 0 &&
505 rules === void 0
506 ) {
507 return null;
508 }
509 return {
510 env,
511 globals,
512 ignorePatterns: ignorePattern,
513 parser,
514 parserOptions,
515 plugins,
516 rules
517 };
518 }
519
520 /**
521 * Checks whether a directory exists at the given location
522 * @param {string} resolvedPath A path from the CWD
523 * @returns {boolean} `true` if a directory exists
524 */
525 function directoryExists(resolvedPath) {
526 try {
527 return fs.statSync(resolvedPath).isDirectory();
528 } catch (error) {
529 if (error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
530 return false;
531 }
532 throw error;
533 }
534 }
535
536 //------------------------------------------------------------------------------
537 // Public Interface
538 //------------------------------------------------------------------------------
539
540 class CLIEngine {
541
542 /**
543 * Creates a new instance of the core CLI engine.
544 * @param {CLIEngineOptions} providedOptions The options for this instance.
545 */
546 constructor(providedOptions) {
547 const options = Object.assign(
548 Object.create(null),
549 defaultOptions,
550 { cwd: process.cwd() },
551 providedOptions
552 );
553
554 if (options.fix === void 0) {
555 options.fix = false;
556 }
557
558 const additionalPluginPool = new Map();
559 const cacheFilePath = getCacheFile(
560 options.cacheLocation || options.cacheFile,
561 options.cwd
562 );
563 const configArrayFactory = new CascadingConfigArrayFactory({
564 additionalPluginPool,
565 baseConfig: options.baseConfig || null,
566 cliConfig: createConfigDataFromOptions(options),
567 cwd: options.cwd,
568 ignorePath: options.ignorePath,
569 resolvePluginsRelativeTo: options.resolvePluginsRelativeTo,
570 rulePaths: options.rulePaths,
571 specificConfigPath: options.configFile,
572 useEslintrc: options.useEslintrc,
573 builtInRules,
574 loadRules,
575 eslintRecommendedPath: path.resolve(__dirname, "../../conf/eslint-recommended.js"),
576 eslintAllPath: path.resolve(__dirname, "../../conf/eslint-all.js")
577 });
578 const fileEnumerator = new FileEnumerator({
579 configArrayFactory,
580 cwd: options.cwd,
581 extensions: options.extensions,
582 globInputPaths: options.globInputPaths,
583 errorOnUnmatchedPattern: options.errorOnUnmatchedPattern,
584 ignore: options.ignore
585 });
586 const lintResultCache =
587 options.cache ? new LintResultCache(cacheFilePath, options.cacheStrategy) : null;
588 const linter = new Linter({ cwd: options.cwd });
589
590 /** @type {ConfigArray[]} */
591 const lastConfigArrays = [configArrayFactory.getConfigArrayForFile()];
592
593 // Store private data.
594 internalSlotsMap.set(this, {
595 additionalPluginPool,
596 cacheFilePath,
597 configArrayFactory,
598 defaultIgnores: IgnorePattern.createDefaultIgnore(options.cwd),
599 fileEnumerator,
600 lastConfigArrays,
601 lintResultCache,
602 linter,
603 options
604 });
605
606 // setup special filter for fixes
607 if (options.fix && options.fixTypes && options.fixTypes.length > 0) {
608 debug(`Using fix types ${options.fixTypes}`);
609
610 // throw an error if any invalid fix types are found
611 validateFixTypes(options.fixTypes);
612
613 // convert to Set for faster lookup
614 const fixTypes = new Set(options.fixTypes);
615
616 // save original value of options.fix in case it's a function
617 const originalFix = (typeof options.fix === "function")
618 ? options.fix : () => true;
619
620 options.fix = message => {
621 const rule = message.ruleId && getRule(message.ruleId, lastConfigArrays);
622 const matches = rule && rule.meta && fixTypes.has(rule.meta.type);
623
624 return matches && originalFix(message);
625 };
626 }
627 }
628
629 getRules() {
630 const { lastConfigArrays } = internalSlotsMap.get(this);
631
632 return new Map(function *() {
633 yield* builtInRules;
634
635 for (const configArray of lastConfigArrays) {
636 yield* configArray.pluginRules;
637 }
638 }());
639 }
640
641 /**
642 * Returns results that only contains errors.
643 * @param {LintResult[]} results The results to filter.
644 * @returns {LintResult[]} The filtered results.
645 */
646 static getErrorResults(results) {
647 const filtered = [];
648
649 results.forEach(result => {
650 const filteredMessages = result.messages.filter(isErrorMessage);
651
652 if (filteredMessages.length > 0) {
653 filtered.push({
654 ...result,
655 messages: filteredMessages,
656 errorCount: filteredMessages.length,
657 warningCount: 0,
658 fixableErrorCount: result.fixableErrorCount,
659 fixableWarningCount: 0
660 });
661 }
662 });
663
664 return filtered;
665 }
666
667 /**
668 * Outputs fixes from the given results to files.
669 * @param {LintReport} report The report object created by CLIEngine.
670 * @returns {void}
671 */
672 static outputFixes(report) {
673 report.results.filter(result => Object.prototype.hasOwnProperty.call(result, "output")).forEach(result => {
674 fs.writeFileSync(result.filePath, result.output);
675 });
676 }
677
678
679 /**
680 * Add a plugin by passing its configuration
681 * @param {string} name Name of the plugin.
682 * @param {Plugin} pluginObject Plugin configuration object.
683 * @returns {void}
684 */
685 addPlugin(name, pluginObject) {
686 const {
687 additionalPluginPool,
688 configArrayFactory,
689 lastConfigArrays
690 } = internalSlotsMap.get(this);
691
692 additionalPluginPool.set(name, pluginObject);
693 configArrayFactory.clearCache();
694 lastConfigArrays.length = 1;
695 lastConfigArrays[0] = configArrayFactory.getConfigArrayForFile();
696 }
697
698 /**
699 * Resolves the patterns passed into executeOnFiles() into glob-based patterns
700 * for easier handling.
701 * @param {string[]} patterns The file patterns passed on the command line.
702 * @returns {string[]} The equivalent glob patterns.
703 */
704 resolveFileGlobPatterns(patterns) {
705 const { options } = internalSlotsMap.get(this);
706
707 if (options.globInputPaths === false) {
708 return patterns.filter(Boolean);
709 }
710
711 const extensions = (options.extensions || [".js"]).map(ext => ext.replace(/^\./u, ""));
712 const dirSuffix = `/**/*.{${extensions.join(",")}}`;
713
714 return patterns.filter(Boolean).map(pathname => {
715 const resolvedPath = path.resolve(options.cwd, pathname);
716 const newPath = directoryExists(resolvedPath)
717 ? pathname.replace(/[/\\]$/u, "") + dirSuffix
718 : pathname;
719
720 return path.normalize(newPath).replace(/\\/gu, "/");
721 });
722 }
723
724 /**
725 * Executes the current configuration on an array of file and directory names.
726 * @param {string[]} patterns An array of file and directory names.
727 * @returns {LintReport} The results for all files that were linted.
728 */
729 executeOnFiles(patterns) {
730 const {
731 cacheFilePath,
732 fileEnumerator,
733 lastConfigArrays,
734 lintResultCache,
735 linter,
736 options: {
737 allowInlineConfig,
738 cache,
739 cwd,
740 fix,
741 reportUnusedDisableDirectives
742 }
743 } = internalSlotsMap.get(this);
744 const results = [];
745 const startTime = Date.now();
746
747 // Clear the last used config arrays.
748 lastConfigArrays.length = 0;
749
750 // Delete cache file; should this do here?
751 if (!cache) {
752 try {
753 fs.unlinkSync(cacheFilePath);
754 } catch (error) {
755 const errorCode = error && error.code;
756
757 // Ignore errors when no such file exists or file system is read only (and cache file does not exist)
758 if (errorCode !== "ENOENT" && !(errorCode === "EROFS" && !fs.existsSync(cacheFilePath))) {
759 throw error;
760 }
761 }
762 }
763
764 // Iterate source code files.
765 for (const { config, filePath, ignored } of fileEnumerator.iterateFiles(patterns)) {
766 if (ignored) {
767 results.push(createIgnoreResult(filePath, cwd));
768 continue;
769 }
770
771 /*
772 * Store used configs for:
773 * - this method uses to collect used deprecated rules.
774 * - `getRules()` method uses to collect all loaded rules.
775 * - `--fix-type` option uses to get the loaded rule's meta data.
776 */
777 if (!lastConfigArrays.includes(config)) {
778 lastConfigArrays.push(config);
779 }
780
781 // Skip if there is cached result.
782 if (lintResultCache) {
783 const cachedResult =
784 lintResultCache.getCachedLintResults(filePath, config);
785
786 if (cachedResult) {
787 const hadMessages =
788 cachedResult.messages &&
789 cachedResult.messages.length > 0;
790
791 if (hadMessages && fix) {
792 debug(`Reprocessing cached file to allow autofix: ${filePath}`);
793 } else {
794 debug(`Skipping file since it hasn't changed: ${filePath}`);
795 results.push(cachedResult);
796 continue;
797 }
798 }
799 }
800
801 // Do lint.
802 const result = verifyText({
803 text: fs.readFileSync(filePath, "utf8"),
804 filePath,
805 config,
806 cwd,
807 fix,
808 allowInlineConfig,
809 reportUnusedDisableDirectives,
810 fileEnumerator,
811 linter
812 });
813
814 results.push(result);
815
816 /*
817 * Store the lint result in the LintResultCache.
818 * NOTE: The LintResultCache will remove the file source and any
819 * other properties that are difficult to serialize, and will
820 * hydrate those properties back in on future lint runs.
821 */
822 if (lintResultCache) {
823 lintResultCache.setCachedLintResults(filePath, config, result);
824 }
825 }
826
827 // Persist the cache to disk.
828 if (lintResultCache) {
829 lintResultCache.reconcile();
830 }
831
832 debug(`Linting complete in: ${Date.now() - startTime}ms`);
833 let usedDeprecatedRules;
834
835 return {
836 results,
837 ...calculateStatsPerRun(results),
838
839 // Initialize it lazily because CLI and `ESLint` API don't use it.
840 get usedDeprecatedRules() {
841 if (!usedDeprecatedRules) {
842 usedDeprecatedRules = Array.from(
843 iterateRuleDeprecationWarnings(lastConfigArrays)
844 );
845 }
846 return usedDeprecatedRules;
847 }
848 };
849 }
850
851 /**
852 * Executes the current configuration on text.
853 * @param {string} text A string of JavaScript code to lint.
854 * @param {string} [filename] An optional string representing the texts filename.
855 * @param {boolean} [warnIgnored] Always warn when a file is ignored
856 * @returns {LintReport} The results for the linting.
857 */
858 executeOnText(text, filename, warnIgnored) {
859 const {
860 configArrayFactory,
861 fileEnumerator,
862 lastConfigArrays,
863 linter,
864 options: {
865 allowInlineConfig,
866 cwd,
867 fix,
868 reportUnusedDisableDirectives
869 }
870 } = internalSlotsMap.get(this);
871 const results = [];
872 const startTime = Date.now();
873 const resolvedFilename = filename && path.resolve(cwd, filename);
874
875
876 // Clear the last used config arrays.
877 lastConfigArrays.length = 0;
878 if (resolvedFilename && this.isPathIgnored(resolvedFilename)) {
879 if (warnIgnored) {
880 results.push(createIgnoreResult(resolvedFilename, cwd));
881 }
882 } else {
883 const config = configArrayFactory.getConfigArrayForFile(
884 resolvedFilename || "__placeholder__.js"
885 );
886
887 /*
888 * Store used configs for:
889 * - this method uses to collect used deprecated rules.
890 * - `getRules()` method uses to collect all loaded rules.
891 * - `--fix-type` option uses to get the loaded rule's meta data.
892 */
893 lastConfigArrays.push(config);
894
895 // Do lint.
896 results.push(verifyText({
897 text,
898 filePath: resolvedFilename,
899 config,
900 cwd,
901 fix,
902 allowInlineConfig,
903 reportUnusedDisableDirectives,
904 fileEnumerator,
905 linter
906 }));
907 }
908
909 debug(`Linting complete in: ${Date.now() - startTime}ms`);
910 let usedDeprecatedRules;
911
912 return {
913 results,
914 ...calculateStatsPerRun(results),
915
916 // Initialize it lazily because CLI and `ESLint` API don't use it.
917 get usedDeprecatedRules() {
918 if (!usedDeprecatedRules) {
919 usedDeprecatedRules = Array.from(
920 iterateRuleDeprecationWarnings(lastConfigArrays)
921 );
922 }
923 return usedDeprecatedRules;
924 }
925 };
926 }
927
928 /**
929 * Returns a configuration object for the given file based on the CLI options.
930 * This is the same logic used by the ESLint CLI executable to determine
931 * configuration for each file it processes.
932 * @param {string} filePath The path of the file to retrieve a config object for.
933 * @returns {ConfigData} A configuration object for the file.
934 */
935 getConfigForFile(filePath) {
936 const { configArrayFactory, options } = internalSlotsMap.get(this);
937 const absolutePath = path.resolve(options.cwd, filePath);
938
939 if (directoryExists(absolutePath)) {
940 throw Object.assign(
941 new Error("'filePath' should not be a directory path."),
942 { messageTemplate: "print-config-with-directory-path" }
943 );
944 }
945
946 return configArrayFactory
947 .getConfigArrayForFile(absolutePath)
948 .extractConfig(absolutePath)
949 .toCompatibleObjectAsConfigFileContent();
950 }
951
952 /**
953 * Checks if a given path is ignored by ESLint.
954 * @param {string} filePath The path of the file to check.
955 * @returns {boolean} Whether or not the given path is ignored.
956 */
957 isPathIgnored(filePath) {
958 const {
959 configArrayFactory,
960 defaultIgnores,
961 options: { cwd, ignore }
962 } = internalSlotsMap.get(this);
963 const absolutePath = path.resolve(cwd, filePath);
964
965 if (ignore) {
966 const config = configArrayFactory
967 .getConfigArrayForFile(absolutePath)
968 .extractConfig(absolutePath);
969 const ignores = config.ignores || defaultIgnores;
970
971 return ignores(absolutePath);
972 }
973
974 return defaultIgnores(absolutePath);
975 }
976
977 /**
978 * Returns the formatter representing the given format or null if the `format` is not a string.
979 * @param {string} [format] The name of the format to load or the path to a
980 * custom formatter.
981 * @returns {(Function|null)} The formatter function or null if the `format` is not a string.
982 */
983 getFormatter(format) {
984
985 // default is stylish
986 const resolvedFormatName = format || "stylish";
987
988 // only strings are valid formatters
989 if (typeof resolvedFormatName === "string") {
990
991 // replace \ with / for Windows compatibility
992 const normalizedFormatName = resolvedFormatName.replace(/\\/gu, "/");
993
994 const slots = internalSlotsMap.get(this);
995 const cwd = slots ? slots.options.cwd : process.cwd();
996 const namespace = naming.getNamespaceFromTerm(normalizedFormatName);
997
998 let formatterPath;
999
1000 // if there's a slash, then it's a file (TODO: this check seems dubious for scoped npm packages)
1001 if (!namespace && normalizedFormatName.indexOf("/") > -1) {
1002 formatterPath = path.resolve(cwd, normalizedFormatName);
1003 } else {
1004 try {
1005 const npmFormat = naming.normalizePackageName(normalizedFormatName, "eslint-formatter");
1006
1007 formatterPath = ModuleResolver.resolve(npmFormat, path.join(cwd, "__placeholder__.js"));
1008 } catch {
1009 formatterPath = path.resolve(__dirname, "formatters", normalizedFormatName);
1010 }
1011 }
1012
1013 try {
1014 return require(formatterPath);
1015 } catch (ex) {
1016 ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`;
1017 throw ex;
1018 }
1019
1020 } else {
1021 return null;
1022 }
1023 }
1024 }
1025
1026 CLIEngine.version = pkg.version;
1027 CLIEngine.getFormatter = CLIEngine.prototype.getFormatter;
1028
1029 module.exports = {
1030 CLIEngine,
1031
1032 /**
1033 * Get the internal slots of a given CLIEngine instance for tests.
1034 * @param {CLIEngine} instance The CLIEngine instance to get.
1035 * @returns {CLIEngineInternalSlots} The internal slots.
1036 */
1037 getCLIEngineInternalSlots(instance) {
1038 return internalSlotsMap.get(instance);
1039 }
1040 };