cli.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. { promisify } = require("util"),
  17. { ESLint } = require("./eslint"),
  18. CLIOptions = require("./options"),
  19. log = require("./shared/logging"),
  20. RuntimeInfo = require("./shared/runtime-info");
  21. const debug = require("debug")("eslint:cli");
  22. //------------------------------------------------------------------------------
  23. // Types
  24. //------------------------------------------------------------------------------
  25. /** @typedef {import("./eslint/eslint").ESLintOptions} ESLintOptions */
  26. /** @typedef {import("./eslint/eslint").LintMessage} LintMessage */
  27. /** @typedef {import("./eslint/eslint").LintResult} LintResult */
  28. /** @typedef {import("./options").ParsedCLIOptions} ParsedCLIOptions */
  29. //------------------------------------------------------------------------------
  30. // Helpers
  31. //------------------------------------------------------------------------------
  32. const mkdir = promisify(fs.mkdir);
  33. const stat = promisify(fs.stat);
  34. const writeFile = promisify(fs.writeFile);
  35. /**
  36. * Predicate function for whether or not to apply fixes in quiet mode.
  37. * If a message is a warning, do not apply a fix.
  38. * @param {LintMessage} message The lint result.
  39. * @returns {boolean} True if the lint message is an error (and thus should be
  40. * autofixed), false otherwise.
  41. */
  42. function quietFixPredicate(message) {
  43. return message.severity === 2;
  44. }
  45. /**
  46. * Translates the CLI options into the options expected by the CLIEngine.
  47. * @param {ParsedCLIOptions} cliOptions The CLI options to translate.
  48. * @returns {ESLintOptions} The options object for the CLIEngine.
  49. * @private
  50. */
  51. function translateOptions({
  52. cache,
  53. cacheFile,
  54. cacheLocation,
  55. cacheStrategy,
  56. config,
  57. env,
  58. errorOnUnmatchedPattern,
  59. eslintrc,
  60. ext,
  61. fix,
  62. fixDryRun,
  63. fixType,
  64. global,
  65. ignore,
  66. ignorePath,
  67. ignorePattern,
  68. inlineConfig,
  69. parser,
  70. parserOptions,
  71. plugin,
  72. quiet,
  73. reportUnusedDisableDirectives,
  74. resolvePluginsRelativeTo,
  75. rule,
  76. rulesdir
  77. }) {
  78. return {
  79. allowInlineConfig: inlineConfig,
  80. cache,
  81. cacheLocation: cacheLocation || cacheFile,
  82. cacheStrategy,
  83. errorOnUnmatchedPattern,
  84. extensions: ext,
  85. fix: (fix || fixDryRun) && (quiet ? quietFixPredicate : true),
  86. fixTypes: fixType,
  87. ignore,
  88. ignorePath,
  89. overrideConfig: {
  90. env: env && env.reduce((obj, name) => {
  91. obj[name] = true;
  92. return obj;
  93. }, {}),
  94. globals: global && global.reduce((obj, name) => {
  95. if (name.endsWith(":true")) {
  96. obj[name.slice(0, -5)] = "writable";
  97. } else {
  98. obj[name] = "readonly";
  99. }
  100. return obj;
  101. }, {}),
  102. ignorePatterns: ignorePattern,
  103. parser,
  104. parserOptions,
  105. plugins: plugin,
  106. rules: rule
  107. },
  108. overrideConfigFile: config,
  109. reportUnusedDisableDirectives: reportUnusedDisableDirectives ? "error" : void 0,
  110. resolvePluginsRelativeTo,
  111. rulePaths: rulesdir,
  112. useEslintrc: eslintrc
  113. };
  114. }
  115. /**
  116. * Count error messages.
  117. * @param {LintResult[]} results The lint results.
  118. * @returns {{errorCount:number;warningCount:number}} The number of error messages.
  119. */
  120. function countErrors(results) {
  121. let errorCount = 0;
  122. let warningCount = 0;
  123. for (const result of results) {
  124. errorCount += result.errorCount;
  125. warningCount += result.warningCount;
  126. }
  127. return { errorCount, warningCount };
  128. }
  129. /**
  130. * Check if a given file path is a directory or not.
  131. * @param {string} filePath The path to a file to check.
  132. * @returns {Promise<boolean>} `true` if the given path is a directory.
  133. */
  134. async function isDirectory(filePath) {
  135. try {
  136. return (await stat(filePath)).isDirectory();
  137. } catch (error) {
  138. if (error.code === "ENOENT" || error.code === "ENOTDIR") {
  139. return false;
  140. }
  141. throw error;
  142. }
  143. }
  144. /**
  145. * Outputs the results of the linting.
  146. * @param {ESLint} engine The ESLint instance to use.
  147. * @param {LintResult[]} results The results to print.
  148. * @param {string} format The name of the formatter to use or the path to the formatter.
  149. * @param {string} outputFile The path for the output file.
  150. * @returns {Promise<boolean>} True if the printing succeeds, false if not.
  151. * @private
  152. */
  153. async function printResults(engine, results, format, outputFile) {
  154. let formatter;
  155. try {
  156. formatter = await engine.loadFormatter(format);
  157. } catch (e) {
  158. log.error(e.message);
  159. return false;
  160. }
  161. const output = formatter.format(results);
  162. if (output) {
  163. if (outputFile) {
  164. const filePath = path.resolve(process.cwd(), outputFile);
  165. if (await isDirectory(filePath)) {
  166. log.error("Cannot write to output file path, it is a directory: %s", outputFile);
  167. return false;
  168. }
  169. try {
  170. await mkdir(path.dirname(filePath), { recursive: true });
  171. await writeFile(filePath, output);
  172. } catch (ex) {
  173. log.error("There was a problem writing the output file:\n%s", ex);
  174. return false;
  175. }
  176. } else {
  177. log.info(output);
  178. }
  179. }
  180. return true;
  181. }
  182. //------------------------------------------------------------------------------
  183. // Public Interface
  184. //------------------------------------------------------------------------------
  185. /**
  186. * Encapsulates all CLI behavior for eslint. Makes it easier to test as well as
  187. * for other Node.js programs to effectively run the CLI.
  188. */
  189. const cli = {
  190. /**
  191. * Executes the CLI based on an array of arguments that is passed in.
  192. * @param {string|Array|Object} args The arguments to process.
  193. * @param {string} [text] The text to lint (used for TTY).
  194. * @returns {Promise<number>} The exit code for the operation.
  195. */
  196. async execute(args, text) {
  197. if (Array.isArray(args)) {
  198. debug("CLI args: %o", args.slice(2));
  199. }
  200. /** @type {ParsedCLIOptions} */
  201. let options;
  202. try {
  203. options = CLIOptions.parse(args);
  204. } catch (error) {
  205. log.error(error.message);
  206. return 2;
  207. }
  208. const files = options._;
  209. const useStdin = typeof text === "string";
  210. if (options.help) {
  211. log.info(CLIOptions.generateHelp());
  212. return 0;
  213. }
  214. if (options.version) {
  215. log.info(RuntimeInfo.version());
  216. return 0;
  217. }
  218. if (options.envInfo) {
  219. try {
  220. log.info(RuntimeInfo.environment());
  221. return 0;
  222. } catch (err) {
  223. log.error(err.message);
  224. return 2;
  225. }
  226. }
  227. if (options.printConfig) {
  228. if (files.length) {
  229. log.error("The --print-config option must be used with exactly one file name.");
  230. return 2;
  231. }
  232. if (useStdin) {
  233. log.error("The --print-config option is not available for piped-in code.");
  234. return 2;
  235. }
  236. const engine = new ESLint(translateOptions(options));
  237. const fileConfig =
  238. await engine.calculateConfigForFile(options.printConfig);
  239. log.info(JSON.stringify(fileConfig, null, " "));
  240. return 0;
  241. }
  242. debug(`Running on ${useStdin ? "text" : "files"}`);
  243. if (options.fix && options.fixDryRun) {
  244. log.error("The --fix option and the --fix-dry-run option cannot be used together.");
  245. return 2;
  246. }
  247. if (useStdin && options.fix) {
  248. log.error("The --fix option is not available for piped-in code; use --fix-dry-run instead.");
  249. return 2;
  250. }
  251. if (options.fixType && !options.fix && !options.fixDryRun) {
  252. log.error("The --fix-type option requires either --fix or --fix-dry-run.");
  253. return 2;
  254. }
  255. const engine = new ESLint(translateOptions(options));
  256. let results;
  257. if (useStdin) {
  258. results = await engine.lintText(text, {
  259. filePath: options.stdinFilename,
  260. warnIgnored: true
  261. });
  262. } else {
  263. results = await engine.lintFiles(files);
  264. }
  265. if (options.fix) {
  266. debug("Fix mode enabled - applying fixes");
  267. await ESLint.outputFixes(results);
  268. }
  269. let resultsToPrint = results;
  270. if (options.quiet) {
  271. debug("Quiet mode enabled - filtering out warnings");
  272. resultsToPrint = ESLint.getErrorResults(resultsToPrint);
  273. }
  274. if (await printResults(engine, resultsToPrint, options.format, options.outputFile)) {
  275. // Errors and warnings from the original unfiltered results should determine the exit code
  276. const { errorCount, warningCount } = countErrors(results);
  277. const tooManyWarnings =
  278. options.maxWarnings >= 0 && warningCount > options.maxWarnings;
  279. if (!errorCount && tooManyWarnings) {
  280. log.error(
  281. "ESLint found too many warnings (maximum: %s).",
  282. options.maxWarnings
  283. );
  284. }
  285. return (errorCount || tooManyWarnings) ? 1 : 0;
  286. }
  287. return 2;
  288. }
  289. };
  290. module.exports = cli;