source: imaps-frontend/node_modules/eslint/lib/cli-engine/cli-engine.js@ d565449

main
Last change on this file since d565449 was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

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