flat-eslint.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. /**
  2. * @fileoverview Main class using flat config
  3. * @author Nicholas C. Zakas
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. // Note: Node.js 12 does not support fs/promises.
  10. const fs = require("fs").promises;
  11. const path = require("path");
  12. const findUp = require("find-up");
  13. const { version } = require("../../package.json");
  14. const { Linter } = require("../linter");
  15. const { getRuleFromConfig } = require("../config/flat-config-helpers");
  16. const {
  17. Legacy: {
  18. ConfigOps: {
  19. getRuleSeverity
  20. },
  21. ModuleResolver,
  22. naming
  23. }
  24. } = require("@eslint/eslintrc");
  25. const {
  26. findFiles,
  27. getCacheFile,
  28. isNonEmptyString,
  29. isArrayOfNonEmptyString,
  30. createIgnoreResult,
  31. isErrorMessage,
  32. processOptions
  33. } = require("./eslint-helpers");
  34. const { pathToFileURL } = require("url");
  35. const { FlatConfigArray } = require("../config/flat-config-array");
  36. const LintResultCache = require("../cli-engine/lint-result-cache");
  37. /*
  38. * This is necessary to allow overwriting writeFile for testing purposes.
  39. * We can just use fs/promises once we drop Node.js 12 support.
  40. */
  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").ResultsMeta} ResultsMeta */
  51. /** @typedef {import("../shared/types").RuleConf} RuleConf */
  52. /** @typedef {import("../shared/types").Rule} Rule */
  53. /** @typedef {ReturnType<ConfigArray.extractConfig>} ExtractedConfig */
  54. /**
  55. * The options with which to configure the ESLint instance.
  56. * @typedef {Object} FlatESLintOptions
  57. * @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments.
  58. * @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this instance
  59. * @property {boolean} [cache] Enable result caching.
  60. * @property {string} [cacheLocation] The cache file to use instead of .eslintcache.
  61. * @property {"metadata" | "content"} [cacheStrategy] The strategy used to detect changed files.
  62. * @property {string} [cwd] The value to use for the current working directory.
  63. * @property {boolean} [errorOnUnmatchedPattern] If `false` then `ESLint#lintFiles()` doesn't throw even if no target files found. Defaults to `true`.
  64. * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean.
  65. * @property {string[]} [fixTypes] Array of rule types to apply fixes for.
  66. * @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.
  67. * @property {boolean} [ignore] False disables all ignore patterns except for the default ones.
  68. * @property {string[]} [ignorePatterns] Ignore file patterns to use in addition to config ignores.
  69. * @property {ConfigData} [overrideConfig] Override config object, overrides all configs used with this instance
  70. * @property {boolean|string} [overrideConfigFile] Searches for default config file when falsy;
  71. * doesn't do any config file lookup when `true`; considered to be a config filename
  72. * when a string.
  73. * @property {Record<string,Plugin>} [plugins] An array of plugin implementations.
  74. * @property {"error" | "warn" | "off"} [reportUnusedDisableDirectives] the severity to report unused eslint-disable directives.
  75. */
  76. //------------------------------------------------------------------------------
  77. // Helpers
  78. //------------------------------------------------------------------------------
  79. const FLAT_CONFIG_FILENAME = "eslint.config.js";
  80. const debug = require("debug")("eslint:flat-eslint");
  81. const removedFormatters = new Set(["table", "codeframe"]);
  82. const privateMembers = new WeakMap();
  83. const importedConfigFileModificationTime = new Map();
  84. /**
  85. * It will calculate the error and warning count for collection of messages per file
  86. * @param {LintMessage[]} messages Collection of messages
  87. * @returns {Object} Contains the stats
  88. * @private
  89. */
  90. function calculateStatsPerFile(messages) {
  91. return messages.reduce((stat, message) => {
  92. if (message.fatal || message.severity === 2) {
  93. stat.errorCount++;
  94. if (message.fatal) {
  95. stat.fatalErrorCount++;
  96. }
  97. if (message.fix) {
  98. stat.fixableErrorCount++;
  99. }
  100. } else {
  101. stat.warningCount++;
  102. if (message.fix) {
  103. stat.fixableWarningCount++;
  104. }
  105. }
  106. return stat;
  107. }, {
  108. errorCount: 0,
  109. fatalErrorCount: 0,
  110. warningCount: 0,
  111. fixableErrorCount: 0,
  112. fixableWarningCount: 0
  113. });
  114. }
  115. /**
  116. * It will calculate the error and warning count for collection of results from all files
  117. * @param {LintResult[]} results Collection of messages from all the files
  118. * @returns {Object} Contains the stats
  119. * @private
  120. */
  121. function calculateStatsPerRun(results) {
  122. return results.reduce((stat, result) => {
  123. stat.errorCount += result.errorCount;
  124. stat.fatalErrorCount += result.fatalErrorCount;
  125. stat.warningCount += result.warningCount;
  126. stat.fixableErrorCount += result.fixableErrorCount;
  127. stat.fixableWarningCount += result.fixableWarningCount;
  128. return stat;
  129. }, {
  130. errorCount: 0,
  131. fatalErrorCount: 0,
  132. warningCount: 0,
  133. fixableErrorCount: 0,
  134. fixableWarningCount: 0
  135. });
  136. }
  137. /**
  138. * Create rulesMeta object.
  139. * @param {Map<string,Rule>} rules a map of rules from which to generate the object.
  140. * @returns {Object} metadata for all enabled rules.
  141. */
  142. function createRulesMeta(rules) {
  143. return Array.from(rules).reduce((retVal, [id, rule]) => {
  144. retVal[id] = rule.meta;
  145. return retVal;
  146. }, {});
  147. }
  148. /**
  149. * Return the absolute path of a file named `"__placeholder__.js"` in a given directory.
  150. * This is used as a replacement for a missing file path.
  151. * @param {string} cwd An absolute directory path.
  152. * @returns {string} The absolute path of a file named `"__placeholder__.js"` in the given directory.
  153. */
  154. function getPlaceholderPath(cwd) {
  155. return path.join(cwd, "__placeholder__.js");
  156. }
  157. /** @type {WeakMap<ExtractedConfig, DeprecatedRuleInfo[]>} */
  158. const usedDeprecatedRulesCache = new WeakMap();
  159. /**
  160. * Create used deprecated rule list.
  161. * @param {CLIEngine} eslint The CLIEngine instance.
  162. * @param {string} maybeFilePath The absolute path to a lint target file or `"<text>"`.
  163. * @returns {DeprecatedRuleInfo[]} The used deprecated rule list.
  164. */
  165. function getOrFindUsedDeprecatedRules(eslint, maybeFilePath) {
  166. const {
  167. configs,
  168. options: { cwd }
  169. } = privateMembers.get(eslint);
  170. const filePath = path.isAbsolute(maybeFilePath)
  171. ? maybeFilePath
  172. : getPlaceholderPath(cwd);
  173. const config = configs.getConfig(filePath);
  174. // Most files use the same config, so cache it.
  175. if (config && !usedDeprecatedRulesCache.has(config)) {
  176. const retv = [];
  177. if (config.rules) {
  178. for (const [ruleId, ruleConf] of Object.entries(config.rules)) {
  179. if (getRuleSeverity(ruleConf) === 0) {
  180. continue;
  181. }
  182. const rule = getRuleFromConfig(ruleId, config);
  183. const meta = rule && rule.meta;
  184. if (meta && meta.deprecated) {
  185. retv.push({ ruleId, replacedBy: meta.replacedBy || [] });
  186. }
  187. }
  188. }
  189. usedDeprecatedRulesCache.set(config, Object.freeze(retv));
  190. }
  191. return config ? usedDeprecatedRulesCache.get(config) : Object.freeze([]);
  192. }
  193. /**
  194. * Processes the linting results generated by a CLIEngine linting report to
  195. * match the ESLint class's API.
  196. * @param {CLIEngine} eslint The CLIEngine instance.
  197. * @param {CLIEngineLintReport} report The CLIEngine linting report to process.
  198. * @returns {LintResult[]} The processed linting results.
  199. */
  200. function processLintReport(eslint, { results }) {
  201. const descriptor = {
  202. configurable: true,
  203. enumerable: true,
  204. get() {
  205. return getOrFindUsedDeprecatedRules(eslint, this.filePath);
  206. }
  207. };
  208. for (const result of results) {
  209. Object.defineProperty(result, "usedDeprecatedRules", descriptor);
  210. }
  211. return results;
  212. }
  213. /**
  214. * An Array.prototype.sort() compatible compare function to order results by their file path.
  215. * @param {LintResult} a The first lint result.
  216. * @param {LintResult} b The second lint result.
  217. * @returns {number} An integer representing the order in which the two results should occur.
  218. */
  219. function compareResultsByFilePath(a, b) {
  220. if (a.filePath < b.filePath) {
  221. return -1;
  222. }
  223. if (a.filePath > b.filePath) {
  224. return 1;
  225. }
  226. return 0;
  227. }
  228. /**
  229. * Searches from the current working directory up until finding the
  230. * given flat config filename.
  231. * @param {string} cwd The current working directory to search from.
  232. * @returns {Promise<string|null>} The filename if found or `null` if not.
  233. */
  234. function findFlatConfigFile(cwd) {
  235. return findUp(
  236. FLAT_CONFIG_FILENAME,
  237. { cwd }
  238. );
  239. }
  240. /**
  241. * Load the config array from the given filename.
  242. * @param {string} filePath The filename to load from.
  243. * @returns {Promise<any>} The config loaded from the config file.
  244. */
  245. async function loadFlatConfigFile(filePath) {
  246. debug(`Loading config from ${filePath}`);
  247. const fileURL = pathToFileURL(filePath);
  248. debug(`Config file URL is ${fileURL}`);
  249. const mtime = (await fs.stat(filePath)).mtime.getTime();
  250. /*
  251. * Append a query with the config file's modification time (`mtime`) in order
  252. * to import the current version of the config file. Without the query, `import()` would
  253. * cache the config file module by the pathname only, and then always return
  254. * the same version (the one that was actual when the module was imported for the first time).
  255. *
  256. * This ensures that the config file module is loaded and executed again
  257. * if it has been changed since the last time it was imported.
  258. * If it hasn't been changed, `import()` will just return the cached version.
  259. *
  260. * Note that we should not overuse queries (e.g., by appending the current time
  261. * to always reload the config file module) as that could cause memory leaks
  262. * because entries are never removed from the import cache.
  263. */
  264. fileURL.searchParams.append("mtime", mtime);
  265. /*
  266. * With queries, we can bypass the import cache. However, when import-ing a CJS module,
  267. * Node.js uses the require infrastructure under the hood. That includes the require cache,
  268. * which caches the config file module by its file path (queries have no effect).
  269. * Therefore, we also need to clear the require cache before importing the config file module.
  270. * In order to get the same behavior with ESM and CJS config files, in particular - to reload
  271. * the config file only if it has been changed, we track file modification times and clear
  272. * the require cache only if the file has been changed.
  273. */
  274. if (importedConfigFileModificationTime.get(filePath) !== mtime) {
  275. delete require.cache[filePath];
  276. }
  277. const config = (await import(fileURL)).default;
  278. importedConfigFileModificationTime.set(filePath, mtime);
  279. return config;
  280. }
  281. /**
  282. * Calculates the config array for this run based on inputs.
  283. * @param {FlatESLint} eslint The instance to create the config array for.
  284. * @param {import("./eslint").ESLintOptions} options The ESLint instance options.
  285. * @returns {FlatConfigArray} The config array for `eslint``.
  286. */
  287. async function calculateConfigArray(eslint, {
  288. cwd,
  289. baseConfig,
  290. overrideConfig,
  291. configFile,
  292. ignore: shouldIgnore,
  293. ignorePatterns
  294. }) {
  295. // check for cached instance
  296. const slots = privateMembers.get(eslint);
  297. if (slots.configs) {
  298. return slots.configs;
  299. }
  300. // determine where to load config file from
  301. let configFilePath;
  302. let basePath = cwd;
  303. if (typeof configFile === "string") {
  304. debug(`Override config file path is ${configFile}`);
  305. configFilePath = path.resolve(cwd, configFile);
  306. } else if (configFile !== false) {
  307. debug("Searching for eslint.config.js");
  308. configFilePath = await findFlatConfigFile(cwd);
  309. if (!configFilePath) {
  310. throw new Error("Could not find config file.");
  311. }
  312. basePath = path.resolve(path.dirname(configFilePath));
  313. }
  314. const configs = new FlatConfigArray(baseConfig || [], { basePath, shouldIgnore });
  315. // load config file
  316. if (configFilePath) {
  317. const fileConfig = await loadFlatConfigFile(configFilePath);
  318. if (Array.isArray(fileConfig)) {
  319. configs.push(...fileConfig);
  320. } else {
  321. configs.push(fileConfig);
  322. }
  323. }
  324. // add in any configured defaults
  325. configs.push(...slots.defaultConfigs);
  326. let allIgnorePatterns = [];
  327. // append command line ignore patterns
  328. if (ignorePatterns) {
  329. if (typeof ignorePatterns === "string") {
  330. allIgnorePatterns.push(ignorePatterns);
  331. } else {
  332. allIgnorePatterns.push(...ignorePatterns);
  333. }
  334. }
  335. /*
  336. * If the config file basePath is different than the cwd, then
  337. * the ignore patterns won't work correctly. Here, we adjust the
  338. * ignore pattern to include the correct relative path. Patterns
  339. * loaded from ignore files are always relative to the cwd, whereas
  340. * the config file basePath can be an ancestor of the cwd.
  341. */
  342. if (basePath !== cwd && allIgnorePatterns.length) {
  343. const relativeIgnorePath = path.relative(basePath, cwd);
  344. allIgnorePatterns = allIgnorePatterns.map(pattern => {
  345. const negated = pattern.startsWith("!");
  346. const basePattern = negated ? pattern.slice(1) : pattern;
  347. return (negated ? "!" : "") +
  348. path.posix.join(relativeIgnorePath, basePattern);
  349. });
  350. }
  351. if (allIgnorePatterns.length) {
  352. /*
  353. * Ignore patterns are added to the end of the config array
  354. * so they can override default ignores.
  355. */
  356. configs.push({
  357. ignores: allIgnorePatterns
  358. });
  359. }
  360. if (overrideConfig) {
  361. if (Array.isArray(overrideConfig)) {
  362. configs.push(...overrideConfig);
  363. } else {
  364. configs.push(overrideConfig);
  365. }
  366. }
  367. await configs.normalize();
  368. // cache the config array for this instance
  369. slots.configs = configs;
  370. return configs;
  371. }
  372. /**
  373. * Processes an source code using ESLint.
  374. * @param {Object} config The config object.
  375. * @param {string} config.text The source code to verify.
  376. * @param {string} config.cwd The path to the current working directory.
  377. * @param {string|undefined} config.filePath The path to the file of `text`. If this is undefined, it uses `<text>`.
  378. * @param {FlatConfigArray} config.configs The config.
  379. * @param {boolean} config.fix If `true` then it does fix.
  380. * @param {boolean} config.allowInlineConfig If `true` then it uses directive comments.
  381. * @param {boolean} config.reportUnusedDisableDirectives If `true` then it reports unused `eslint-disable` comments.
  382. * @param {Linter} config.linter The linter instance to verify.
  383. * @returns {LintResult} The result of linting.
  384. * @private
  385. */
  386. function verifyText({
  387. text,
  388. cwd,
  389. filePath: providedFilePath,
  390. configs,
  391. fix,
  392. allowInlineConfig,
  393. reportUnusedDisableDirectives,
  394. linter
  395. }) {
  396. const filePath = providedFilePath || "<text>";
  397. debug(`Lint ${filePath}`);
  398. /*
  399. * Verify.
  400. * `config.extractConfig(filePath)` requires an absolute path, but `linter`
  401. * doesn't know CWD, so it gives `linter` an absolute path always.
  402. */
  403. const filePathToVerify = filePath === "<text>" ? getPlaceholderPath(cwd) : filePath;
  404. const { fixed, messages, output } = linter.verifyAndFix(
  405. text,
  406. configs,
  407. {
  408. allowInlineConfig,
  409. filename: filePathToVerify,
  410. fix,
  411. reportUnusedDisableDirectives,
  412. /**
  413. * Check if the linter should adopt a given code block or not.
  414. * @param {string} blockFilename The virtual filename of a code block.
  415. * @returns {boolean} `true` if the linter should adopt the code block.
  416. */
  417. filterCodeBlock(blockFilename) {
  418. return configs.isExplicitMatch(blockFilename);
  419. }
  420. }
  421. );
  422. // Tweak and return.
  423. const result = {
  424. filePath: filePath === "<text>" ? filePath : path.resolve(filePath),
  425. messages,
  426. suppressedMessages: linter.getSuppressedMessages(),
  427. ...calculateStatsPerFile(messages)
  428. };
  429. if (fixed) {
  430. result.output = output;
  431. }
  432. if (
  433. result.errorCount + result.warningCount > 0 &&
  434. typeof result.output === "undefined"
  435. ) {
  436. result.source = text;
  437. }
  438. return result;
  439. }
  440. /**
  441. * Checks whether a message's rule type should be fixed.
  442. * @param {LintMessage} message The message to check.
  443. * @param {FlatConfig} config The config for the file that generated the message.
  444. * @param {string[]} fixTypes An array of fix types to check.
  445. * @returns {boolean} Whether the message should be fixed.
  446. */
  447. function shouldMessageBeFixed(message, config, fixTypes) {
  448. if (!message.ruleId) {
  449. return fixTypes.has("directive");
  450. }
  451. const rule = message.ruleId && getRuleFromConfig(message.ruleId, config);
  452. return Boolean(rule && rule.meta && fixTypes.has(rule.meta.type));
  453. }
  454. /**
  455. * Collect used deprecated rules.
  456. * @param {Array<FlatConfig>} configs The configs to evaluate.
  457. * @returns {IterableIterator<DeprecatedRuleInfo>} Used deprecated rules.
  458. */
  459. function *iterateRuleDeprecationWarnings(configs) {
  460. const processedRuleIds = new Set();
  461. for (const config of configs) {
  462. for (const [ruleId, ruleConfig] of Object.entries(config.rules)) {
  463. // Skip if it was processed.
  464. if (processedRuleIds.has(ruleId)) {
  465. continue;
  466. }
  467. processedRuleIds.add(ruleId);
  468. // Skip if it's not used.
  469. if (!getRuleSeverity(ruleConfig)) {
  470. continue;
  471. }
  472. const rule = getRuleFromConfig(ruleId, config);
  473. // Skip if it's not deprecated.
  474. if (!(rule && rule.meta && rule.meta.deprecated)) {
  475. continue;
  476. }
  477. // This rule was used and deprecated.
  478. yield {
  479. ruleId,
  480. replacedBy: rule.meta.replacedBy || []
  481. };
  482. }
  483. }
  484. }
  485. /**
  486. * Creates an error to be thrown when an array of results passed to `getRulesMetaForResults` was not created by the current engine.
  487. * @returns {TypeError} An error object.
  488. */
  489. function createExtraneousResultsError() {
  490. return new TypeError("Results object was not created from this ESLint instance.");
  491. }
  492. //-----------------------------------------------------------------------------
  493. // Main API
  494. //-----------------------------------------------------------------------------
  495. /**
  496. * Primary Node.js API for ESLint.
  497. */
  498. class FlatESLint {
  499. /**
  500. * Creates a new instance of the main ESLint API.
  501. * @param {FlatESLintOptions} options The options for this instance.
  502. */
  503. constructor(options = {}) {
  504. const defaultConfigs = [];
  505. const processedOptions = processOptions(options);
  506. const linter = new Linter({
  507. cwd: processedOptions.cwd,
  508. configType: "flat"
  509. });
  510. const cacheFilePath = getCacheFile(
  511. processedOptions.cacheLocation,
  512. processedOptions.cwd
  513. );
  514. const lintResultCache = processedOptions.cache
  515. ? new LintResultCache(cacheFilePath, processedOptions.cacheStrategy)
  516. : null;
  517. privateMembers.set(this, {
  518. options: processedOptions,
  519. linter,
  520. cacheFilePath,
  521. lintResultCache,
  522. defaultConfigs,
  523. defaultIgnores: () => false,
  524. configs: null
  525. });
  526. /**
  527. * If additional plugins are passed in, add that to the default
  528. * configs for this instance.
  529. */
  530. if (options.plugins) {
  531. const plugins = {};
  532. for (const [pluginName, plugin] of Object.entries(options.plugins)) {
  533. plugins[naming.getShorthandName(pluginName, "eslint-plugin")] = plugin;
  534. }
  535. defaultConfigs.push({
  536. plugins
  537. });
  538. }
  539. }
  540. /**
  541. * The version text.
  542. * @type {string}
  543. */
  544. static get version() {
  545. return version;
  546. }
  547. /**
  548. * Outputs fixes from the given results to files.
  549. * @param {LintResult[]} results The lint results.
  550. * @returns {Promise<void>} Returns a promise that is used to track side effects.
  551. */
  552. static async outputFixes(results) {
  553. if (!Array.isArray(results)) {
  554. throw new Error("'results' must be an array");
  555. }
  556. await Promise.all(
  557. results
  558. .filter(result => {
  559. if (typeof result !== "object" || result === null) {
  560. throw new Error("'results' must include only objects");
  561. }
  562. return (
  563. typeof result.output === "string" &&
  564. path.isAbsolute(result.filePath)
  565. );
  566. })
  567. .map(r => fs.writeFile(r.filePath, r.output))
  568. );
  569. }
  570. /**
  571. * Returns results that only contains errors.
  572. * @param {LintResult[]} results The results to filter.
  573. * @returns {LintResult[]} The filtered results.
  574. */
  575. static getErrorResults(results) {
  576. const filtered = [];
  577. results.forEach(result => {
  578. const filteredMessages = result.messages.filter(isErrorMessage);
  579. const filteredSuppressedMessages = result.suppressedMessages.filter(isErrorMessage);
  580. if (filteredMessages.length > 0) {
  581. filtered.push({
  582. ...result,
  583. messages: filteredMessages,
  584. suppressedMessages: filteredSuppressedMessages,
  585. errorCount: filteredMessages.length,
  586. warningCount: 0,
  587. fixableErrorCount: result.fixableErrorCount,
  588. fixableWarningCount: 0
  589. });
  590. }
  591. });
  592. return filtered;
  593. }
  594. /**
  595. * Returns meta objects for each rule represented in the lint results.
  596. * @param {LintResult[]} results The results to fetch rules meta for.
  597. * @returns {Object} A mapping of ruleIds to rule meta objects.
  598. * @throws {TypeError} When the results object wasn't created from this ESLint instance.
  599. * @throws {TypeError} When a plugin or rule is missing.
  600. */
  601. getRulesMetaForResults(results) {
  602. // short-circuit simple case
  603. if (results.length === 0) {
  604. return {};
  605. }
  606. const resultRules = new Map();
  607. const {
  608. configs,
  609. options: { cwd }
  610. } = privateMembers.get(this);
  611. /*
  612. * We can only accurately return rules meta information for linting results if the
  613. * results were created by this instance. Otherwise, the necessary rules data is
  614. * not available. So if the config array doesn't already exist, just throw an error
  615. * to let the user know we can't do anything here.
  616. */
  617. if (!configs) {
  618. throw createExtraneousResultsError();
  619. }
  620. for (const result of results) {
  621. /*
  622. * Normalize filename for <text>.
  623. */
  624. const filePath = result.filePath === "<text>"
  625. ? getPlaceholderPath(cwd) : result.filePath;
  626. const allMessages = result.messages.concat(result.suppressedMessages);
  627. for (const { ruleId } of allMessages) {
  628. if (!ruleId) {
  629. continue;
  630. }
  631. /*
  632. * All of the plugin and rule information is contained within the
  633. * calculated config for the given file.
  634. */
  635. const config = configs.getConfig(filePath);
  636. if (!config) {
  637. throw createExtraneousResultsError();
  638. }
  639. const rule = getRuleFromConfig(ruleId, config);
  640. // ensure the rule exists
  641. if (!rule) {
  642. throw new TypeError(`Could not find the rule "${ruleId}".`);
  643. }
  644. resultRules.set(ruleId, rule);
  645. }
  646. }
  647. return createRulesMeta(resultRules);
  648. }
  649. /**
  650. * Executes the current configuration on an array of file and directory names.
  651. * @param {string|string[]} patterns An array of file and directory names.
  652. * @returns {Promise<LintResult[]>} The results of linting the file patterns given.
  653. */
  654. async lintFiles(patterns) {
  655. if (!isNonEmptyString(patterns) && !isArrayOfNonEmptyString(patterns)) {
  656. throw new Error("'patterns' must be a non-empty string or an array of non-empty strings");
  657. }
  658. const {
  659. cacheFilePath,
  660. lintResultCache,
  661. linter,
  662. options: eslintOptions
  663. } = privateMembers.get(this);
  664. const configs = await calculateConfigArray(this, eslintOptions);
  665. const {
  666. allowInlineConfig,
  667. cache,
  668. cwd,
  669. fix,
  670. fixTypes,
  671. reportUnusedDisableDirectives,
  672. globInputPaths,
  673. errorOnUnmatchedPattern
  674. } = eslintOptions;
  675. const startTime = Date.now();
  676. const usedConfigs = [];
  677. const fixTypesSet = fixTypes ? new Set(fixTypes) : null;
  678. // Delete cache file; should this be done here?
  679. if (!cache && cacheFilePath) {
  680. debug(`Deleting cache file at ${cacheFilePath}`);
  681. try {
  682. await fs.unlink(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" && !(await fs.exists(cacheFilePath)))) {
  687. throw error;
  688. }
  689. }
  690. }
  691. const filePaths = await findFiles({
  692. patterns: typeof patterns === "string" ? [patterns] : patterns,
  693. cwd,
  694. globInputPaths,
  695. configs,
  696. errorOnUnmatchedPattern
  697. });
  698. debug(`${filePaths.length} files found in: ${Date.now() - startTime}ms`);
  699. /*
  700. * Because we need to process multiple files, including reading from disk,
  701. * it is most efficient to start by reading each file via promises so that
  702. * they can be done in parallel. Then, we can lint the returned text. This
  703. * ensures we are waiting the minimum amount of time in between lints.
  704. */
  705. const results = await Promise.all(
  706. filePaths.map(({ filePath, ignored }) => {
  707. /*
  708. * If a filename was entered that matches an ignore
  709. * pattern, then notify the user.
  710. */
  711. if (ignored) {
  712. return createIgnoreResult(filePath, cwd);
  713. }
  714. const config = configs.getConfig(filePath);
  715. /*
  716. * Sometimes a file found through a glob pattern will
  717. * be ignored. In this case, `config` will be undefined
  718. * and we just silently ignore the file.
  719. */
  720. if (!config) {
  721. return void 0;
  722. }
  723. /*
  724. * Store used configs for:
  725. * - this method uses to collect used deprecated rules.
  726. * - `--fix-type` option uses to get the loaded rule's meta data.
  727. */
  728. if (!usedConfigs.includes(config)) {
  729. usedConfigs.push(config);
  730. }
  731. // Skip if there is cached result.
  732. if (lintResultCache) {
  733. const cachedResult =
  734. lintResultCache.getCachedLintResults(filePath, config);
  735. if (cachedResult) {
  736. const hadMessages =
  737. cachedResult.messages &&
  738. cachedResult.messages.length > 0;
  739. if (hadMessages && fix) {
  740. debug(`Reprocessing cached file to allow autofix: ${filePath}`);
  741. } else {
  742. debug(`Skipping file since it hasn't changed: ${filePath}`);
  743. return cachedResult;
  744. }
  745. }
  746. }
  747. // set up fixer for fixTypes if necessary
  748. let fixer = fix;
  749. if (fix && fixTypesSet) {
  750. // save original value of options.fix in case it's a function
  751. const originalFix = (typeof fix === "function")
  752. ? fix : () => true;
  753. fixer = message => shouldMessageBeFixed(message, config, fixTypesSet) && originalFix(message);
  754. }
  755. return fs.readFile(filePath, "utf8")
  756. .then(text => {
  757. // do the linting
  758. const result = verifyText({
  759. text,
  760. filePath,
  761. configs,
  762. cwd,
  763. fix: fixer,
  764. allowInlineConfig,
  765. reportUnusedDisableDirectives,
  766. linter
  767. });
  768. /*
  769. * Store the lint result in the LintResultCache.
  770. * NOTE: The LintResultCache will remove the file source and any
  771. * other properties that are difficult to serialize, and will
  772. * hydrate those properties back in on future lint runs.
  773. */
  774. if (lintResultCache) {
  775. lintResultCache.setCachedLintResults(filePath, config, result);
  776. }
  777. return result;
  778. });
  779. })
  780. );
  781. // Persist the cache to disk.
  782. if (lintResultCache) {
  783. lintResultCache.reconcile();
  784. }
  785. let usedDeprecatedRules;
  786. const finalResults = results.filter(result => !!result);
  787. return processLintReport(this, {
  788. results: finalResults,
  789. ...calculateStatsPerRun(finalResults),
  790. // Initialize it lazily because CLI and `ESLint` API don't use it.
  791. get usedDeprecatedRules() {
  792. if (!usedDeprecatedRules) {
  793. usedDeprecatedRules = Array.from(
  794. iterateRuleDeprecationWarnings(usedConfigs)
  795. );
  796. }
  797. return usedDeprecatedRules;
  798. }
  799. });
  800. }
  801. /**
  802. * Executes the current configuration on text.
  803. * @param {string} code A string of JavaScript code to lint.
  804. * @param {Object} [options] The options.
  805. * @param {string} [options.filePath] The path to the file of the source code.
  806. * @param {boolean} [options.warnIgnored] When set to true, warn if given filePath is an ignored path.
  807. * @returns {Promise<LintResult[]>} The results of linting the string of code given.
  808. */
  809. async lintText(code, options = {}) {
  810. // Parameter validation
  811. if (typeof code !== "string") {
  812. throw new Error("'code' must be a string");
  813. }
  814. if (typeof options !== "object") {
  815. throw new Error("'options' must be an object, null, or undefined");
  816. }
  817. // Options validation
  818. const {
  819. filePath,
  820. warnIgnored = false,
  821. ...unknownOptions
  822. } = options || {};
  823. const unknownOptionKeys = Object.keys(unknownOptions);
  824. if (unknownOptionKeys.length > 0) {
  825. throw new Error(`'options' must not include the unknown option(s): ${unknownOptionKeys.join(", ")}`);
  826. }
  827. if (filePath !== void 0 && !isNonEmptyString(filePath)) {
  828. throw new Error("'options.filePath' must be a non-empty string or undefined");
  829. }
  830. if (typeof warnIgnored !== "boolean") {
  831. throw new Error("'options.warnIgnored' must be a boolean or undefined");
  832. }
  833. // Now we can get down to linting
  834. const {
  835. linter,
  836. options: eslintOptions
  837. } = privateMembers.get(this);
  838. const configs = await calculateConfigArray(this, eslintOptions);
  839. const {
  840. allowInlineConfig,
  841. cwd,
  842. fix,
  843. reportUnusedDisableDirectives
  844. } = eslintOptions;
  845. const results = [];
  846. const startTime = Date.now();
  847. const resolvedFilename = path.resolve(cwd, filePath || "__placeholder__.js");
  848. let config;
  849. // Clear the last used config arrays.
  850. if (resolvedFilename && await this.isPathIgnored(resolvedFilename)) {
  851. if (warnIgnored) {
  852. results.push(createIgnoreResult(resolvedFilename, cwd));
  853. }
  854. } else {
  855. // TODO: Needed?
  856. config = configs.getConfig(resolvedFilename);
  857. // Do lint.
  858. results.push(verifyText({
  859. text: code,
  860. filePath: resolvedFilename.endsWith("__placeholder__.js") ? "<text>" : resolvedFilename,
  861. configs,
  862. cwd,
  863. fix,
  864. allowInlineConfig,
  865. reportUnusedDisableDirectives,
  866. linter
  867. }));
  868. }
  869. debug(`Linting complete in: ${Date.now() - startTime}ms`);
  870. let usedDeprecatedRules;
  871. return processLintReport(this, {
  872. results,
  873. ...calculateStatsPerRun(results),
  874. // Initialize it lazily because CLI and `ESLint` API don't use it.
  875. get usedDeprecatedRules() {
  876. if (!usedDeprecatedRules) {
  877. usedDeprecatedRules = Array.from(
  878. iterateRuleDeprecationWarnings(config)
  879. );
  880. }
  881. return usedDeprecatedRules;
  882. }
  883. });
  884. }
  885. /**
  886. * Returns the formatter representing the given formatter name.
  887. * @param {string} [name] The name of the formatter to load.
  888. * The following values are allowed:
  889. * - `undefined` ... Load `stylish` builtin formatter.
  890. * - A builtin formatter name ... Load the builtin formatter.
  891. * - A third-party formatter name:
  892. * - `foo` → `eslint-formatter-foo`
  893. * - `@foo` → `@foo/eslint-formatter`
  894. * - `@foo/bar` → `@foo/eslint-formatter-bar`
  895. * - A file path ... Load the file.
  896. * @returns {Promise<Formatter>} A promise resolving to the formatter object.
  897. * This promise will be rejected if the given formatter was not found or not
  898. * a function.
  899. */
  900. async loadFormatter(name = "stylish") {
  901. if (typeof name !== "string") {
  902. throw new Error("'name' must be a string");
  903. }
  904. // replace \ with / for Windows compatibility
  905. const normalizedFormatName = name.replace(/\\/gu, "/");
  906. const namespace = naming.getNamespaceFromTerm(normalizedFormatName);
  907. // grab our options
  908. const { cwd } = privateMembers.get(this).options;
  909. let formatterPath;
  910. // if there's a slash, then it's a file (TODO: this check seems dubious for scoped npm packages)
  911. if (!namespace && normalizedFormatName.includes("/")) {
  912. formatterPath = path.resolve(cwd, normalizedFormatName);
  913. } else {
  914. try {
  915. const npmFormat = naming.normalizePackageName(normalizedFormatName, "eslint-formatter");
  916. // TODO: This is pretty dirty...would be nice to clean up at some point.
  917. formatterPath = ModuleResolver.resolve(npmFormat, getPlaceholderPath(cwd));
  918. } catch {
  919. formatterPath = path.resolve(__dirname, "../", "cli-engine", "formatters", `${normalizedFormatName}.js`);
  920. }
  921. }
  922. let formatter;
  923. try {
  924. formatter = (await import(pathToFileURL(formatterPath))).default;
  925. } catch (ex) {
  926. // check for formatters that have been removed
  927. if (removedFormatters.has(name)) {
  928. ex.message = `The ${name} formatter is no longer part of core ESLint. Install it manually with \`npm install -D eslint-formatter-${name}\``;
  929. } else {
  930. ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`;
  931. }
  932. throw ex;
  933. }
  934. if (typeof formatter !== "function") {
  935. throw new TypeError(`Formatter must be a function, but got a ${typeof formatter}.`);
  936. }
  937. const eslint = this;
  938. return {
  939. /**
  940. * The main formatter method.
  941. * @param {LintResults[]} results The lint results to format.
  942. * @param {ResultsMeta} resultsMeta Warning count and max threshold.
  943. * @returns {string} The formatted lint results.
  944. */
  945. format(results, resultsMeta) {
  946. let rulesMeta = null;
  947. results.sort(compareResultsByFilePath);
  948. return formatter(results, {
  949. ...resultsMeta,
  950. cwd,
  951. get rulesMeta() {
  952. if (!rulesMeta) {
  953. rulesMeta = eslint.getRulesMetaForResults(results);
  954. }
  955. return rulesMeta;
  956. }
  957. });
  958. }
  959. };
  960. }
  961. /**
  962. * Returns a configuration object for the given file based on the CLI options.
  963. * This is the same logic used by the ESLint CLI executable to determine
  964. * configuration for each file it processes.
  965. * @param {string} filePath The path of the file to retrieve a config object for.
  966. * @returns {Promise<ConfigData|undefined>} A configuration object for the file
  967. * or `undefined` if there is no configuration data for the object.
  968. */
  969. async calculateConfigForFile(filePath) {
  970. if (!isNonEmptyString(filePath)) {
  971. throw new Error("'filePath' must be a non-empty string");
  972. }
  973. const options = privateMembers.get(this).options;
  974. const absolutePath = path.resolve(options.cwd, filePath);
  975. const configs = await calculateConfigArray(this, options);
  976. return configs.getConfig(absolutePath);
  977. }
  978. /**
  979. * Checks if a given path is ignored by ESLint.
  980. * @param {string} filePath The path of the file to check.
  981. * @returns {Promise<boolean>} Whether or not the given path is ignored.
  982. */
  983. async isPathIgnored(filePath) {
  984. const config = await this.calculateConfigForFile(filePath);
  985. return config === void 0;
  986. }
  987. }
  988. //------------------------------------------------------------------------------
  989. // Public Interface
  990. //------------------------------------------------------------------------------
  991. module.exports = {
  992. FlatESLint,
  993. findFlatConfigFile
  994. };