Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cli-engine.js 36KB

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