2 * @fileoverview Main CLI object.
3 * @author Nicholas C. Zakas
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.
14 //------------------------------------------------------------------------------
16 //------------------------------------------------------------------------------
18 const fs
= require("fs");
19 const path
= require("path");
20 const defaultOptions
= require("../../conf/default-cli-options");
21 const pkg
= require("../../package.json");
28 CascadingConfigArrayFactory
,
30 getUsedExtractedConfigs
32 } = require("@eslint/eslintrc");
35 * For some reason, ModuleResolver must be included via filepath instead of by
36 * API exports in order to work properly. That's why this is separated out onto
37 * its own require() statement.
39 const ModuleResolver
= require("@eslint/eslintrc/lib/shared/relative-module-resolver");
40 const { FileEnumerator
} = require("./file-enumerator");
42 const { Linter
} = require("../linter");
43 const builtInRules
= require("../rules");
44 const loadRules
= require("./load-rules");
45 const hash
= require("./hash");
46 const LintResultCache
= require("./lint-result-cache");
48 const debug
= require("debug")("eslint:cli-engine");
49 const validFixTypes
= new Set(["problem", "suggestion", "layout"]);
51 //------------------------------------------------------------------------------
53 //------------------------------------------------------------------------------
55 // For VSCode IntelliSense
56 /** @typedef {import("../shared/types").ConfigData} ConfigData */
57 /** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */
58 /** @typedef {import("../shared/types").LintMessage} LintMessage */
59 /** @typedef {import("../shared/types").ParserOptions} ParserOptions */
60 /** @typedef {import("../shared/types").Plugin} Plugin */
61 /** @typedef {import("../shared/types").RuleConf} RuleConf */
62 /** @typedef {import("../shared/types").Rule} Rule */
63 /** @typedef {ReturnType<CascadingConfigArrayFactory["getConfigArrayForFile"]>} ConfigArray */
64 /** @typedef {ReturnType<ConfigArray["extractConfig"]>} ExtractedConfig */
67 * The options to configure a CLI engine with.
68 * @typedef {Object} CLIEngineOptions
69 * @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments.
70 * @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this CLIEngine instance
71 * @property {boolean} [cache] Enable result caching.
72 * @property {string} [cacheLocation] The cache file to use instead of .eslintcache.
73 * @property {string} [configFile] The configuration file to use.
74 * @property {string} [cwd] The value to use for the current working directory.
75 * @property {string[]} [envs] An array of environments to load.
76 * @property {string[]|null} [extensions] An array of file extensions to check.
77 * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean.
78 * @property {string[]} [fixTypes] Array of rule types to apply fixes for.
79 * @property {string[]} [globals] An array of global variables to declare.
80 * @property {boolean} [ignore] False disables use of .eslintignore.
81 * @property {string} [ignorePath] The ignore file to use instead of .eslintignore.
82 * @property {string|string[]} [ignorePattern] One or more glob patterns to ignore.
83 * @property {boolean} [useEslintrc] False disables looking for .eslintrc
84 * @property {string} [parser] The name of the parser to use.
85 * @property {ParserOptions} [parserOptions] An object of parserOption settings to use.
86 * @property {string[]} [plugins] An array of plugins to load.
87 * @property {Record<string,RuleConf>} [rules] An object of rules to use.
88 * @property {string[]} [rulePaths] An array of directories to load custom rules from.
89 * @property {boolean} [reportUnusedDisableDirectives] `true` adds reports for unused eslint-disable directives
90 * @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.
91 * @property {string} [resolvePluginsRelativeTo] The folder where plugins should be resolved from, defaulting to the CWD
96 * @typedef {Object} LintResult
97 * @property {string} filePath The path to the file that was linted.
98 * @property {LintMessage[]} messages All of the messages for the result.
99 * @property {number} errorCount Number of errors for the result.
100 * @property {number} warningCount Number of warnings for the result.
101 * @property {number} fixableErrorCount Number of fixable errors for the result.
102 * @property {number} fixableWarningCount Number of fixable warnings for the result.
103 * @property {string} [source] The source code of the file that was linted.
104 * @property {string} [output] The source code of the file that was linted, with as many fixes applied as possible.
109 * @typedef {Object} LintReport
110 * @property {LintResult[]} results All of the result.
111 * @property {number} errorCount Number of 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.
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.
132 //------------------------------------------------------------------------------
134 //------------------------------------------------------------------------------
136 /** @type {WeakMap<CLIEngine, CLIEngineInternalSlots>} */
137 const internalSlotsMap
= new WeakMap();
140 * Determines if each fix type in an array is supported by ESLint and throws
142 * @param {string[]} fixTypes An array of fix types to check.
144 * @throws {Error} If an invalid fix type is found.
146 function validateFixTypes(fixTypes
) {
147 for (const fixType
of fixTypes
) {
148 if (!validFixTypes
.has(fixType
)) {
149 throw new Error(`Invalid fix type "${fixType}" found.`);
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
160 function calculateStatsPerFile(messages
) {
161 return messages
.reduce((stat
, message
) => {
162 if (message
.fatal
|| message
.severity
=== 2) {
165 stat
.fixableErrorCount
++;
170 stat
.fixableWarningCount
++;
177 fixableErrorCount
: 0,
178 fixableWarningCount
: 0
183 * It will calculate the error and warning count for collection of results from all files
184 * @param {LintResult[]} results Collection of messages from all the files
185 * @returns {Object} Contains the stats
188 function calculateStatsPerRun(results
) {
189 return results
.reduce((stat
, result
) => {
190 stat
.errorCount
+= result
.errorCount
;
191 stat
.warningCount
+= result
.warningCount
;
192 stat
.fixableErrorCount
+= result
.fixableErrorCount
;
193 stat
.fixableWarningCount
+= result
.fixableWarningCount
;
198 fixableErrorCount
: 0,
199 fixableWarningCount
: 0
204 * Processes an source code using ESLint.
205 * @param {Object} config The config object.
206 * @param {string} config.text The source code to verify.
207 * @param {string} config.cwd The path to the current working directory.
208 * @param {string|undefined} config.filePath The path to the file of `text`. If this is undefined, it uses `<text>`.
209 * @param {ConfigArray} config.config The config.
210 * @param {boolean} config.fix If `true` then it does fix.
211 * @param {boolean} config.allowInlineConfig If `true` then it uses directive comments.
212 * @param {boolean} config.reportUnusedDisableDirectives If `true` then it reports unused `eslint-disable` comments.
213 * @param {FileEnumerator} config.fileEnumerator The file enumerator to check if a path is a target or not.
214 * @param {Linter} config.linter The linter instance to verify.
215 * @returns {LintResult} The result of linting.
218 function verifyText({
221 filePath
: providedFilePath
,
225 reportUnusedDisableDirectives
,
229 const filePath
= providedFilePath
|| "<text>";
231 debug(`Lint ${filePath}`);
235 * `config.extractConfig(filePath)` requires an absolute path, but `linter`
236 * doesn't know CWD, so it gives `linter` an absolute path always.
238 const filePathToVerify
= filePath
=== "<text>" ? path
.join(cwd
, filePath
) : filePath
;
239 const { fixed
, messages
, output
} = linter
.verifyAndFix(
244 filename
: filePathToVerify
,
246 reportUnusedDisableDirectives
,
249 * Check if the linter should adopt a given code block or not.
250 * @param {string} blockFilename The virtual filename of a code block.
251 * @returns {boolean} `true` if the linter should adopt the code block.
253 filterCodeBlock(blockFilename
) {
254 return fileEnumerator
.isTargetPath(blockFilename
);
263 ...calculateStatsPerFile(messages
)
267 result
.output
= output
;
270 result
.errorCount
+ result
.warningCount
> 0 &&
271 typeof result
.output
=== "undefined"
273 result
.source
= text
;
280 * Returns result with warning by ignore settings
281 * @param {string} filePath File path of checked code
282 * @param {string} baseDir Absolute path of base directory
283 * @returns {LintResult} Result with single warning
286 function createIgnoreResult(filePath
, baseDir
) {
288 const isHidden
= filePath
.split(path
.sep
)
289 .find(segment
=> /^\./u.test(segment
));
290 const isInNodeModules
= baseDir
&& path
.relative(baseDir
, filePath
).startsWith("node_modules");
293 message
= "File ignored by default. Use a negated ignore pattern (like \"--ignore-pattern '!<relative/path/to/filename>'\") to override.";
294 } else if (isInNodeModules
) {
295 message
= "File ignored by default. Use \"--ignore-pattern '!node_modules/*'\" to override.";
297 message
= "File ignored because of a matching ignore pattern. Use \"--no-ignore\" to override.";
301 filePath
: path
.resolve(filePath
),
311 fixableErrorCount
: 0,
312 fixableWarningCount
: 0
318 * @param {string} ruleId The rule ID to get.
319 * @param {ConfigArray[]} configArrays The config arrays that have plugin rules.
320 * @returns {Rule|null} The rule or null.
322 function getRule(ruleId
, configArrays
) {
323 for (const configArray
of configArrays
) {
324 const rule
= configArray
.pluginRules
.get(ruleId
);
330 return builtInRules
.get(ruleId
) || null;
334 * Collect used deprecated rules.
335 * @param {ConfigArray[]} usedConfigArrays The config arrays which were used.
336 * @returns {IterableIterator<DeprecatedRuleInfo>} Used deprecated rules.
338 function *iterateRuleDeprecationWarnings(usedConfigArrays
) {
339 const processedRuleIds
= new Set();
341 // Flatten used configs.
342 /** @type {ExtractedConfig[]} */
343 const configs
= [].concat(
344 ...usedConfigArrays
.map(getUsedExtractedConfigs
)
347 // Traverse rule configs.
348 for (const config
of configs
) {
349 for (const [ruleId
, ruleConfig
] of Object
.entries(config
.rules
)) {
351 // Skip if it was processed.
352 if (processedRuleIds
.has(ruleId
)) {
355 processedRuleIds
.add(ruleId
);
357 // Skip if it's not used.
358 if (!ConfigOps
.getRuleSeverity(ruleConfig
)) {
361 const rule
= getRule(ruleId
, usedConfigArrays
);
363 // Skip if it's not deprecated.
364 if (!(rule
&& rule
.meta
&& rule
.meta
.deprecated
)) {
368 // This rule was used and deprecated.
371 replacedBy
: rule
.meta
.replacedBy
|| []
378 * Checks if the given message is an error message.
379 * @param {LintMessage} message The message to check.
380 * @returns {boolean} Whether or not the message is an error message.
383 function isErrorMessage(message
) {
384 return message
.severity
=== 2;
389 * return the cacheFile to be used by eslint, based on whether the provided parameter is
390 * a directory or looks like a directory (ends in `path.sep`), in which case the file
391 * name will be the `cacheFile/.cache_hashOfCWD`
393 * if cacheFile points to a file or looks like a file then in will just use that file
394 * @param {string} cacheFile The name of file to be used to store the cache
395 * @param {string} cwd Current working directory
396 * @returns {string} the resolved path to the cache file
398 function getCacheFile(cacheFile
, cwd
) {
401 * make sure the path separators are normalized for the environment/os
402 * keeping the trailing path separator if present
404 const normalizedCacheFile
= path
.normalize(cacheFile
);
406 const resolvedCacheFile
= path
.resolve(cwd
, normalizedCacheFile
);
407 const looksLikeADirectory
= normalizedCacheFile
.slice(-1) === path
.sep
;
410 * return the name for the cache file in case the provided parameter is a directory
411 * @returns {string} the resolved path to the cacheFile
413 function getCacheFileForDirectory() {
414 return path
.join(resolvedCacheFile
, `.cache_${hash(cwd)}`);
420 fileStats
= fs
.lstatSync(resolvedCacheFile
);
427 * in case the file exists we need to verify if the provided path
428 * is a directory or a file. If it is a directory we want to create a file
429 * inside that directory
434 * is a directory or is a file, but the original file the user provided
435 * looks like a directory but `path.resolve` removed the `last path.sep`
436 * so we need to still treat this like a directory
438 if (fileStats
.isDirectory() || looksLikeADirectory
) {
439 return getCacheFileForDirectory();
442 // is file so just use that file
443 return resolvedCacheFile
;
447 * here we known the file or directory doesn't exist,
448 * so we will try to infer if its a directory if it looks like a directory
449 * for the current operating system.
452 // if the last character passed is a path separator we assume is a directory
453 if (looksLikeADirectory
) {
454 return getCacheFileForDirectory();
457 return resolvedCacheFile
;
461 * Convert a string array to a boolean map.
462 * @param {string[]|null} keys The keys to assign true.
463 * @param {boolean} defaultValue The default value for each property.
464 * @param {string} displayName The property name which is used in error message.
465 * @returns {Record<string,boolean>} The boolean map.
467 function toBooleanMap(keys
, defaultValue
, displayName
) {
468 if (keys
&& !Array
.isArray(keys
)) {
469 throw new Error(`${displayName} must be an array.`);
471 if (keys
&& keys
.length
> 0) {
472 return keys
.reduce((map
, def
) => {
473 const [key
, value
] = def
.split(":");
475 if (key
!== "__proto__") {
476 map
[key
] = value
=== void 0
488 * Create a config data from CLI options.
489 * @param {CLIEngineOptions} options The options
490 * @returns {ConfigData|null} The created config data.
492 function createConfigDataFromOptions(options
) {
500 const env
= toBooleanMap(options
.envs
, true, "envs");
501 const globals
= toBooleanMap(options
.globals
, false, "globals");
505 globals
=== void 0 &&
506 (ignorePattern
=== void 0 || ignorePattern
.length
=== 0) &&
508 parserOptions
=== void 0 &&
509 plugins
=== void 0 &&
517 ignorePatterns
: ignorePattern
,
526 * Checks whether a directory exists at the given location
527 * @param {string} resolvedPath A path from the CWD
528 * @returns {boolean} `true` if a directory exists
530 function directoryExists(resolvedPath
) {
532 return fs
.statSync(resolvedPath
).isDirectory();
534 if (error
&& error
.code
=== "ENOENT") {
541 //------------------------------------------------------------------------------
543 //------------------------------------------------------------------------------
548 * Creates a new instance of the core CLI engine.
549 * @param {CLIEngineOptions} providedOptions The options for this instance.
551 constructor(providedOptions
) {
552 const options
= Object
.assign(
555 { cwd
: process
.cwd() },
559 if (options
.fix
=== void 0) {
563 const additionalPluginPool
= new Map();
564 const cacheFilePath
= getCacheFile(
565 options
.cacheLocation
|| options
.cacheFile
,
568 const configArrayFactory
= new CascadingConfigArrayFactory({
569 additionalPluginPool
,
570 baseConfig
: options
.baseConfig
|| null,
571 cliConfig
: createConfigDataFromOptions(options
),
573 ignorePath
: options
.ignorePath
,
574 resolvePluginsRelativeTo
: options
.resolvePluginsRelativeTo
,
575 rulePaths
: options
.rulePaths
,
576 specificConfigPath
: options
.configFile
,
577 useEslintrc
: options
.useEslintrc
,
580 eslintRecommendedPath
: path
.resolve(__dirname
, "../../conf/eslint-recommended.js"),
581 eslintAllPath
: path
.resolve(__dirname
, "../../conf/eslint-all.js")
583 const fileEnumerator
= new FileEnumerator({
586 extensions
: options
.extensions
,
587 globInputPaths
: options
.globInputPaths
,
588 errorOnUnmatchedPattern
: options
.errorOnUnmatchedPattern
,
589 ignore
: options
.ignore
591 const lintResultCache
=
592 options
.cache
? new LintResultCache(cacheFilePath
) : null;
593 const linter
= new Linter({ cwd
: options
.cwd
});
595 /** @type {ConfigArray[]} */
596 const lastConfigArrays
= [configArrayFactory
.getConfigArrayForFile()];
598 // Store private data.
599 internalSlotsMap
.set(this, {
600 additionalPluginPool
,
603 defaultIgnores
: IgnorePattern
.createDefaultIgnore(options
.cwd
),
611 // setup special filter for fixes
612 if (options
.fix
&& options
.fixTypes
&& options
.fixTypes
.length
> 0) {
613 debug(`Using fix types ${options.fixTypes}`);
615 // throw an error if any invalid fix types are found
616 validateFixTypes(options
.fixTypes
);
618 // convert to Set for faster lookup
619 const fixTypes
= new Set(options
.fixTypes
);
621 // save original value of options.fix in case it's a function
622 const originalFix
= (typeof options
.fix
=== "function")
623 ? options
.fix
: () => true;
625 options
.fix
= message
=> {
626 const rule
= message
.ruleId
&& getRule(message
.ruleId
, lastConfigArrays
);
627 const matches
= rule
&& rule
.meta
&& fixTypes
.has(rule
.meta
.type
);
629 return matches
&& originalFix(message
);
635 const { lastConfigArrays
} = internalSlotsMap
.get(this);
637 return new Map(function *() {
640 for (const configArray
of lastConfigArrays
) {
641 yield* configArray
.pluginRules
;
647 * Returns results that only contains errors.
648 * @param {LintResult[]} results The results to filter.
649 * @returns {LintResult[]} The filtered results.
651 static getErrorResults(results
) {
654 results
.forEach(result
=> {
655 const filteredMessages
= result
.messages
.filter(isErrorMessage
);
657 if (filteredMessages
.length
> 0) {
660 messages
: filteredMessages
,
661 errorCount
: filteredMessages
.length
,
663 fixableErrorCount
: result
.fixableErrorCount
,
664 fixableWarningCount
: 0
673 * Outputs fixes from the given results to files.
674 * @param {LintReport} report The report object created by CLIEngine.
677 static outputFixes(report
) {
678 report
.results
.filter(result
=> Object
.prototype.hasOwnProperty
.call(result
, "output")).forEach(result
=> {
679 fs
.writeFileSync(result
.filePath
, result
.output
);
685 * Add a plugin by passing its configuration
686 * @param {string} name Name of the plugin.
687 * @param {Plugin} pluginObject Plugin configuration object.
690 addPlugin(name
, pluginObject
) {
692 additionalPluginPool
,
695 } = internalSlotsMap
.get(this);
697 additionalPluginPool
.set(name
, pluginObject
);
698 configArrayFactory
.clearCache();
699 lastConfigArrays
.length
= 1;
700 lastConfigArrays
[0] = configArrayFactory
.getConfigArrayForFile();
704 * Resolves the patterns passed into executeOnFiles() into glob-based patterns
705 * for easier handling.
706 * @param {string[]} patterns The file patterns passed on the command line.
707 * @returns {string[]} The equivalent glob patterns.
709 resolveFileGlobPatterns(patterns
) {
710 const { options
} = internalSlotsMap
.get(this);
712 if (options
.globInputPaths
=== false) {
713 return patterns
.filter(Boolean
);
716 const extensions
= (options
.extensions
|| [".js"]).map(ext
=> ext
.replace(/^\./u, ""));
717 const dirSuffix
= `/**/*.{${extensions.join(",")}}`;
719 return patterns
.filter(Boolean
).map(pathname
=> {
720 const resolvedPath
= path
.resolve(options
.cwd
, pathname
);
721 const newPath
= directoryExists(resolvedPath
)
722 ? pathname
.replace(/[/\\]$/u, "") + dirSuffix
725 return path
.normalize(newPath
).replace(/\\/gu, "/");
730 * Executes the current configuration on an array of file and directory names.
731 * @param {string[]} patterns An array of file and directory names.
732 * @returns {LintReport} The results for all files that were linted.
734 executeOnFiles(patterns) {
746 reportUnusedDisableDirectives
748 } = internalSlotsMap.get(this);
750 const startTime = Date.now();
752 // Clear the last used config arrays.
753 lastConfigArrays.length = 0;
755 // Delete cache file; should this do here?
758 fs.unlinkSync(cacheFilePath);
760 const errorCode = error && error.code;
762 // Ignore errors when no such file exists or file system is read only (and cache file does not exist)
763 if (errorCode !== "ENOENT
" && !(errorCode === "EROFS
" && !fs.existsSync(cacheFilePath))) {
769 // Iterate source code files.
770 for (const { config, filePath, ignored } of fileEnumerator.iterateFiles(patterns)) {
772 results.push(createIgnoreResult(filePath, cwd));
777 * Store used configs for:
778 * - this method uses to collect used deprecated rules.
779 * - `getRules()` method uses to collect all loaded rules.
780 * - `--fix-type` option uses to get the loaded rule's meta data.
782 if (!lastConfigArrays.includes(config)) {
783 lastConfigArrays.push(config);
786 // Skip if there is cached result.
787 if (lintResultCache) {
789 lintResultCache.getCachedLintResults(filePath, config);
793 cachedResult.messages &&
794 cachedResult.messages.length > 0;
796 if (hadMessages && fix) {
797 debug(`Reprocessing cached file to allow autofix: ${filePath}`);
799 debug(`Skipping file since it hasn't changed: ${filePath}`);
800 results.push(cachedResult);
807 const result = verifyText({
808 text: fs.readFileSync(filePath, "utf8
"),
814 reportUnusedDisableDirectives,
819 results.push(result);
822 * Store the lint result in the LintResultCache.
823 * NOTE: The LintResultCache will remove the file source and any
824 * other properties that are difficult to serialize, and will
825 * hydrate those properties back in on future lint runs.
827 if (lintResultCache) {
828 lintResultCache.setCachedLintResults(filePath, config, result);
832 // Persist the cache to disk.
833 if (lintResultCache) {
834 lintResultCache.reconcile();
837 debug(`Linting complete in: ${Date.now() - startTime}ms`);
838 let usedDeprecatedRules;
842 ...calculateStatsPerRun(results),
844 // Initialize it lazily because CLI and `ESLint` API don't use it.
845 get usedDeprecatedRules() {
846 if (!usedDeprecatedRules) {
847 usedDeprecatedRules = Array.from(
848 iterateRuleDeprecationWarnings(lastConfigArrays)
851 return usedDeprecatedRules;
857 * Executes the current configuration on text.
858 * @param {string} text A string of JavaScript code to lint.
859 * @param {string} [filename] An optional string representing the texts filename.
860 * @param {boolean} [warnIgnored] Always warn when a file is ignored
861 * @returns {LintReport} The results for the linting.
863 executeOnText(text, filename, warnIgnored) {
873 reportUnusedDisableDirectives
875 } = internalSlotsMap.get(this);
877 const startTime = Date.now();
878 const resolvedFilename = filename && path.resolve(cwd, filename);
881 // Clear the last used config arrays.
882 lastConfigArrays.length = 0;
883 if (resolvedFilename && this.isPathIgnored(resolvedFilename)) {
885 results.push(createIgnoreResult(resolvedFilename, cwd));
888 const config = configArrayFactory.getConfigArrayForFile(
889 resolvedFilename || "__placeholder__
.js
"
893 * Store used configs for:
894 * - this method uses to collect used deprecated rules.
895 * - `getRules()` method uses to collect all loaded rules.
896 * - `--fix-type` option uses to get the loaded rule's meta data.
898 lastConfigArrays.push(config);
901 results.push(verifyText({
903 filePath: resolvedFilename,
908 reportUnusedDisableDirectives,
914 debug(`Linting complete in: ${Date.now() - startTime}ms`);
915 let usedDeprecatedRules;
919 ...calculateStatsPerRun(results),
921 // Initialize it lazily because CLI and `ESLint` API don't use it.
922 get usedDeprecatedRules() {
923 if (!usedDeprecatedRules) {
924 usedDeprecatedRules = Array.from(
925 iterateRuleDeprecationWarnings(lastConfigArrays)
928 return usedDeprecatedRules;
934 * Returns a configuration object for the given file based on the CLI options.
935 * This is the same logic used by the ESLint CLI executable to determine
936 * configuration for each file it processes.
937 * @param {string} filePath The path of the file to retrieve a config object for.
938 * @returns {ConfigData} A configuration object for the file.
940 getConfigForFile(filePath) {
941 const { configArrayFactory, options } = internalSlotsMap.get(this);
942 const absolutePath = path.resolve(options.cwd, filePath);
944 if (directoryExists(absolutePath)) {
946 new Error("'filePath' should not be a directory path
."),
947 { messageTemplate: "print
-config
-with-directory
-path
" }
951 return configArrayFactory
952 .getConfigArrayForFile(absolutePath)
953 .extractConfig(absolutePath)
954 .toCompatibleObjectAsConfigFileContent();
958 * Checks if a given path is ignored by ESLint.
959 * @param {string} filePath The path of the file to check.
960 * @returns {boolean} Whether or not the given path is ignored.
962 isPathIgnored(filePath) {
966 options: { cwd, ignore }
967 } = internalSlotsMap.get(this);
968 const absolutePath = path.resolve(cwd, filePath);
971 const config = configArrayFactory
972 .getConfigArrayForFile(absolutePath)
973 .extractConfig(absolutePath);
974 const ignores = config.ignores || defaultIgnores;
976 return ignores(absolutePath);
979 return defaultIgnores(absolutePath);
983 * Returns the formatter representing the given format or null if the `format` is not a string.
984 * @param {string} [format] The name of the format to load or the path to a
986 * @returns {(Function|null)} The formatter function or null if the `format` is not a string.
988 getFormatter(format) {
990 // default is stylish
991 const resolvedFormatName = format || "stylish
";
993 // only strings are valid formatters
994 if (typeof resolvedFormatName === "string
") {
996 // replace \ with / for Windows compatibility
997 const normalizedFormatName = resolvedFormatName.replace(/\\/gu, "/");
999 const slots = internalSlotsMap.get(this);
1000 const cwd = slots ? slots.options.cwd : process.cwd();
1001 const namespace = naming.getNamespaceFromTerm(normalizedFormatName);
1005 // if there's a slash, then it's a file (TODO: this check seems dubious for scoped npm packages)
1006 if (!namespace && normalizedFormatName.indexOf("/") > -1) {
1007 formatterPath = path.resolve(cwd, normalizedFormatName);
1010 const npmFormat = naming.normalizePackageName(normalizedFormatName, "eslint
-formatter
");
1012 formatterPath = ModuleResolver.resolve(npmFormat, path.join(cwd, "__placeholder__
.js
"));
1014 formatterPath = path.resolve(__dirname, "formatters
", normalizedFormatName);
1019 return require(formatterPath);
1021 ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`;
1031 CLIEngine.version = pkg.version;
1032 CLIEngine.getFormatter = CLIEngine.prototype.getFormatter;
1038 * Get the internal slots of a given CLIEngine instance for tests.
1039 * @param {CLIEngine} instance The CLIEngine instance to get.
1040 * @returns {CLIEngineInternalSlots} The internal slots.
1042 getCLIEngineInternalSlots(instance) {
1043 return internalSlotsMap.get(instance);