cli-engine.js 35 KB

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