Ohm-Management - Projektarbeit B-ME
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 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  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. path = require("path"),
  16. defaultOptions = require("../conf/default-cli-options"),
  17. Linter = require("./linter"),
  18. lodash = require("lodash"),
  19. IgnoredPaths = require("./ignored-paths"),
  20. Config = require("./config"),
  21. ConfigOps = require("./config/config-ops"),
  22. LintResultCache = require("./util/lint-result-cache"),
  23. globUtils = require("./util/glob-utils"),
  24. validator = require("./config/config-validator"),
  25. hash = require("./util/hash"),
  26. ModuleResolver = require("./util/module-resolver"),
  27. naming = require("./util/naming"),
  28. pkg = require("../package.json");
  29. const debug = require("debug")("eslint:cli-engine");
  30. const resolver = new ModuleResolver();
  31. const validFixTypes = new Set(["problem", "suggestion", "layout"]);
  32. //------------------------------------------------------------------------------
  33. // Typedefs
  34. //------------------------------------------------------------------------------
  35. /**
  36. * The options to configure a CLI engine with.
  37. * @typedef {Object} CLIEngineOptions
  38. * @property {boolean} allowInlineConfig Enable or disable inline configuration comments.
  39. * @property {Object} baseConfig Base config object, extended by all configs used with this CLIEngine instance
  40. * @property {boolean} cache Enable result caching.
  41. * @property {string} cacheLocation The cache file to use instead of .eslintcache.
  42. * @property {string} configFile The configuration file to use.
  43. * @property {string} cwd The value to use for the current working directory.
  44. * @property {string[]} envs An array of environments to load.
  45. * @property {string[]} extensions An array of file extensions to check.
  46. * @property {boolean|Function} fix Execute in autofix mode. If a function, should return a boolean.
  47. * @property {string[]} fixTypes Array of rule types to apply fixes for.
  48. * @property {string[]} globals An array of global variables to declare.
  49. * @property {boolean} ignore False disables use of .eslintignore.
  50. * @property {string} ignorePath The ignore file to use instead of .eslintignore.
  51. * @property {string} ignorePattern A glob pattern of files to ignore.
  52. * @property {boolean} useEslintrc False disables looking for .eslintrc
  53. * @property {string} parser The name of the parser to use.
  54. * @property {Object} parserOptions An object of parserOption settings to use.
  55. * @property {string[]} plugins An array of plugins to load.
  56. * @property {Object<string,*>} rules An object of rules to use.
  57. * @property {string[]} rulePaths An array of directories to load custom rules from.
  58. * @property {boolean} reportUnusedDisableDirectives `true` adds reports for unused eslint-disable directives
  59. */
  60. /**
  61. * A linting warning or error.
  62. * @typedef {Object} LintMessage
  63. * @property {string} message The message to display to the user.
  64. */
  65. /**
  66. * A linting result.
  67. * @typedef {Object} LintResult
  68. * @property {string} filePath The path to the file that was linted.
  69. * @property {LintMessage[]} messages All of the messages for the result.
  70. * @property {number} errorCount Number of errors for the result.
  71. * @property {number} warningCount Number of warnings for the result.
  72. * @property {number} fixableErrorCount Number of fixable errors for the result.
  73. * @property {number} fixableWarningCount Number of fixable warnings for the result.
  74. * @property {string=} [source] The source code of the file that was linted.
  75. * @property {string=} [output] The source code of the file that was linted, with as many fixes applied as possible.
  76. */
  77. //------------------------------------------------------------------------------
  78. // Helpers
  79. //------------------------------------------------------------------------------
  80. /**
  81. * Determines if each fix type in an array is supported by ESLint and throws
  82. * an error if not.
  83. * @param {string[]} fixTypes An array of fix types to check.
  84. * @returns {void}
  85. * @throws {Error} If an invalid fix type is found.
  86. */
  87. function validateFixTypes(fixTypes) {
  88. for (const fixType of fixTypes) {
  89. if (!validFixTypes.has(fixType)) {
  90. throw new Error(`Invalid fix type "${fixType}" found.`);
  91. }
  92. }
  93. }
  94. /**
  95. * It will calculate the error and warning count for collection of messages per file
  96. * @param {Object[]} messages - Collection of messages
  97. * @returns {Object} Contains the stats
  98. * @private
  99. */
  100. function calculateStatsPerFile(messages) {
  101. return messages.reduce((stat, message) => {
  102. if (message.fatal || message.severity === 2) {
  103. stat.errorCount++;
  104. if (message.fix) {
  105. stat.fixableErrorCount++;
  106. }
  107. } else {
  108. stat.warningCount++;
  109. if (message.fix) {
  110. stat.fixableWarningCount++;
  111. }
  112. }
  113. return stat;
  114. }, {
  115. errorCount: 0,
  116. warningCount: 0,
  117. fixableErrorCount: 0,
  118. fixableWarningCount: 0
  119. });
  120. }
  121. /**
  122. * It will calculate the error and warning count for collection of results from all files
  123. * @param {Object[]} results - Collection of messages from all the files
  124. * @returns {Object} Contains the stats
  125. * @private
  126. */
  127. function calculateStatsPerRun(results) {
  128. return results.reduce((stat, result) => {
  129. stat.errorCount += result.errorCount;
  130. stat.warningCount += result.warningCount;
  131. stat.fixableErrorCount += result.fixableErrorCount;
  132. stat.fixableWarningCount += result.fixableWarningCount;
  133. return stat;
  134. }, {
  135. errorCount: 0,
  136. warningCount: 0,
  137. fixableErrorCount: 0,
  138. fixableWarningCount: 0
  139. });
  140. }
  141. /**
  142. * Processes an source code using ESLint.
  143. * @param {string} text The source code to check.
  144. * @param {Object} configHelper The configuration options for ESLint.
  145. * @param {string} filename An optional string representing the texts filename.
  146. * @param {boolean|Function} fix Indicates if fixes should be processed.
  147. * @param {boolean} allowInlineConfig Allow/ignore comments that change config.
  148. * @param {boolean} reportUnusedDisableDirectives Allow/ignore comments that change config.
  149. * @param {Linter} linter Linter context
  150. * @returns {{rules: LintResult, config: Object}} The results for linting on this text and the fully-resolved config for it.
  151. * @private
  152. */
  153. function processText(text, configHelper, filename, fix, allowInlineConfig, reportUnusedDisableDirectives, linter) {
  154. let filePath,
  155. fileExtension,
  156. processor;
  157. if (filename) {
  158. filePath = path.resolve(filename);
  159. fileExtension = path.extname(filename);
  160. }
  161. const effectiveFilename = filename || "<text>";
  162. debug(`Linting ${effectiveFilename}`);
  163. const config = configHelper.getConfig(filePath);
  164. if (config.plugins) {
  165. configHelper.plugins.loadAll(config.plugins);
  166. }
  167. const loadedPlugins = configHelper.plugins.getAll();
  168. for (const plugin in loadedPlugins) {
  169. if (loadedPlugins[plugin].processors && Object.keys(loadedPlugins[plugin].processors).indexOf(fileExtension) >= 0) {
  170. processor = loadedPlugins[plugin].processors[fileExtension];
  171. break;
  172. }
  173. }
  174. const autofixingEnabled = typeof fix !== "undefined" && (!processor || processor.supportsAutofix);
  175. const fixedResult = linter.verifyAndFix(text, config, {
  176. filename: effectiveFilename,
  177. allowInlineConfig,
  178. reportUnusedDisableDirectives,
  179. fix: !!autofixingEnabled && fix,
  180. preprocess: processor && (rawText => processor.preprocess(rawText, effectiveFilename)),
  181. postprocess: processor && (problemLists => processor.postprocess(problemLists, effectiveFilename))
  182. });
  183. const stats = calculateStatsPerFile(fixedResult.messages);
  184. const result = {
  185. filePath: effectiveFilename,
  186. messages: fixedResult.messages,
  187. errorCount: stats.errorCount,
  188. warningCount: stats.warningCount,
  189. fixableErrorCount: stats.fixableErrorCount,
  190. fixableWarningCount: stats.fixableWarningCount
  191. };
  192. if (fixedResult.fixed) {
  193. result.output = fixedResult.output;
  194. }
  195. if (result.errorCount + result.warningCount > 0 && typeof result.output === "undefined") {
  196. result.source = text;
  197. }
  198. return { result, config };
  199. }
  200. /**
  201. * Processes an individual file using ESLint. Files used here are known to
  202. * exist, so no need to check that here.
  203. * @param {string} filename The filename of the file being checked.
  204. * @param {Object} configHelper The configuration options for ESLint.
  205. * @param {Object} options The CLIEngine options object.
  206. * @param {Linter} linter Linter context
  207. * @returns {{rules: LintResult, config: Object}} The results for linting on this text and the fully-resolved config for it.
  208. * @private
  209. */
  210. function processFile(filename, configHelper, options, linter) {
  211. const text = fs.readFileSync(path.resolve(filename), "utf8");
  212. return processText(
  213. text,
  214. configHelper,
  215. filename,
  216. options.fix,
  217. options.allowInlineConfig,
  218. options.reportUnusedDisableDirectives,
  219. linter
  220. );
  221. }
  222. /**
  223. * Returns result with warning by ignore settings
  224. * @param {string} filePath - File path of checked code
  225. * @param {string} baseDir - Absolute path of base directory
  226. * @returns {LintResult} Result with single warning
  227. * @private
  228. */
  229. function createIgnoreResult(filePath, baseDir) {
  230. let message;
  231. const isHidden = /^\./.test(path.basename(filePath));
  232. const isInNodeModules = baseDir && path.relative(baseDir, filePath).startsWith("node_modules");
  233. const isInBowerComponents = baseDir && path.relative(baseDir, filePath).startsWith("bower_components");
  234. if (isHidden) {
  235. message = "File ignored by default. Use a negated ignore pattern (like \"--ignore-pattern '!<relative/path/to/filename>'\") to override.";
  236. } else if (isInNodeModules) {
  237. message = "File ignored by default. Use \"--ignore-pattern '!node_modules/*'\" to override.";
  238. } else if (isInBowerComponents) {
  239. message = "File ignored by default. Use \"--ignore-pattern '!bower_components/*'\" to override.";
  240. } else {
  241. message = "File ignored because of a matching ignore pattern. Use \"--no-ignore\" to override.";
  242. }
  243. return {
  244. filePath: path.resolve(filePath),
  245. messages: [
  246. {
  247. fatal: false,
  248. severity: 1,
  249. message
  250. }
  251. ],
  252. errorCount: 0,
  253. warningCount: 1,
  254. fixableErrorCount: 0,
  255. fixableWarningCount: 0
  256. };
  257. }
  258. /**
  259. * Produces rule warnings (i.e. deprecation) from configured rules
  260. * @param {(Array<string>|Set<string>)} usedRules - Rules configured
  261. * @param {Map} loadedRules - Map of loaded rules
  262. * @returns {Array<Object>} Contains rule warnings
  263. * @private
  264. */
  265. function createRuleDeprecationWarnings(usedRules, loadedRules) {
  266. const usedDeprecatedRules = [];
  267. usedRules.forEach(name => {
  268. const loadedRule = loadedRules.get(name);
  269. if (loadedRule && loadedRule.meta && loadedRule.meta.deprecated) {
  270. const deprecatedRule = { ruleId: name };
  271. const replacedBy = lodash.get(loadedRule, "meta.replacedBy", []);
  272. if (replacedBy.every(newRule => lodash.isString(newRule))) {
  273. deprecatedRule.replacedBy = replacedBy;
  274. }
  275. usedDeprecatedRules.push(deprecatedRule);
  276. }
  277. });
  278. return usedDeprecatedRules;
  279. }
  280. /**
  281. * Checks if the given message is an error message.
  282. * @param {Object} message The message to check.
  283. * @returns {boolean} Whether or not the message is an error message.
  284. * @private
  285. */
  286. function isErrorMessage(message) {
  287. return message.severity === 2;
  288. }
  289. /**
  290. * return the cacheFile to be used by eslint, based on whether the provided parameter is
  291. * a directory or looks like a directory (ends in `path.sep`), in which case the file
  292. * name will be the `cacheFile/.cache_hashOfCWD`
  293. *
  294. * if cacheFile points to a file or looks like a file then in will just use that file
  295. *
  296. * @param {string} cacheFile The name of file to be used to store the cache
  297. * @param {string} cwd Current working directory
  298. * @returns {string} the resolved path to the cache file
  299. */
  300. function getCacheFile(cacheFile, cwd) {
  301. /*
  302. * make sure the path separators are normalized for the environment/os
  303. * keeping the trailing path separator if present
  304. */
  305. const normalizedCacheFile = path.normalize(cacheFile);
  306. const resolvedCacheFile = path.resolve(cwd, normalizedCacheFile);
  307. const looksLikeADirectory = normalizedCacheFile.slice(-1) === path.sep;
  308. /**
  309. * return the name for the cache file in case the provided parameter is a directory
  310. * @returns {string} the resolved path to the cacheFile
  311. */
  312. function getCacheFileForDirectory() {
  313. return path.join(resolvedCacheFile, `.cache_${hash(cwd)}`);
  314. }
  315. let fileStats;
  316. try {
  317. fileStats = fs.lstatSync(resolvedCacheFile);
  318. } catch (ex) {
  319. fileStats = null;
  320. }
  321. /*
  322. * in case the file exists we need to verify if the provided path
  323. * is a directory or a file. If it is a directory we want to create a file
  324. * inside that directory
  325. */
  326. if (fileStats) {
  327. /*
  328. * is a directory or is a file, but the original file the user provided
  329. * looks like a directory but `path.resolve` removed the `last path.sep`
  330. * so we need to still treat this like a directory
  331. */
  332. if (fileStats.isDirectory() || looksLikeADirectory) {
  333. return getCacheFileForDirectory();
  334. }
  335. // is file so just use that file
  336. return resolvedCacheFile;
  337. }
  338. /*
  339. * here we known the file or directory doesn't exist,
  340. * so we will try to infer if its a directory if it looks like a directory
  341. * for the current operating system.
  342. */
  343. // if the last character passed is a path separator we assume is a directory
  344. if (looksLikeADirectory) {
  345. return getCacheFileForDirectory();
  346. }
  347. return resolvedCacheFile;
  348. }
  349. //------------------------------------------------------------------------------
  350. // Public Interface
  351. //------------------------------------------------------------------------------
  352. class CLIEngine {
  353. /**
  354. * Creates a new instance of the core CLI engine.
  355. * @param {CLIEngineOptions} providedOptions The options for this instance.
  356. * @constructor
  357. */
  358. constructor(providedOptions) {
  359. const options = Object.assign(
  360. Object.create(null),
  361. defaultOptions,
  362. { cwd: process.cwd() },
  363. providedOptions
  364. );
  365. /*
  366. * if an --ignore-path option is provided, ensure that the ignore
  367. * file exists and is not a directory
  368. */
  369. if (options.ignore && options.ignorePath) {
  370. try {
  371. if (!fs.statSync(options.ignorePath).isFile()) {
  372. throw new Error(`${options.ignorePath} is not a file`);
  373. }
  374. } catch (e) {
  375. e.message = `Error: Could not load file ${options.ignorePath}\nError: ${e.message}`;
  376. throw e;
  377. }
  378. }
  379. /**
  380. * Stored options for this instance
  381. * @type {Object}
  382. */
  383. this.options = options;
  384. this.linter = new Linter();
  385. // load in additional rules
  386. if (this.options.rulePaths) {
  387. const cwd = this.options.cwd;
  388. this.options.rulePaths.forEach(rulesdir => {
  389. debug(`Loading rules from ${rulesdir}`);
  390. this.linter.rules.load(rulesdir, cwd);
  391. });
  392. }
  393. if (this.options.rules && Object.keys(this.options.rules).length) {
  394. const loadedRules = this.linter.getRules();
  395. Object.keys(this.options.rules).forEach(name => {
  396. validator.validateRuleOptions(loadedRules.get(name), name, this.options.rules[name], "CLI");
  397. });
  398. }
  399. this.config = new Config(this.options, this.linter);
  400. if (this.options.cache) {
  401. const cacheFile = getCacheFile(this.options.cacheLocation || this.options.cacheFile, this.options.cwd);
  402. /**
  403. * Cache used to avoid operating on files that haven't changed since the
  404. * last successful execution.
  405. * @type {Object}
  406. */
  407. this._lintResultCache = new LintResultCache(cacheFile, this.config);
  408. }
  409. // setup special filter for fixes
  410. if (this.options.fix && this.options.fixTypes && this.options.fixTypes.length > 0) {
  411. debug(`Using fix types ${this.options.fixTypes}`);
  412. // throw an error if any invalid fix types are found
  413. validateFixTypes(this.options.fixTypes);
  414. // convert to Set for faster lookup
  415. const fixTypes = new Set(this.options.fixTypes);
  416. // save original value of options.fix in case it's a function
  417. const originalFix = (typeof this.options.fix === "function")
  418. ? this.options.fix : () => this.options.fix;
  419. // create a cache of rules (but don't populate until needed)
  420. this._rulesCache = null;
  421. this.options.fix = lintResult => {
  422. const rule = this._rulesCache.get(lintResult.ruleId);
  423. const matches = rule.meta && fixTypes.has(rule.meta.type);
  424. return matches && originalFix(lintResult);
  425. };
  426. }
  427. }
  428. getRules() {
  429. return this.linter.getRules();
  430. }
  431. /**
  432. * Returns results that only contains errors.
  433. * @param {LintResult[]} results The results to filter.
  434. * @returns {LintResult[]} The filtered results.
  435. */
  436. static getErrorResults(results) {
  437. const filtered = [];
  438. results.forEach(result => {
  439. const filteredMessages = result.messages.filter(isErrorMessage);
  440. if (filteredMessages.length > 0) {
  441. filtered.push(
  442. Object.assign(result, {
  443. messages: filteredMessages,
  444. errorCount: filteredMessages.length,
  445. warningCount: 0,
  446. fixableErrorCount: result.fixableErrorCount,
  447. fixableWarningCount: 0
  448. })
  449. );
  450. }
  451. });
  452. return filtered;
  453. }
  454. /**
  455. * Outputs fixes from the given results to files.
  456. * @param {Object} report The report object created by CLIEngine.
  457. * @returns {void}
  458. */
  459. static outputFixes(report) {
  460. report.results.filter(result => Object.prototype.hasOwnProperty.call(result, "output")).forEach(result => {
  461. fs.writeFileSync(result.filePath, result.output);
  462. });
  463. }
  464. /**
  465. * Add a plugin by passing its configuration
  466. * @param {string} name Name of the plugin.
  467. * @param {Object} pluginobject Plugin configuration object.
  468. * @returns {void}
  469. */
  470. addPlugin(name, pluginobject) {
  471. this.config.plugins.define(name, pluginobject);
  472. }
  473. /**
  474. * Resolves the patterns passed into executeOnFiles() into glob-based patterns
  475. * for easier handling.
  476. * @param {string[]} patterns The file patterns passed on the command line.
  477. * @returns {string[]} The equivalent glob patterns.
  478. */
  479. resolveFileGlobPatterns(patterns) {
  480. return globUtils.resolveFileGlobPatterns(patterns.filter(Boolean), this.options);
  481. }
  482. /**
  483. * Executes the current configuration on an array of file and directory names.
  484. * @param {string[]} patterns An array of file and directory names.
  485. * @returns {Object} The results for all files that were linted.
  486. */
  487. executeOnFiles(patterns) {
  488. const options = this.options,
  489. lintResultCache = this._lintResultCache,
  490. configHelper = this.config;
  491. const cacheFile = getCacheFile(this.options.cacheLocation || this.options.cacheFile, this.options.cwd);
  492. if (!options.cache && fs.existsSync(cacheFile)) {
  493. fs.unlinkSync(cacheFile);
  494. }
  495. const startTime = Date.now();
  496. const fileList = globUtils.listFilesToProcess(patterns, options);
  497. const allUsedRules = new Set();
  498. const results = fileList.map(fileInfo => {
  499. if (fileInfo.ignored) {
  500. return createIgnoreResult(fileInfo.filename, options.cwd);
  501. }
  502. if (options.cache) {
  503. const cachedLintResults = lintResultCache.getCachedLintResults(fileInfo.filename);
  504. if (cachedLintResults) {
  505. const resultHadMessages = cachedLintResults.messages && cachedLintResults.messages.length;
  506. if (resultHadMessages && options.fix) {
  507. debug(`Reprocessing cached file to allow autofix: ${fileInfo.filename}`);
  508. } else {
  509. debug(`Skipping file since it hasn't changed: ${fileInfo.filename}`);
  510. return cachedLintResults;
  511. }
  512. }
  513. }
  514. // if there's a cache, populate it
  515. if ("_rulesCache" in this) {
  516. this._rulesCache = this.getRules();
  517. }
  518. debug(`Processing ${fileInfo.filename}`);
  519. const { result, config } = processFile(fileInfo.filename, configHelper, options, this.linter);
  520. Object.keys(config.rules)
  521. .filter(ruleId => ConfigOps.getRuleSeverity(config.rules[ruleId]))
  522. .forEach(ruleId => allUsedRules.add(ruleId));
  523. return result;
  524. });
  525. if (options.cache) {
  526. results.forEach(result => {
  527. /*
  528. * Store the lint result in the LintResultCache.
  529. * NOTE: The LintResultCache will remove the file source and any
  530. * other properties that are difficult to serialize, and will
  531. * hydrate those properties back in on future lint runs.
  532. */
  533. lintResultCache.setCachedLintResults(result.filePath, result);
  534. });
  535. // persist the cache to disk
  536. lintResultCache.reconcile();
  537. }
  538. const stats = calculateStatsPerRun(results);
  539. const usedDeprecatedRules = createRuleDeprecationWarnings(allUsedRules, this.getRules());
  540. debug(`Linting complete in: ${Date.now() - startTime}ms`);
  541. return {
  542. results,
  543. errorCount: stats.errorCount,
  544. warningCount: stats.warningCount,
  545. fixableErrorCount: stats.fixableErrorCount,
  546. fixableWarningCount: stats.fixableWarningCount,
  547. usedDeprecatedRules
  548. };
  549. }
  550. /**
  551. * Executes the current configuration on text.
  552. * @param {string} text A string of JavaScript code to lint.
  553. * @param {string} filename An optional string representing the texts filename.
  554. * @param {boolean} warnIgnored Always warn when a file is ignored
  555. * @returns {Object} The results for the linting.
  556. */
  557. executeOnText(text, filename, warnIgnored) {
  558. const results = [],
  559. options = this.options,
  560. configHelper = this.config,
  561. ignoredPaths = new IgnoredPaths(options);
  562. // resolve filename based on options.cwd (for reporting, ignoredPaths also resolves)
  563. const resolvedFilename = filename && !path.isAbsolute(filename)
  564. ? path.resolve(options.cwd, filename)
  565. : filename;
  566. let usedDeprecatedRules;
  567. if (resolvedFilename && ignoredPaths.contains(resolvedFilename)) {
  568. if (warnIgnored) {
  569. results.push(createIgnoreResult(resolvedFilename, options.cwd));
  570. }
  571. usedDeprecatedRules = [];
  572. } else {
  573. // if there's a cache, populate it
  574. if ("_rulesCache" in this) {
  575. this._rulesCache = this.getRules();
  576. }
  577. const { result, config } = processText(
  578. text,
  579. configHelper,
  580. resolvedFilename,
  581. options.fix,
  582. options.allowInlineConfig,
  583. options.reportUnusedDisableDirectives,
  584. this.linter
  585. );
  586. results.push(result);
  587. usedDeprecatedRules = createRuleDeprecationWarnings(
  588. Object.keys(config.rules).filter(rule => ConfigOps.getRuleSeverity(config.rules[rule])),
  589. this.getRules()
  590. );
  591. }
  592. const stats = calculateStatsPerRun(results);
  593. return {
  594. results,
  595. errorCount: stats.errorCount,
  596. warningCount: stats.warningCount,
  597. fixableErrorCount: stats.fixableErrorCount,
  598. fixableWarningCount: stats.fixableWarningCount,
  599. usedDeprecatedRules
  600. };
  601. }
  602. /**
  603. * Returns a configuration object for the given file based on the CLI options.
  604. * This is the same logic used by the ESLint CLI executable to determine
  605. * configuration for each file it processes.
  606. * @param {string} filePath The path of the file to retrieve a config object for.
  607. * @returns {Object} A configuration object for the file.
  608. */
  609. getConfigForFile(filePath) {
  610. const configHelper = this.config;
  611. return configHelper.getConfig(filePath);
  612. }
  613. /**
  614. * Checks if a given path is ignored by ESLint.
  615. * @param {string} filePath The path of the file to check.
  616. * @returns {boolean} Whether or not the given path is ignored.
  617. */
  618. isPathIgnored(filePath) {
  619. const resolvedPath = path.resolve(this.options.cwd, filePath);
  620. const ignoredPaths = new IgnoredPaths(this.options);
  621. return ignoredPaths.contains(resolvedPath);
  622. }
  623. /**
  624. * Returns the formatter representing the given format or null if no formatter
  625. * with the given name can be found.
  626. * @param {string} [format] The name of the format to load or the path to a
  627. * custom formatter.
  628. * @returns {Function} The formatter function or null if not found.
  629. */
  630. getFormatter(format) {
  631. // default is stylish
  632. const resolvedFormatName = format || "stylish";
  633. // only strings are valid formatters
  634. if (typeof resolvedFormatName === "string") {
  635. // replace \ with / for Windows compatibility
  636. const normalizedFormatName = resolvedFormatName.replace(/\\/g, "/");
  637. const cwd = this.options ? this.options.cwd : process.cwd();
  638. const namespace = naming.getNamespaceFromTerm(normalizedFormatName);
  639. let formatterPath;
  640. // if there's a slash, then it's a file
  641. if (!namespace && normalizedFormatName.indexOf("/") > -1) {
  642. formatterPath = path.resolve(cwd, normalizedFormatName);
  643. } else {
  644. try {
  645. const npmFormat = naming.normalizePackageName(normalizedFormatName, "eslint-formatter");
  646. formatterPath = resolver.resolve(npmFormat, `${cwd}/node_modules`);
  647. } catch (e) {
  648. formatterPath = `./formatters/${normalizedFormatName}`;
  649. }
  650. }
  651. try {
  652. return require(formatterPath);
  653. } catch (ex) {
  654. ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`;
  655. throw ex;
  656. }
  657. } else {
  658. return null;
  659. }
  660. }
  661. }
  662. CLIEngine.version = pkg.version;
  663. CLIEngine.getFormatter = CLIEngine.prototype.getFormatter;
  664. module.exports = CLIEngine;