cli-engine.js 37 KB

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