cli.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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. options = require("./options"),
  17. CLIEngine = require("./cli-engine"),
  18. mkdirp = require("mkdirp"),
  19. log = require("./logging");
  20. const debug = require("debug")("eslint:cli");
  21. //------------------------------------------------------------------------------
  22. // Helpers
  23. //------------------------------------------------------------------------------
  24. /**
  25. * Predicate function for whether or not to apply fixes in quiet mode.
  26. * If a message is a warning, do not apply a fix.
  27. * @param {LintResult} lintResult The lint result.
  28. * @returns {boolean} True if the lint message is an error (and thus should be
  29. * autofixed), false otherwise.
  30. */
  31. function quietFixPredicate(lintResult) {
  32. return lintResult.severity === 2;
  33. }
  34. /**
  35. * Translates the CLI options into the options expected by the CLIEngine.
  36. * @param {Object} cliOptions The CLI options to translate.
  37. * @returns {CLIEngineOptions} The options object for the CLIEngine.
  38. * @private
  39. */
  40. function translateOptions(cliOptions) {
  41. return {
  42. envs: cliOptions.env,
  43. extensions: cliOptions.ext,
  44. rules: cliOptions.rule,
  45. plugins: cliOptions.plugin,
  46. globals: cliOptions.global,
  47. ignore: cliOptions.ignore,
  48. ignorePath: cliOptions.ignorePath,
  49. ignorePattern: cliOptions.ignorePattern,
  50. configFile: cliOptions.config,
  51. rulePaths: cliOptions.rulesdir,
  52. useEslintrc: cliOptions.eslintrc,
  53. parser: cliOptions.parser,
  54. parserOptions: cliOptions.parserOptions,
  55. cache: cliOptions.cache,
  56. cacheFile: cliOptions.cacheFile,
  57. cacheLocation: cliOptions.cacheLocation,
  58. fix: (cliOptions.fix || cliOptions.fixDryRun) && (cliOptions.quiet ? quietFixPredicate : true),
  59. allowInlineConfig: cliOptions.inlineConfig,
  60. reportUnusedDisableDirectives: cliOptions.reportUnusedDisableDirectives
  61. };
  62. }
  63. /**
  64. * Outputs the results of the linting.
  65. * @param {CLIEngine} engine The CLIEngine to use.
  66. * @param {LintResult[]} results The results to print.
  67. * @param {string} format The name of the formatter to use or the path to the formatter.
  68. * @param {string} outputFile The path for the output file.
  69. * @returns {boolean} True if the printing succeeds, false if not.
  70. * @private
  71. */
  72. function printResults(engine, results, format, outputFile) {
  73. let formatter;
  74. try {
  75. formatter = engine.getFormatter(format);
  76. } catch (e) {
  77. log.error(e.message);
  78. return false;
  79. }
  80. const output = formatter(results);
  81. if (output) {
  82. if (outputFile) {
  83. const filePath = path.resolve(process.cwd(), outputFile);
  84. if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory()) {
  85. log.error("Cannot write to output file path, it is a directory: %s", outputFile);
  86. return false;
  87. }
  88. try {
  89. mkdirp.sync(path.dirname(filePath));
  90. fs.writeFileSync(filePath, output);
  91. } catch (ex) {
  92. log.error("There was a problem writing the output file:\n%s", ex);
  93. return false;
  94. }
  95. } else {
  96. log.info(output);
  97. }
  98. }
  99. return true;
  100. }
  101. //------------------------------------------------------------------------------
  102. // Public Interface
  103. //------------------------------------------------------------------------------
  104. /**
  105. * Encapsulates all CLI behavior for eslint. Makes it easier to test as well as
  106. * for other Node.js programs to effectively run the CLI.
  107. */
  108. const cli = {
  109. /**
  110. * Executes the CLI based on an array of arguments that is passed in.
  111. * @param {string|Array|Object} args The arguments to process.
  112. * @param {string} [text] The text to lint (used for TTY).
  113. * @returns {int} The exit code for the operation.
  114. */
  115. execute(args, text) {
  116. let currentOptions;
  117. try {
  118. currentOptions = options.parse(args);
  119. } catch (error) {
  120. log.error(error.message);
  121. return 1;
  122. }
  123. const files = currentOptions._;
  124. const useStdin = typeof text === "string";
  125. if (currentOptions.version) { // version from package.json
  126. log.info(`v${require("../package.json").version}`);
  127. } else if (currentOptions.printConfig) {
  128. if (files.length) {
  129. log.error("The --print-config option must be used with exactly one file name.");
  130. return 1;
  131. }
  132. if (useStdin) {
  133. log.error("The --print-config option is not available for piped-in code.");
  134. return 1;
  135. }
  136. const engine = new CLIEngine(translateOptions(currentOptions));
  137. const fileConfig = engine.getConfigForFile(currentOptions.printConfig);
  138. log.info(JSON.stringify(fileConfig, null, " "));
  139. return 0;
  140. } else if (currentOptions.help || (!files.length && !useStdin)) {
  141. log.info(options.generateHelp());
  142. } else {
  143. debug(`Running on ${useStdin ? "text" : "files"}`);
  144. if (currentOptions.fix && currentOptions.fixDryRun) {
  145. log.error("The --fix option and the --fix-dry-run option cannot be used together.");
  146. return 1;
  147. }
  148. if (useStdin && currentOptions.fix) {
  149. log.error("The --fix option is not available for piped-in code; use --fix-dry-run instead.");
  150. return 1;
  151. }
  152. const engine = new CLIEngine(translateOptions(currentOptions));
  153. const report = useStdin ? engine.executeOnText(text, currentOptions.stdinFilename, true) : engine.executeOnFiles(files);
  154. if (currentOptions.fix) {
  155. debug("Fix mode enabled - applying fixes");
  156. CLIEngine.outputFixes(report);
  157. }
  158. if (currentOptions.quiet) {
  159. debug("Quiet mode enabled - filtering out warnings");
  160. report.results = CLIEngine.getErrorResults(report.results);
  161. }
  162. if (printResults(engine, report.results, currentOptions.format, currentOptions.outputFile)) {
  163. const tooManyWarnings = currentOptions.maxWarnings >= 0 && report.warningCount > currentOptions.maxWarnings;
  164. if (!report.errorCount && tooManyWarnings) {
  165. log.error("ESLint found too many warnings (maximum: %s).", currentOptions.maxWarnings);
  166. }
  167. return (report.errorCount || tooManyWarnings) ? 1 : 0;
  168. }
  169. return 1;
  170. }
  171. return 0;
  172. }
  173. };
  174. module.exports = cli;