UNPKG

36.5 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 }
32} = require("@eslint/eslintrc");
33
34/*
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.
38 */
39const ModuleResolver = require("@eslint/eslintrc/lib/shared/relative-module-resolver");
40const { FileEnumerator } = require("./file-enumerator");
41
42const { Linter } = require("../linter");
43const builtInRules = require("../rules");
44const loadRules = require("./load-rules");
45const hash = require("./hash");
46const LintResultCache = require("./lint-result-cache");
47
48const debug = require("debug")("eslint:cli-engine");
49const validFixTypes = new Set(["problem", "suggestion", "layout"]);
50
51//------------------------------------------------------------------------------
52// Typedefs
53//------------------------------------------------------------------------------
54
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 */
65
66/**
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
92 */
93
94/**
95 * A linting result.
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.
105 */
106
107/**
108 * Linting results.
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.
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.fix) {
165 stat.fixableErrorCount++;
166 }
167 } else {
168 stat.warningCount++;
169 if (message.fix) {
170 stat.fixableWarningCount++;
171 }
172 }
173 return stat;
174 }, {
175 errorCount: 0,
176 warningCount: 0,
177 fixableErrorCount: 0,
178 fixableWarningCount: 0
179 });
180}
181
182/**
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
186 * @private
187 */
188function 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;
194 return stat;
195 }, {
196 errorCount: 0,
197 warningCount: 0,
198 fixableErrorCount: 0,
199 fixableWarningCount: 0
200 });
201}
202
203/**
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.
216 * @private
217 */
218function verifyText({
219 text,
220 cwd,
221 filePath: providedFilePath,
222 config,
223 fix,
224 allowInlineConfig,
225 reportUnusedDisableDirectives,
226 fileEnumerator,
227 linter
228}) {
229 const filePath = providedFilePath || "<text>";
230
231 debug(`Lint ${filePath}`);
232
233 /*
234 * Verify.
235 * `config.extractConfig(filePath)` requires an absolute path, but `linter`
236 * doesn't know CWD, so it gives `linter` an absolute path always.
237 */
238 const filePathToVerify = filePath === "<text>" ? path.join(cwd, filePath) : filePath;
239 const { fixed, messages, output } = linter.verifyAndFix(
240 text,
241 config,
242 {
243 allowInlineConfig,
244 filename: filePathToVerify,
245 fix,
246 reportUnusedDisableDirectives,
247
248 /**
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.
252 */
253 filterCodeBlock(blockFilename) {
254 return fileEnumerator.isTargetPath(blockFilename);
255 }
256 }
257 );
258
259 // Tweak and return.
260 const result = {
261 filePath,
262 messages,
263 ...calculateStatsPerFile(messages)
264 };
265
266 if (fixed) {
267 result.output = output;
268 }
269 if (
270 result.errorCount + result.warningCount > 0 &&
271 typeof result.output === "undefined"
272 ) {
273 result.source = text;
274 }
275
276 return result;
277}
278
279/**
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
284 * @private
285 */
286function createIgnoreResult(filePath, baseDir) {
287 let message;
288 const isHidden = filePath.split(path.sep)
289 .find(segment => /^\./u.test(segment));
290 const isInNodeModules = baseDir && path.relative(baseDir, filePath).startsWith("node_modules");
291
292 if (isHidden) {
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.";
296 } else {
297 message = "File ignored because of a matching ignore pattern. Use \"--no-ignore\" to override.";
298 }
299
300 return {
301 filePath: path.resolve(filePath),
302 messages: [
303 {
304 fatal: false,
305 severity: 1,
306 message
307 }
308 ],
309 errorCount: 0,
310 warningCount: 1,
311 fixableErrorCount: 0,
312 fixableWarningCount: 0
313 };
314}
315
316/**
317 * Get a rule.
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.
321 */
322function getRule(ruleId, configArrays) {
323 for (const configArray of configArrays) {
324 const rule = configArray.pluginRules.get(ruleId);
325
326 if (rule) {
327 return rule;
328 }
329 }
330 return builtInRules.get(ruleId) || null;
331}
332
333/**
334 * Collect used deprecated rules.
335 * @param {ConfigArray[]} usedConfigArrays The config arrays which were used.
336 * @returns {IterableIterator<DeprecatedRuleInfo>} Used deprecated rules.
337 */
338function *iterateRuleDeprecationWarnings(usedConfigArrays) {
339 const processedRuleIds = new Set();
340
341 // Flatten used configs.
342 /** @type {ExtractedConfig[]} */
343 const configs = [].concat(
344 ...usedConfigArrays.map(getUsedExtractedConfigs)
345 );
346
347 // Traverse rule configs.
348 for (const config of configs) {
349 for (const [ruleId, ruleConfig] of Object.entries(config.rules)) {
350
351 // Skip if it was processed.
352 if (processedRuleIds.has(ruleId)) {
353 continue;
354 }
355 processedRuleIds.add(ruleId);
356
357 // Skip if it's not used.
358 if (!ConfigOps.getRuleSeverity(ruleConfig)) {
359 continue;
360 }
361 const rule = getRule(ruleId, usedConfigArrays);
362
363 // Skip if it's not deprecated.
364 if (!(rule && rule.meta && rule.meta.deprecated)) {
365 continue;
366 }
367
368 // This rule was used and deprecated.
369 yield {
370 ruleId,
371 replacedBy: rule.meta.replacedBy || []
372 };
373 }
374 }
375}
376
377/**
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.
381 * @private
382 */
383function isErrorMessage(message) {
384 return message.severity === 2;
385}
386
387
388/**
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`
392 *
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
397 */
398function getCacheFile(cacheFile, cwd) {
399
400 /*
401 * make sure the path separators are normalized for the environment/os
402 * keeping the trailing path separator if present
403 */
404 const normalizedCacheFile = path.normalize(cacheFile);
405
406 const resolvedCacheFile = path.resolve(cwd, normalizedCacheFile);
407 const looksLikeADirectory = normalizedCacheFile.slice(-1) === path.sep;
408
409 /**
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
412 */
413 function getCacheFileForDirectory() {
414 return path.join(resolvedCacheFile, `.cache_${hash(cwd)}`);
415 }
416
417 let fileStats;
418
419 try {
420 fileStats = fs.lstatSync(resolvedCacheFile);
421 } catch {
422 fileStats = null;
423 }
424
425
426 /*
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
430 */
431 if (fileStats) {
432
433 /*
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
437 */
438 if (fileStats.isDirectory() || looksLikeADirectory) {
439 return getCacheFileForDirectory();
440 }
441
442 // is file so just use that file
443 return resolvedCacheFile;
444 }
445
446 /*
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.
450 */
451
452 // if the last character passed is a path separator we assume is a directory
453 if (looksLikeADirectory) {
454 return getCacheFileForDirectory();
455 }
456
457 return resolvedCacheFile;
458}
459
460/**
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.
466 */
467function toBooleanMap(keys, defaultValue, displayName) {
468 if (keys && !Array.isArray(keys)) {
469 throw new Error(`${displayName} must be an array.`);
470 }
471 if (keys && keys.length > 0) {
472 return keys.reduce((map, def) => {
473 const [key, value] = def.split(":");
474
475 if (key !== "__proto__") {
476 map[key] = value === void 0
477 ? defaultValue
478 : value === "true";
479 }
480
481 return map;
482 }, {});
483 }
484 return void 0;
485}
486
487/**
488 * Create a config data from CLI options.
489 * @param {CLIEngineOptions} options The options
490 * @returns {ConfigData|null} The created config data.
491 */
492function createConfigDataFromOptions(options) {
493 const {
494 ignorePattern,
495 parser,
496 parserOptions,
497 plugins,
498 rules
499 } = options;
500 const env = toBooleanMap(options.envs, true, "envs");
501 const globals = toBooleanMap(options.globals, false, "globals");
502
503 if (
504 env === void 0 &&
505 globals === void 0 &&
506 (ignorePattern === void 0 || ignorePattern.length === 0) &&
507 parser === void 0 &&
508 parserOptions === void 0 &&
509 plugins === void 0 &&
510 rules === void 0
511 ) {
512 return null;
513 }
514 return {
515 env,
516 globals,
517 ignorePatterns: ignorePattern,
518 parser,
519 parserOptions,
520 plugins,
521 rules
522 };
523}
524
525/**
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
529 */
530function directoryExists(resolvedPath) {
531 try {
532 return fs.statSync(resolvedPath).isDirectory();
533 } catch (error) {
534 if (error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
535 return false;
536 }
537 throw error;
538 }
539}
540
541//------------------------------------------------------------------------------
542// Public Interface
543//------------------------------------------------------------------------------
544
545class CLIEngine {
546
547 /**
548 * Creates a new instance of the core CLI engine.
549 * @param {CLIEngineOptions} providedOptions The options for this instance.
550 */
551 constructor(providedOptions) {
552 const options = Object.assign(
553 Object.create(null),
554 defaultOptions,
555 { cwd: process.cwd() },
556 providedOptions
557 );
558
559 if (options.fix === void 0) {
560 options.fix = false;
561 }
562
563 const additionalPluginPool = new Map();
564 const cacheFilePath = getCacheFile(
565 options.cacheLocation || options.cacheFile,
566 options.cwd
567 );
568 const configArrayFactory = new CascadingConfigArrayFactory({
569 additionalPluginPool,
570 baseConfig: options.baseConfig || null,
571 cliConfig: createConfigDataFromOptions(options),
572 cwd: options.cwd,
573 ignorePath: options.ignorePath,
574 resolvePluginsRelativeTo: options.resolvePluginsRelativeTo,
575 rulePaths: options.rulePaths,
576 specificConfigPath: options.configFile,
577 useEslintrc: options.useEslintrc,
578 builtInRules,
579 loadRules,
580 eslintRecommendedPath: path.resolve(__dirname, "../../conf/eslint-recommended.js"),
581 eslintAllPath: path.resolve(__dirname, "../../conf/eslint-all.js")
582 });
583 const fileEnumerator = new FileEnumerator({
584 configArrayFactory,
585 cwd: options.cwd,
586 extensions: options.extensions,
587 globInputPaths: options.globInputPaths,
588 errorOnUnmatchedPattern: options.errorOnUnmatchedPattern,
589 ignore: options.ignore
590 });
591 const lintResultCache =
592 options.cache ? new LintResultCache(cacheFilePath, options.cacheStrategy) : null;
593 const linter = new Linter({ cwd: options.cwd });
594
595 /** @type {ConfigArray[]} */
596 const lastConfigArrays = [configArrayFactory.getConfigArrayForFile()];
597
598 // Store private data.
599 internalSlotsMap.set(this, {
600 additionalPluginPool,
601 cacheFilePath,
602 configArrayFactory,
603 defaultIgnores: IgnorePattern.createDefaultIgnore(options.cwd),
604 fileEnumerator,
605 lastConfigArrays,
606 lintResultCache,
607 linter,
608 options
609 });
610
611 // setup special filter for fixes
612 if (options.fix && options.fixTypes && options.fixTypes.length > 0) {
613 debug(`Using fix types ${options.fixTypes}`);
614
615 // throw an error if any invalid fix types are found
616 validateFixTypes(options.fixTypes);
617
618 // convert to Set for faster lookup
619 const fixTypes = new Set(options.fixTypes);
620
621 // save original value of options.fix in case it's a function
622 const originalFix = (typeof options.fix === "function")
623 ? options.fix : () => true;
624
625 options.fix = message => {
626 const rule = message.ruleId && getRule(message.ruleId, lastConfigArrays);
627 const matches = rule && rule.meta && fixTypes.has(rule.meta.type);
628
629 return matches && originalFix(message);
630 };
631 }
632 }
633
634 getRules() {
635 const { lastConfigArrays } = internalSlotsMap.get(this);
636
637 return new Map(function *() {
638 yield* builtInRules;
639
640 for (const configArray of lastConfigArrays) {
641 yield* configArray.pluginRules;
642 }
643 }());
644 }
645
646 /**
647 * Returns results that only contains errors.
648 * @param {LintResult[]} results The results to filter.
649 * @returns {LintResult[]} The filtered results.
650 */
651 static getErrorResults(results) {
652 const filtered = [];
653
654 results.forEach(result => {
655 const filteredMessages = result.messages.filter(isErrorMessage);
656
657 if (filteredMessages.length > 0) {
658 filtered.push({
659 ...result,
660 messages: filteredMessages,
661 errorCount: filteredMessages.length,
662 warningCount: 0,
663 fixableErrorCount: result.fixableErrorCount,
664 fixableWarningCount: 0
665 });
666 }
667 });
668
669 return filtered;
670 }
671
672 /**
673 * Outputs fixes from the given results to files.
674 * @param {LintReport} report The report object created by CLIEngine.
675 * @returns {void}
676 */
677 static outputFixes(report) {
678 report.results.filter(result => Object.prototype.hasOwnProperty.call(result, "output")).forEach(result => {
679 fs.writeFileSync(result.filePath, result.output);
680 });
681 }
682
683
684 /**
685 * Add a plugin by passing its configuration
686 * @param {string} name Name of the plugin.
687 * @param {Plugin} pluginObject Plugin configuration object.
688 * @returns {void}
689 */
690 addPlugin(name, pluginObject) {
691 const {
692 additionalPluginPool,
693 configArrayFactory,
694 lastConfigArrays
695 } = internalSlotsMap.get(this);
696
697 additionalPluginPool.set(name, pluginObject);
698 configArrayFactory.clearCache();
699 lastConfigArrays.length = 1;
700 lastConfigArrays[0] = configArrayFactory.getConfigArrayForFile();
701 }
702
703 /**
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.
708 */
709 resolveFileGlobPatterns(patterns) {
710 const { options } = internalSlotsMap.get(this);
711
712 if (options.globInputPaths === false) {
713 return patterns.filter(Boolean);
714 }
715
716 const extensions = (options.extensions || [".js"]).map(ext => ext.replace(/^\./u, ""));
717 const dirSuffix = `/**/*.{${extensions.join(",")}}`;
718
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
723 : pathname;
724
725 return path.normalize(newPath).replace(/\\/gu, "/");
726 });
727 }
728
729 /**
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.
733 */
734 executeOnFiles(patterns) {
735 const {
736 cacheFilePath,
737 fileEnumerator,
738 lastConfigArrays,
739 lintResultCache,
740 linter,
741 options: {
742 allowInlineConfig,
743 cache,
744 cwd,
745 fix,
746 reportUnusedDisableDirectives
747 }
748 } = internalSlotsMap.get(this);
749 const results = [];
750 const startTime = Date.now();
751
752 // Clear the last used config arrays.
753 lastConfigArrays.length = 0;
754
755 // Delete cache file; should this do here?
756 if (!cache) {
757 try {
758 fs.unlinkSync(cacheFilePath);
759 } catch (error) {
760 const errorCode = error && error.code;
761
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))) {
764 throw error;
765 }
766 }
767 }
768
769 // Iterate source code files.
770 for (const { config, filePath, ignored } of fileEnumerator.iterateFiles(patterns)) {
771 if (ignored) {
772 results.push(createIgnoreResult(filePath, cwd));
773 continue;
774 }
775
776 /*
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.
781 */
782 if (!lastConfigArrays.includes(config)) {
783 lastConfigArrays.push(config);
784 }
785
786 // Skip if there is cached result.
787 if (lintResultCache) {
788 const cachedResult =
789 lintResultCache.getCachedLintResults(filePath, config);
790
791 if (cachedResult) {
792 const hadMessages =
793 cachedResult.messages &&
794 cachedResult.messages.length > 0;
795
796 if (hadMessages && fix) {
797 debug(`Reprocessing cached file to allow autofix: ${filePath}`);
798 } else {
799 debug(`Skipping file since it hasn't changed: ${filePath}`);
800 results.push(cachedResult);
801 continue;
802 }
803 }
804 }
805
806 // Do lint.
807 const result = verifyText({
808 text: fs.readFileSync(filePath, "utf8"),
809 filePath,
810 config,
811 cwd,
812 fix,
813 allowInlineConfig,
814 reportUnusedDisableDirectives,
815 fileEnumerator,
816 linter
817 });
818
819 results.push(result);
820
821 /*
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.
826 */
827 if (lintResultCache) {
828 lintResultCache.setCachedLintResults(filePath, config, result);
829 }
830 }
831
832 // Persist the cache to disk.
833 if (lintResultCache) {
834 lintResultCache.reconcile();
835 }
836
837 debug(`Linting complete in: ${Date.now() - startTime}ms`);
838 let usedDeprecatedRules;
839
840 return {
841 results,
842 ...calculateStatsPerRun(results),
843
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)
849 );
850 }
851 return usedDeprecatedRules;
852 }
853 };
854 }
855
856 /**
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.
862 */
863 executeOnText(text, filename, warnIgnored) {
864 const {
865 configArrayFactory,
866 fileEnumerator,
867 lastConfigArrays,
868 linter,
869 options: {
870 allowInlineConfig,
871 cwd,
872 fix,
873 reportUnusedDisableDirectives
874 }
875 } = internalSlotsMap.get(this);
876 const results = [];
877 const startTime = Date.now();
878 const resolvedFilename = filename && path.resolve(cwd, filename);
879
880
881 // Clear the last used config arrays.
882 lastConfigArrays.length = 0;
883 if (resolvedFilename && this.isPathIgnored(resolvedFilename)) {
884 if (warnIgnored) {
885 results.push(createIgnoreResult(resolvedFilename, cwd));
886 }
887 } else {
888 const config = configArrayFactory.getConfigArrayForFile(
889 resolvedFilename || "__placeholder__.js"
890 );
891
892 /*
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.
897 */
898 lastConfigArrays.push(config);
899
900 // Do lint.
901 results.push(verifyText({
902 text,
903 filePath: resolvedFilename,
904 config,
905 cwd,
906 fix,
907 allowInlineConfig,
908 reportUnusedDisableDirectives,
909 fileEnumerator,
910 linter
911 }));
912 }
913
914 debug(`Linting complete in: ${Date.now() - startTime}ms`);
915 let usedDeprecatedRules;
916
917 return {
918 results,
919 ...calculateStatsPerRun(results),
920
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)
926 );
927 }
928 return usedDeprecatedRules;
929 }
930 };
931 }
932
933 /**
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.
939 */
940 getConfigForFile(filePath) {
941 const { configArrayFactory, options } = internalSlotsMap.get(this);
942 const absolutePath = path.resolve(options.cwd, filePath);
943
944 if (directoryExists(absolutePath)) {
945 throw Object.assign(
946 new Error("'filePath' should not be a directory path."),
947 { messageTemplate: "print-config-with-directory-path" }
948 );
949 }
950
951 return configArrayFactory
952 .getConfigArrayForFile(absolutePath)
953 .extractConfig(absolutePath)
954 .toCompatibleObjectAsConfigFileContent();
955 }
956
957 /**
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.
961 */
962 isPathIgnored(filePath) {
963 const {
964 configArrayFactory,
965 defaultIgnores,
966 options: { cwd, ignore }
967 } = internalSlotsMap.get(this);
968 const absolutePath = path.resolve(cwd, filePath);
969
970 if (ignore) {
971 const config = configArrayFactory
972 .getConfigArrayForFile(absolutePath)
973 .extractConfig(absolutePath);
974 const ignores = config.ignores || defaultIgnores;
975
976 return ignores(absolutePath);
977 }
978
979 return defaultIgnores(absolutePath);
980 }
981
982 /**
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
985 * custom formatter.
986 * @returns {(Function|null)} The formatter function or null if the `format` is not a string.
987 */
988 getFormatter(format) {
989
990 // default is stylish
991 const resolvedFormatName = format || "stylish";
992
993 // only strings are valid formatters
994 if (typeof resolvedFormatName === "string") {
995
996 // replace \ with / for Windows compatibility
997 const normalizedFormatName = resolvedFormatName.replace(/\\/gu, "/");
998
999 const slots = internalSlotsMap.get(this);
1000 const cwd = slots ? slots.options.cwd : process.cwd();
1001 const namespace = naming.getNamespaceFromTerm(normalizedFormatName);
1002
1003 let formatterPath;
1004
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);
1008 } else {
1009 try {
1010 const npmFormat = naming.normalizePackageName(normalizedFormatName, "eslint-formatter");
1011
1012 formatterPath = ModuleResolver.resolve(npmFormat, path.join(cwd, "__placeholder__.js"));
1013 } catch {
1014 formatterPath = path.resolve(__dirname, "formatters", normalizedFormatName);
1015 }
1016 }
1017
1018 try {
1019 return require(formatterPath);
1020 } catch (ex) {
1021 ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`;
1022 throw ex;
1023 }
1024
1025 } else {
1026 return null;
1027 }
1028 }
1029}
1030
1031CLIEngine.version = pkg.version;
1032CLIEngine.getFormatter = CLIEngine.prototype.getFormatter;
1033
1034module.exports = {
1035 CLIEngine,
1036
1037 /**
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.
1041 */
1042 getCLIEngineInternalSlots(instance) {
1043 return internalSlotsMap.get(instance);
1044 }
1045};