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.

146 lines
4.3 KiB

4 years ago
  1. #!/usr/bin/env node
  2. /**
  3. * @fileoverview Main CLI that is run via the eslint command.
  4. * @author Nicholas C. Zakas
  5. */
  6. /* eslint no-console:off */
  7. "use strict";
  8. // to use V8's code cache to speed up instantiation time
  9. require("v8-compile-cache");
  10. // must do this initialization *before* other requires in order to work
  11. if (process.argv.includes("--debug")) {
  12. require("debug").enable("eslint:*,-eslint:code-path");
  13. }
  14. //------------------------------------------------------------------------------
  15. // Helpers
  16. //------------------------------------------------------------------------------
  17. /**
  18. * Read data from stdin til the end.
  19. *
  20. * Note: See
  21. * - https://github.com/nodejs/node/blob/master/doc/api/process.md#processstdin
  22. * - https://github.com/nodejs/node/blob/master/doc/api/process.md#a-note-on-process-io
  23. * - https://lists.gnu.org/archive/html/bug-gnu-emacs/2016-01/msg00419.html
  24. * - https://github.com/nodejs/node/issues/7439 (historical)
  25. *
  26. * On Windows using `fs.readFileSync(STDIN_FILE_DESCRIPTOR, "utf8")` seems
  27. * to read 4096 bytes before blocking and never drains to read further data.
  28. *
  29. * The investigation on the Emacs thread indicates:
  30. *
  31. * > Emacs on MS-Windows uses pipes to communicate with subprocesses; a
  32. * > pipe on Windows has a 4K buffer. So as soon as Emacs writes more than
  33. * > 4096 bytes to the pipe, the pipe becomes full, and Emacs then waits for
  34. * > the subprocess to read its end of the pipe, at which time Emacs will
  35. * > write the rest of the stuff.
  36. * @returns {Promise<string>} The read text.
  37. */
  38. function readStdin() {
  39. return new Promise((resolve, reject) => {
  40. let content = "";
  41. let chunk = "";
  42. process.stdin
  43. .setEncoding("utf8")
  44. .on("readable", () => {
  45. while ((chunk = process.stdin.read()) !== null) {
  46. content += chunk;
  47. }
  48. })
  49. .on("end", () => resolve(content))
  50. .on("error", reject);
  51. });
  52. }
  53. /**
  54. * Get the error message of a given value.
  55. * @param {any} error The value to get.
  56. * @returns {string} The error message.
  57. */
  58. function getErrorMessage(error) {
  59. // Lazy loading because those are used only if error happened.
  60. const fs = require("fs");
  61. const path = require("path");
  62. const util = require("util");
  63. const lodash = require("lodash");
  64. // Foolproof -- thirdparty module might throw non-object.
  65. if (typeof error !== "object" || error === null) {
  66. return String(error);
  67. }
  68. // Use templates if `error.messageTemplate` is present.
  69. if (typeof error.messageTemplate === "string") {
  70. try {
  71. const templateFilePath = path.resolve(
  72. __dirname,
  73. `../messages/${error.messageTemplate}.txt`
  74. );
  75. // Use sync API because Node.js should exit at this tick.
  76. const templateText = fs.readFileSync(templateFilePath, "utf-8");
  77. const template = lodash.template(templateText);
  78. return template(error.messageData || {});
  79. } catch {
  80. // Ignore template error then fallback to use `error.stack`.
  81. }
  82. }
  83. // Use the stacktrace if it's an error object.
  84. if (typeof error.stack === "string") {
  85. return error.stack;
  86. }
  87. // Otherwise, dump the object.
  88. return util.format("%o", error);
  89. }
  90. /**
  91. * Catch and report unexpected error.
  92. * @param {any} error The thrown error object.
  93. * @returns {void}
  94. */
  95. function onFatalError(error) {
  96. process.exitCode = 2;
  97. const { version } = require("../package.json");
  98. const message = getErrorMessage(error);
  99. console.error(`
  100. Oops! Something went wrong! :(
  101. ESLint: ${version}
  102. ${message}`);
  103. }
  104. //------------------------------------------------------------------------------
  105. // Execution
  106. //------------------------------------------------------------------------------
  107. (async function main() {
  108. process.on("uncaughtException", onFatalError);
  109. process.on("unhandledRejection", onFatalError);
  110. // Call the config initializer if `--init` is present.
  111. if (process.argv.includes("--init")) {
  112. await require("../lib/init/config-initializer").initializeConfig();
  113. return;
  114. }
  115. // Otherwise, call the CLI.
  116. process.exitCode = await require("../lib/cli").execute(
  117. process.argv,
  118. process.argv.includes("--stdin") ? await readStdin() : null
  119. );
  120. }()).catch(onFatalError);