cli-engine.js 35 KB

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