cli-engine.js 37 KB

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