cli-engine.js 37 KB

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