cli-engine.js 33 KB

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