eslint.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. /**
  2. * @fileoverview Main API Class
  3. * @author Kai Cataldo
  4. * @author Toru Nagashima
  5. */
  6. "use strict";
  7. //------------------------------------------------------------------------------
  8. // Requirements
  9. //------------------------------------------------------------------------------
  10. const path = require("path");
  11. const fs = require("fs");
  12. const { promisify } = require("util");
  13. const { CLIEngine, getCLIEngineInternalSlots } = require("../cli-engine/cli-engine");
  14. const BuiltinRules = require("../rules");
  15. const {
  16. Legacy: {
  17. ConfigOps: {
  18. getRuleSeverity
  19. }
  20. }
  21. } = require("@eslint/eslintrc");
  22. const { version } = require("../../package.json");
  23. //------------------------------------------------------------------------------
  24. // Typedefs
  25. //------------------------------------------------------------------------------
  26. /** @typedef {import("../cli-engine/cli-engine").LintReport} CLIEngineLintReport */
  27. /** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */
  28. /** @typedef {import("../shared/types").ConfigData} ConfigData */
  29. /** @typedef {import("../shared/types").LintMessage} LintMessage */
  30. /** @typedef {import("../shared/types").SuppressedLintMessage} SuppressedLintMessage */
  31. /** @typedef {import("../shared/types").Plugin} Plugin */
  32. /** @typedef {import("../shared/types").Rule} Rule */
  33. /** @typedef {import("../shared/types").LintResult} LintResult */
  34. /** @typedef {import("../shared/types").ResultsMeta} ResultsMeta */
  35. /**
  36. * The main formatter object.
  37. * @typedef LoadedFormatter
  38. * @property {(results: LintResult[], resultsMeta: ResultsMeta) => string | Promise<string>} format format function.
  39. */
  40. /**
  41. * The options with which to configure the ESLint instance.
  42. * @typedef {Object} ESLintOptions
  43. * @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments.
  44. * @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this instance
  45. * @property {boolean} [cache] Enable result caching.
  46. * @property {string} [cacheLocation] The cache file to use instead of .eslintcache.
  47. * @property {"metadata" | "content"} [cacheStrategy] The strategy used to detect changed files.
  48. * @property {string} [cwd] The value to use for the current working directory.
  49. * @property {boolean} [errorOnUnmatchedPattern] If `false` then `ESLint#lintFiles()` doesn't throw even if no target files found. Defaults to `true`.
  50. * @property {string[]} [extensions] An array of file extensions to check.
  51. * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean.
  52. * @property {string[]} [fixTypes] Array of rule types to apply fixes for.
  53. * @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.
  54. * @property {boolean} [ignore] False disables use of .eslintignore.
  55. * @property {string} [ignorePath] The ignore file to use instead of .eslintignore.
  56. * @property {ConfigData} [overrideConfig] Override config object, overrides all configs used with this instance
  57. * @property {string} [overrideConfigFile] The configuration file to use.
  58. * @property {Record<string,Plugin>|null} [plugins] Preloaded plugins. This is a map-like object, keys are plugin IDs and each value is implementation.
  59. * @property {"error" | "warn" | "off"} [reportUnusedDisableDirectives] the severity to report unused eslint-disable directives.
  60. * @property {string} [resolvePluginsRelativeTo] The folder where plugins should be resolved from, defaulting to the CWD.
  61. * @property {string[]} [rulePaths] An array of directories to load custom rules from.
  62. * @property {boolean} [useEslintrc] False disables looking for .eslintrc.* files.
  63. */
  64. /**
  65. * A rules metadata object.
  66. * @typedef {Object} RulesMeta
  67. * @property {string} id The plugin ID.
  68. * @property {Object} definition The plugin definition.
  69. */
  70. /**
  71. * Private members for the `ESLint` instance.
  72. * @typedef {Object} ESLintPrivateMembers
  73. * @property {CLIEngine} cliEngine The wrapped CLIEngine instance.
  74. * @property {ESLintOptions} options The options used to instantiate the ESLint instance.
  75. */
  76. //------------------------------------------------------------------------------
  77. // Helpers
  78. //------------------------------------------------------------------------------
  79. const writeFile = promisify(fs.writeFile);
  80. /**
  81. * The map with which to store private class members.
  82. * @type {WeakMap<ESLint, ESLintPrivateMembers>}
  83. */
  84. const privateMembersMap = new WeakMap();
  85. /**
  86. * Check if a given value is a non-empty string or not.
  87. * @param {any} x The value to check.
  88. * @returns {boolean} `true` if `x` is a non-empty string.
  89. */
  90. function isNonEmptyString(x) {
  91. return typeof x === "string" && x.trim() !== "";
  92. }
  93. /**
  94. * Check if a given value is an array of non-empty strings or not.
  95. * @param {any} x The value to check.
  96. * @returns {boolean} `true` if `x` is an array of non-empty strings.
  97. */
  98. function isArrayOfNonEmptyString(x) {
  99. return Array.isArray(x) && x.every(isNonEmptyString);
  100. }
  101. /**
  102. * Check if a given value is a valid fix type or not.
  103. * @param {any} x The value to check.
  104. * @returns {boolean} `true` if `x` is valid fix type.
  105. */
  106. function isFixType(x) {
  107. return x === "directive" || x === "problem" || x === "suggestion" || x === "layout";
  108. }
  109. /**
  110. * Check if a given value is an array of fix types or not.
  111. * @param {any} x The value to check.
  112. * @returns {boolean} `true` if `x` is an array of fix types.
  113. */
  114. function isFixTypeArray(x) {
  115. return Array.isArray(x) && x.every(isFixType);
  116. }
  117. /**
  118. * The error for invalid options.
  119. */
  120. class ESLintInvalidOptionsError extends Error {
  121. constructor(messages) {
  122. super(`Invalid Options:\n- ${messages.join("\n- ")}`);
  123. this.code = "ESLINT_INVALID_OPTIONS";
  124. Error.captureStackTrace(this, ESLintInvalidOptionsError);
  125. }
  126. }
  127. /**
  128. * Validates and normalizes options for the wrapped CLIEngine instance.
  129. * @param {ESLintOptions} options The options to process.
  130. * @throws {ESLintInvalidOptionsError} If of any of a variety of type errors.
  131. * @returns {ESLintOptions} The normalized options.
  132. */
  133. function processOptions({
  134. allowInlineConfig = true, // ← we cannot use `overrideConfig.noInlineConfig` instead because `allowInlineConfig` has side-effect that suppress warnings that show inline configs are ignored.
  135. baseConfig = null,
  136. cache = false,
  137. cacheLocation = ".eslintcache",
  138. cacheStrategy = "metadata",
  139. cwd = process.cwd(),
  140. errorOnUnmatchedPattern = true,
  141. extensions = null, // ← should be null by default because if it's an array then it suppresses RFC20 feature.
  142. fix = false,
  143. fixTypes = null, // ← should be null by default because if it's an array then it suppresses rules that don't have the `meta.type` property.
  144. globInputPaths = true,
  145. ignore = true,
  146. ignorePath = null, // ← should be null by default because if it's a string then it may throw ENOENT.
  147. overrideConfig = null,
  148. overrideConfigFile = null,
  149. plugins = {},
  150. reportUnusedDisableDirectives = null, // ← should be null by default because if it's a string then it overrides the 'reportUnusedDisableDirectives' setting in config files. And we cannot use `overrideConfig.reportUnusedDisableDirectives` instead because we cannot configure the `error` severity with that.
  151. resolvePluginsRelativeTo = null, // ← should be null by default because if it's a string then it suppresses RFC47 feature.
  152. rulePaths = [],
  153. useEslintrc = true,
  154. ...unknownOptions
  155. }) {
  156. const errors = [];
  157. const unknownOptionKeys = Object.keys(unknownOptions);
  158. if (unknownOptionKeys.length >= 1) {
  159. errors.push(`Unknown options: ${unknownOptionKeys.join(", ")}`);
  160. if (unknownOptionKeys.includes("cacheFile")) {
  161. errors.push("'cacheFile' has been removed. Please use the 'cacheLocation' option instead.");
  162. }
  163. if (unknownOptionKeys.includes("configFile")) {
  164. errors.push("'configFile' has been removed. Please use the 'overrideConfigFile' option instead.");
  165. }
  166. if (unknownOptionKeys.includes("envs")) {
  167. errors.push("'envs' has been removed. Please use the 'overrideConfig.env' option instead.");
  168. }
  169. if (unknownOptionKeys.includes("globals")) {
  170. errors.push("'globals' has been removed. Please use the 'overrideConfig.globals' option instead.");
  171. }
  172. if (unknownOptionKeys.includes("ignorePattern")) {
  173. errors.push("'ignorePattern' has been removed. Please use the 'overrideConfig.ignorePatterns' option instead.");
  174. }
  175. if (unknownOptionKeys.includes("parser")) {
  176. errors.push("'parser' has been removed. Please use the 'overrideConfig.parser' option instead.");
  177. }
  178. if (unknownOptionKeys.includes("parserOptions")) {
  179. errors.push("'parserOptions' has been removed. Please use the 'overrideConfig.parserOptions' option instead.");
  180. }
  181. if (unknownOptionKeys.includes("rules")) {
  182. errors.push("'rules' has been removed. Please use the 'overrideConfig.rules' option instead.");
  183. }
  184. }
  185. if (typeof allowInlineConfig !== "boolean") {
  186. errors.push("'allowInlineConfig' must be a boolean.");
  187. }
  188. if (typeof baseConfig !== "object") {
  189. errors.push("'baseConfig' must be an object or null.");
  190. }
  191. if (typeof cache !== "boolean") {
  192. errors.push("'cache' must be a boolean.");
  193. }
  194. if (!isNonEmptyString(cacheLocation)) {
  195. errors.push("'cacheLocation' must be a non-empty string.");
  196. }
  197. if (
  198. cacheStrategy !== "metadata" &&
  199. cacheStrategy !== "content"
  200. ) {
  201. errors.push("'cacheStrategy' must be any of \"metadata\", \"content\".");
  202. }
  203. if (!isNonEmptyString(cwd) || !path.isAbsolute(cwd)) {
  204. errors.push("'cwd' must be an absolute path.");
  205. }
  206. if (typeof errorOnUnmatchedPattern !== "boolean") {
  207. errors.push("'errorOnUnmatchedPattern' must be a boolean.");
  208. }
  209. if (!isArrayOfNonEmptyString(extensions) && extensions !== null) {
  210. errors.push("'extensions' must be an array of non-empty strings or null.");
  211. }
  212. if (typeof fix !== "boolean" && typeof fix !== "function") {
  213. errors.push("'fix' must be a boolean or a function.");
  214. }
  215. if (fixTypes !== null && !isFixTypeArray(fixTypes)) {
  216. errors.push("'fixTypes' must be an array of any of \"directive\", \"problem\", \"suggestion\", and \"layout\".");
  217. }
  218. if (typeof globInputPaths !== "boolean") {
  219. errors.push("'globInputPaths' must be a boolean.");
  220. }
  221. if (typeof ignore !== "boolean") {
  222. errors.push("'ignore' must be a boolean.");
  223. }
  224. if (!isNonEmptyString(ignorePath) && ignorePath !== null) {
  225. errors.push("'ignorePath' must be a non-empty string or null.");
  226. }
  227. if (typeof overrideConfig !== "object") {
  228. errors.push("'overrideConfig' must be an object or null.");
  229. }
  230. if (!isNonEmptyString(overrideConfigFile) && overrideConfigFile !== null) {
  231. errors.push("'overrideConfigFile' must be a non-empty string or null.");
  232. }
  233. if (typeof plugins !== "object") {
  234. errors.push("'plugins' must be an object or null.");
  235. } else if (plugins !== null && Object.keys(plugins).includes("")) {
  236. errors.push("'plugins' must not include an empty string.");
  237. }
  238. if (Array.isArray(plugins)) {
  239. errors.push("'plugins' doesn't add plugins to configuration to load. Please use the 'overrideConfig.plugins' option instead.");
  240. }
  241. if (
  242. reportUnusedDisableDirectives !== "error" &&
  243. reportUnusedDisableDirectives !== "warn" &&
  244. reportUnusedDisableDirectives !== "off" &&
  245. reportUnusedDisableDirectives !== null
  246. ) {
  247. errors.push("'reportUnusedDisableDirectives' must be any of \"error\", \"warn\", \"off\", and null.");
  248. }
  249. if (
  250. !isNonEmptyString(resolvePluginsRelativeTo) &&
  251. resolvePluginsRelativeTo !== null
  252. ) {
  253. errors.push("'resolvePluginsRelativeTo' must be a non-empty string or null.");
  254. }
  255. if (!isArrayOfNonEmptyString(rulePaths)) {
  256. errors.push("'rulePaths' must be an array of non-empty strings.");
  257. }
  258. if (typeof useEslintrc !== "boolean") {
  259. errors.push("'useEslintrc' must be a boolean.");
  260. }
  261. if (errors.length > 0) {
  262. throw new ESLintInvalidOptionsError(errors);
  263. }
  264. return {
  265. allowInlineConfig,
  266. baseConfig,
  267. cache,
  268. cacheLocation,
  269. cacheStrategy,
  270. configFile: overrideConfigFile,
  271. cwd,
  272. errorOnUnmatchedPattern,
  273. extensions,
  274. fix,
  275. fixTypes,
  276. globInputPaths,
  277. ignore,
  278. ignorePath,
  279. reportUnusedDisableDirectives,
  280. resolvePluginsRelativeTo,
  281. rulePaths,
  282. useEslintrc
  283. };
  284. }
  285. /**
  286. * Check if a value has one or more properties and that value is not undefined.
  287. * @param {any} obj The value to check.
  288. * @returns {boolean} `true` if `obj` has one or more properties that that value is not undefined.
  289. */
  290. function hasDefinedProperty(obj) {
  291. if (typeof obj === "object" && obj !== null) {
  292. for (const key in obj) {
  293. if (typeof obj[key] !== "undefined") {
  294. return true;
  295. }
  296. }
  297. }
  298. return false;
  299. }
  300. /**
  301. * Create rulesMeta object.
  302. * @param {Map<string,Rule>} rules a map of rules from which to generate the object.
  303. * @returns {Object} metadata for all enabled rules.
  304. */
  305. function createRulesMeta(rules) {
  306. return Array.from(rules).reduce((retVal, [id, rule]) => {
  307. retVal[id] = rule.meta;
  308. return retVal;
  309. }, {});
  310. }
  311. /** @type {WeakMap<ExtractedConfig, DeprecatedRuleInfo[]>} */
  312. const usedDeprecatedRulesCache = new WeakMap();
  313. /**
  314. * Create used deprecated rule list.
  315. * @param {CLIEngine} cliEngine The CLIEngine instance.
  316. * @param {string} maybeFilePath The absolute path to a lint target file or `"<text>"`.
  317. * @returns {DeprecatedRuleInfo[]} The used deprecated rule list.
  318. */
  319. function getOrFindUsedDeprecatedRules(cliEngine, maybeFilePath) {
  320. const {
  321. configArrayFactory,
  322. options: { cwd }
  323. } = getCLIEngineInternalSlots(cliEngine);
  324. const filePath = path.isAbsolute(maybeFilePath)
  325. ? maybeFilePath
  326. : path.join(cwd, "__placeholder__.js");
  327. const configArray = configArrayFactory.getConfigArrayForFile(filePath);
  328. const config = configArray.extractConfig(filePath);
  329. // Most files use the same config, so cache it.
  330. if (!usedDeprecatedRulesCache.has(config)) {
  331. const pluginRules = configArray.pluginRules;
  332. const retv = [];
  333. for (const [ruleId, ruleConf] of Object.entries(config.rules)) {
  334. if (getRuleSeverity(ruleConf) === 0) {
  335. continue;
  336. }
  337. const rule = pluginRules.get(ruleId) || BuiltinRules.get(ruleId);
  338. const meta = rule && rule.meta;
  339. if (meta && meta.deprecated) {
  340. retv.push({ ruleId, replacedBy: meta.replacedBy || [] });
  341. }
  342. }
  343. usedDeprecatedRulesCache.set(config, Object.freeze(retv));
  344. }
  345. return usedDeprecatedRulesCache.get(config);
  346. }
  347. /**
  348. * Processes the linting results generated by a CLIEngine linting report to
  349. * match the ESLint class's API.
  350. * @param {CLIEngine} cliEngine The CLIEngine instance.
  351. * @param {CLIEngineLintReport} report The CLIEngine linting report to process.
  352. * @returns {LintResult[]} The processed linting results.
  353. */
  354. function processCLIEngineLintReport(cliEngine, { results }) {
  355. const descriptor = {
  356. configurable: true,
  357. enumerable: true,
  358. get() {
  359. return getOrFindUsedDeprecatedRules(cliEngine, this.filePath);
  360. }
  361. };
  362. for (const result of results) {
  363. Object.defineProperty(result, "usedDeprecatedRules", descriptor);
  364. }
  365. return results;
  366. }
  367. /**
  368. * An Array.prototype.sort() compatible compare function to order results by their file path.
  369. * @param {LintResult} a The first lint result.
  370. * @param {LintResult} b The second lint result.
  371. * @returns {number} An integer representing the order in which the two results should occur.
  372. */
  373. function compareResultsByFilePath(a, b) {
  374. if (a.filePath < b.filePath) {
  375. return -1;
  376. }
  377. if (a.filePath > b.filePath) {
  378. return 1;
  379. }
  380. return 0;
  381. }
  382. /**
  383. * Main API.
  384. */
  385. class ESLint {
  386. /**
  387. * Creates a new instance of the main ESLint API.
  388. * @param {ESLintOptions} options The options for this instance.
  389. */
  390. constructor(options = {}) {
  391. const processedOptions = processOptions(options);
  392. const cliEngine = new CLIEngine(processedOptions, { preloadedPlugins: options.plugins });
  393. const {
  394. configArrayFactory,
  395. lastConfigArrays
  396. } = getCLIEngineInternalSlots(cliEngine);
  397. let updated = false;
  398. /*
  399. * Address `overrideConfig` to set override config.
  400. * Operate the `configArrayFactory` internal slot directly because this
  401. * functionality doesn't exist as the public API of CLIEngine.
  402. */
  403. if (hasDefinedProperty(options.overrideConfig)) {
  404. configArrayFactory.setOverrideConfig(options.overrideConfig);
  405. updated = true;
  406. }
  407. // Update caches.
  408. if (updated) {
  409. configArrayFactory.clearCache();
  410. lastConfigArrays[0] = configArrayFactory.getConfigArrayForFile();
  411. }
  412. // Initialize private properties.
  413. privateMembersMap.set(this, {
  414. cliEngine,
  415. options: processedOptions
  416. });
  417. }
  418. /**
  419. * The version text.
  420. * @type {string}
  421. */
  422. static get version() {
  423. return version;
  424. }
  425. /**
  426. * Outputs fixes from the given results to files.
  427. * @param {LintResult[]} results The lint results.
  428. * @returns {Promise<void>} Returns a promise that is used to track side effects.
  429. */
  430. static async outputFixes(results) {
  431. if (!Array.isArray(results)) {
  432. throw new Error("'results' must be an array");
  433. }
  434. await Promise.all(
  435. results
  436. .filter(result => {
  437. if (typeof result !== "object" || result === null) {
  438. throw new Error("'results' must include only objects");
  439. }
  440. return (
  441. typeof result.output === "string" &&
  442. path.isAbsolute(result.filePath)
  443. );
  444. })
  445. .map(r => writeFile(r.filePath, r.output))
  446. );
  447. }
  448. /**
  449. * Returns results that only contains errors.
  450. * @param {LintResult[]} results The results to filter.
  451. * @returns {LintResult[]} The filtered results.
  452. */
  453. static getErrorResults(results) {
  454. return CLIEngine.getErrorResults(results);
  455. }
  456. /**
  457. * Returns meta objects for each rule represented in the lint results.
  458. * @param {LintResult[]} results The results to fetch rules meta for.
  459. * @returns {Object} A mapping of ruleIds to rule meta objects.
  460. */
  461. getRulesMetaForResults(results) {
  462. const resultRuleIds = new Set();
  463. // first gather all ruleIds from all results
  464. for (const result of results) {
  465. for (const { ruleId } of result.messages) {
  466. resultRuleIds.add(ruleId);
  467. }
  468. for (const { ruleId } of result.suppressedMessages) {
  469. resultRuleIds.add(ruleId);
  470. }
  471. }
  472. // create a map of all rules in the results
  473. const { cliEngine } = privateMembersMap.get(this);
  474. const rules = cliEngine.getRules();
  475. const resultRules = new Map();
  476. for (const [ruleId, rule] of rules) {
  477. if (resultRuleIds.has(ruleId)) {
  478. resultRules.set(ruleId, rule);
  479. }
  480. }
  481. return createRulesMeta(resultRules);
  482. }
  483. /**
  484. * Executes the current configuration on an array of file and directory names.
  485. * @param {string[]} patterns An array of file and directory names.
  486. * @returns {Promise<LintResult[]>} The results of linting the file patterns given.
  487. */
  488. async lintFiles(patterns) {
  489. if (!isNonEmptyString(patterns) && !isArrayOfNonEmptyString(patterns)) {
  490. throw new Error("'patterns' must be a non-empty string or an array of non-empty strings");
  491. }
  492. const { cliEngine } = privateMembersMap.get(this);
  493. return processCLIEngineLintReport(
  494. cliEngine,
  495. cliEngine.executeOnFiles(patterns)
  496. );
  497. }
  498. /**
  499. * Executes the current configuration on text.
  500. * @param {string} code A string of JavaScript code to lint.
  501. * @param {Object} [options] The options.
  502. * @param {string} [options.filePath] The path to the file of the source code.
  503. * @param {boolean} [options.warnIgnored] When set to true, warn if given filePath is an ignored path.
  504. * @returns {Promise<LintResult[]>} The results of linting the string of code given.
  505. */
  506. async lintText(code, options = {}) {
  507. if (typeof code !== "string") {
  508. throw new Error("'code' must be a string");
  509. }
  510. if (typeof options !== "object") {
  511. throw new Error("'options' must be an object, null, or undefined");
  512. }
  513. const {
  514. filePath,
  515. warnIgnored = false,
  516. ...unknownOptions
  517. } = options || {};
  518. const unknownOptionKeys = Object.keys(unknownOptions);
  519. if (unknownOptionKeys.length > 0) {
  520. throw new Error(`'options' must not include the unknown option(s): ${unknownOptionKeys.join(", ")}`);
  521. }
  522. if (filePath !== void 0 && !isNonEmptyString(filePath)) {
  523. throw new Error("'options.filePath' must be a non-empty string or undefined");
  524. }
  525. if (typeof warnIgnored !== "boolean") {
  526. throw new Error("'options.warnIgnored' must be a boolean or undefined");
  527. }
  528. const { cliEngine } = privateMembersMap.get(this);
  529. return processCLIEngineLintReport(
  530. cliEngine,
  531. cliEngine.executeOnText(code, filePath, warnIgnored)
  532. );
  533. }
  534. /**
  535. * Returns the formatter representing the given formatter name.
  536. * @param {string} [name] The name of the formatter to load.
  537. * The following values are allowed:
  538. * - `undefined` ... Load `stylish` builtin formatter.
  539. * - A builtin formatter name ... Load the builtin formatter.
  540. * - A third-party formatter name:
  541. * - `foo` → `eslint-formatter-foo`
  542. * - `@foo` → `@foo/eslint-formatter`
  543. * - `@foo/bar` → `@foo/eslint-formatter-bar`
  544. * - A file path ... Load the file.
  545. * @returns {Promise<LoadedFormatter>} A promise resolving to the formatter object.
  546. * This promise will be rejected if the given formatter was not found or not
  547. * a function.
  548. */
  549. async loadFormatter(name = "stylish") {
  550. if (typeof name !== "string") {
  551. throw new Error("'name' must be a string");
  552. }
  553. const { cliEngine, options } = privateMembersMap.get(this);
  554. const formatter = cliEngine.getFormatter(name);
  555. if (typeof formatter !== "function") {
  556. throw new Error(`Formatter must be a function, but got a ${typeof formatter}.`);
  557. }
  558. return {
  559. /**
  560. * The main formatter method.
  561. * @param {LintResult[]} results The lint results to format.
  562. * @param {ResultsMeta} resultsMeta Warning count and max threshold.
  563. * @returns {string | Promise<string>} The formatted lint results.
  564. */
  565. format(results, resultsMeta) {
  566. let rulesMeta = null;
  567. results.sort(compareResultsByFilePath);
  568. return formatter(results, {
  569. ...resultsMeta,
  570. get cwd() {
  571. return options.cwd;
  572. },
  573. get rulesMeta() {
  574. if (!rulesMeta) {
  575. rulesMeta = createRulesMeta(cliEngine.getRules());
  576. }
  577. return rulesMeta;
  578. }
  579. });
  580. }
  581. };
  582. }
  583. /**
  584. * Returns a configuration object for the given file based on the CLI options.
  585. * This is the same logic used by the ESLint CLI executable to determine
  586. * configuration for each file it processes.
  587. * @param {string} filePath The path of the file to retrieve a config object for.
  588. * @returns {Promise<ConfigData>} A configuration object for the file.
  589. */
  590. async calculateConfigForFile(filePath) {
  591. if (!isNonEmptyString(filePath)) {
  592. throw new Error("'filePath' must be a non-empty string");
  593. }
  594. const { cliEngine } = privateMembersMap.get(this);
  595. return cliEngine.getConfigForFile(filePath);
  596. }
  597. /**
  598. * Checks if a given path is ignored by ESLint.
  599. * @param {string} filePath The path of the file to check.
  600. * @returns {Promise<boolean>} Whether or not the given path is ignored.
  601. */
  602. async isPathIgnored(filePath) {
  603. if (!isNonEmptyString(filePath)) {
  604. throw new Error("'filePath' must be a non-empty string");
  605. }
  606. const { cliEngine } = privateMembersMap.get(this);
  607. return cliEngine.isPathIgnored(filePath);
  608. }
  609. }
  610. //------------------------------------------------------------------------------
  611. // Public Interface
  612. //------------------------------------------------------------------------------
  613. module.exports = {
  614. ESLint,
  615. /**
  616. * Get the private class members of a given ESLint instance for tests.
  617. * @param {ESLint} instance The ESLint instance to get.
  618. * @returns {ESLintPrivateMembers} The instance's private class members.
  619. */
  620. getESLintPrivateMembers(instance) {
  621. return privateMembersMap.get(instance);
  622. }
  623. };