UNPKG

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