Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

223 строки
7.1 KiB

  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("./util/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. if (Array.isArray(args)) {
  117. debug("CLI args: %o", args.slice(2));
  118. }
  119. let currentOptions;
  120. try {
  121. currentOptions = options.parse(args);
  122. } catch (error) {
  123. log.error(error.message);
  124. return 2;
  125. }
  126. const files = currentOptions._;
  127. const useStdin = typeof text === "string";
  128. if (currentOptions.version) { // version from package.json
  129. log.info(`v${require("../package.json").version}`);
  130. } else if (currentOptions.printConfig) {
  131. if (files.length) {
  132. log.error("The --print-config option must be used with exactly one file name.");
  133. return 2;
  134. }
  135. if (useStdin) {
  136. log.error("The --print-config option is not available for piped-in code.");
  137. return 2;
  138. }
  139. const engine = new CLIEngine(translateOptions(currentOptions));
  140. const fileConfig = engine.getConfigForFile(currentOptions.printConfig);
  141. log.info(JSON.stringify(fileConfig, null, " "));
  142. return 0;
  143. } else if (currentOptions.help || (!files.length && !useStdin)) {
  144. log.info(options.generateHelp());
  145. } else {
  146. debug(`Running on ${useStdin ? "text" : "files"}`);
  147. if (currentOptions.fix && currentOptions.fixDryRun) {
  148. log.error("The --fix option and the --fix-dry-run option cannot be used together.");
  149. return 2;
  150. }
  151. if (useStdin && currentOptions.fix) {
  152. log.error("The --fix option is not available for piped-in code; use --fix-dry-run instead.");
  153. return 2;
  154. }
  155. const engine = new CLIEngine(translateOptions(currentOptions));
  156. const report = useStdin ? engine.executeOnText(text, currentOptions.stdinFilename, true) : engine.executeOnFiles(files);
  157. if (currentOptions.fix) {
  158. debug("Fix mode enabled - applying fixes");
  159. CLIEngine.outputFixes(report);
  160. }
  161. if (currentOptions.quiet) {
  162. debug("Quiet mode enabled - filtering out warnings");
  163. report.results = CLIEngine.getErrorResults(report.results);
  164. }
  165. if (printResults(engine, report.results, currentOptions.format, currentOptions.outputFile)) {
  166. const tooManyWarnings = currentOptions.maxWarnings >= 0 && report.warningCount > currentOptions.maxWarnings;
  167. if (!report.errorCount && tooManyWarnings) {
  168. log.error("ESLint found too many warnings (maximum: %s).", currentOptions.maxWarnings);
  169. }
  170. return (report.errorCount || tooManyWarnings) ? 1 : 0;
  171. }
  172. return 2;
  173. }
  174. return 0;
  175. }
  176. };
  177. module.exports = cli;