cli.js 9.6 KB

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