Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1045 строки
36 KiB

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