BVB Source Codes

prettier Show prettier.js Source code

Return Download prettier: download prettier.js Source code - Download prettier Source code - Type:.js
  1. #!/usr/bin/env node
  2.  
  3. "use strict";
  4.  
  5. const fs = require("fs");
  6. const path = require("path");
  7. const getStdin = require("get-stdin");
  8. const glob = require("glob");
  9. const chalk = require("chalk");
  10. const minimist = require("minimist");
  11. const readline = require("readline");
  12. const prettier = eval("require")("../index");
  13. const cleanAST = require("../src/clean-ast.js").cleanAST;
  14.  
  15. const argv = minimist(process.argv.slice(2), {
  16.   boolean: [
  17.     "write",
  18.     "stdin",
  19.     "use-tabs",
  20.     "semi",
  21.     "single-quote",
  22.     "bracket-spacing",
  23.     "jsx-bracket-same-line",
  24.     // The supports-color package (a sub sub dependency) looks directly at
  25.     // `process.argv` for `--no-color` and such-like options. The reason it is
  26.     // listed here is to avoid "Ignored unknown option: --no-color" warnings.
  27.     // See https://github.com/chalk/supports-color/#info for more information.
  28.     "color",
  29.     "list-different",
  30.     "help",
  31.     "version",
  32.     "debug-print-doc",
  33.     "debug-check",
  34.     "with-node-modules",
  35.     // Deprecated in 0.0.10
  36.     "flow-parser"
  37.   ],
  38.   string: [
  39.     "print-width",
  40.     "tab-width",
  41.     "parser",
  42.     "trailing-comma",
  43.     "cursor-offset",
  44.     "range-start",
  45.     "range-end",
  46.     "stdin-filepath"
  47.   ],
  48.   default: {
  49.     semi: true,
  50.     color: true,
  51.     "bracket-spacing": true,
  52.     parser: "babylon"
  53.   },
  54.   alias: { help: "h", version: "v", "list-different": "l" },
  55.   unknown: param => {
  56.     if (param.startsWith("-")) {
  57.       console.warn("Ignored unknown option: " + param + "\n");
  58.       return false;
  59.     }
  60.   }
  61. });
  62.  
  63. if (argv["version"]) {
  64.   console.log(prettier.version);
  65.   process.exit(0);
  66. }
  67.  
  68. const filepatterns = argv["_"];
  69. const write = argv["write"];
  70. const stdin = argv["stdin"] || (!filepatterns.length && !process.stdin.isTTY);
  71. const ignoreNodeModules = argv["with-node-modules"] === false;
  72. const globOptions = {
  73.   ignore: ignoreNodeModules && "**/node_modules/**",
  74.   dot: true
  75. };
  76.  
  77. if (write && argv["debug-check"]) {
  78.   console.error("Cannot use --write and --debug-check together.");
  79.   process.exit(1);
  80. }
  81.  
  82. function getParserOption() {
  83.   const optionName = "parser";
  84.   const value = argv[optionName];
  85.  
  86.   if (value === undefined) {
  87.     return value;
  88.   }
  89.  
  90.   // For backward compatibility. Deprecated in 0.0.10
  91.   if (argv["flow-parser"]) {
  92.     console.warn("`--flow-parser` is deprecated. Use `--parser flow` instead.");
  93.     return "flow";
  94.   }
  95.  
  96.   if (
  97.     value === "flow" ||
  98.     value === "babylon" ||
  99.     value === "typescript" ||
  100.     value === "postcss"
  101.   ) {
  102.     return value;
  103.   }
  104.  
  105.   console.warn(
  106.     "Ignoring unknown --" +
  107.       optionName +
  108.       ' value, falling back to "babylon":\n' +
  109.       '  Expected "flow" or "babylon", but received: ' +
  110.       JSON.stringify(value)
  111.   );
  112.  
  113.   return "babylon";
  114. }
  115.  
  116. function getIntOption(optionName) {
  117.   const value = argv[optionName];
  118.  
  119.   if (value === undefined) {
  120.     return value;
  121.   }
  122.  
  123.   if (/^\d+$/.test(value)) {
  124.     return Number(value);
  125.   }
  126.  
  127.   console.error(
  128.     "Invalid --" +
  129.       optionName +
  130.       " value. Expected an integer, but received: " +
  131.       JSON.stringify(value)
  132.   );
  133.   process.exit(1);
  134. }
  135.  
  136. function getTrailingComma() {
  137.   switch (argv["trailing-comma"]) {
  138.     case undefined:
  139.     case "none":
  140.       return "none";
  141.     case "":
  142.       console.warn(
  143.         "Warning: `--trailing-comma` was used without an argument. This is deprecated. " +
  144.           'Specify "none", "es5", or "all".'
  145.       );
  146.       return "es5";
  147.     case "es5":
  148.       return "es5";
  149.     case "all":
  150.       return "all";
  151.     default:
  152.       throw new Error("Invalid option for --trailing-comma");
  153.   }
  154. }
  155.  
  156. const options = {
  157.   cursorOffset: getIntOption("cursor-offset"),
  158.   rangeStart: getIntOption("range-start"),
  159.   rangeEnd: getIntOption("range-end"),
  160.   useTabs: argv["use-tabs"],
  161.   semi: argv["semi"],
  162.   printWidth: getIntOption("print-width"),
  163.   tabWidth: getIntOption("tab-width"),
  164.   bracketSpacing: argv["bracket-spacing"],
  165.   singleQuote: argv["single-quote"],
  166.   jsxBracketSameLine: argv["jsx-bracket-same-line"],
  167.   filepath: argv["stdin-filepath"],
  168.   trailingComma: getTrailingComma(),
  169.   parser: getParserOption()
  170. };
  171.  
  172. function format(input, opt) {
  173.   if (argv["debug-print-doc"]) {
  174.     const doc = prettier.__debug.printToDoc(input, opt);
  175.     return prettier.__debug.formatDoc(doc);
  176.   }
  177.  
  178.   if (argv["debug-check"]) {
  179.     function diff(a, b) {
  180.       return require("diff").createTwoFilesPatch("", "", a, b, "", "", {
  181.         context: 2
  182.       });
  183.     }
  184.  
  185.     const pp = prettier.format(input, opt);
  186.     const pppp = prettier.format(pp, opt);
  187.     if (pp !== pppp) {
  188.       throw "prettier(input) !== prettier(prettier(input))\n" + diff(pp, pppp);
  189.     } else {
  190.       const ast = cleanAST(prettier.__debug.parse(input, opt));
  191.       const past = cleanAST(prettier.__debug.parse(pp, opt));
  192.  
  193.       if (ast !== past) {
  194.         const MAX_AST_SIZE = 2097152; // 2MB
  195.         const astDiff = ast.length > MAX_AST_SIZE || past.length > MAX_AST_SIZE
  196.           ? "AST diff too large to render"
  197.           : diff(ast, past);
  198.         throw "ast(input) !== ast(prettier(input))\n" +
  199.           astDiff +
  200.           "\n" +
  201.           diff(input, pp);
  202.       }
  203.     }
  204.     return {};
  205.   }
  206.  
  207.   return prettier.formatWithCursor(input, opt);
  208. }
  209.  
  210. function handleError(filename, e) {
  211.   const isParseError = Boolean(e && e.loc);
  212.   const isValidationError = /Validation Error/.test(e && e.message);
  213.  
  214.   // For parse errors and validation errors, we only want to show the error
  215.   // message formatted in a nice way. `String(e)` takes care of that. Other
  216.   // (unexpected) errors are passed as-is as a separate argument to
  217.   // `console.error`. That includes the stack trace (if any), and shows a nice
  218.   // `util.inspect` of throws things that aren't `Error` objects. (The Flow
  219.   // parser has mistakenly thrown arrays sometimes.)
  220.   if (isParseError) {
  221.     console.error(filename + ": " + String(e));
  222.   } else if (isValidationError) {
  223.     console.error(String(e));
  224.     // If validation fails for one file, it will fail for all of them.
  225.     process.exit(1);
  226.   } else {
  227.     console.error(filename + ":", e.stack || e);
  228.   }
  229.  
  230.   // Don't exit the process if one file failed
  231.   process.exitCode = 2;
  232. }
  233.  
  234. if (argv["help"] || (!filepatterns.length && !stdin)) {
  235.   console.log(
  236.     "Usage: prettier [opts] [filename ...]\n\n" +
  237.       "Available options:\n" +
  238.       "  --write                  Edit the file in-place. (Beware!)\n" +
  239.       "  --list-different or -l   Print filenames of files that are different from Prettier formatting.\n" +
  240.       "  --stdin                  Read input from stdin.\n" +
  241.       "  --stdin-filepath         Path to the file used to read from stdin.\n" +
  242.       "  --print-width <int>      Specify the length of line that the printer will wrap on. Defaults to 80.\n" +
  243.       "  --tab-width <int>        Specify the number of spaces per indentation-level. Defaults to 2.\n" +
  244.       "  --use-tabs               Indent lines with tabs instead of spaces.\n" +
  245.       "  --no-semi                Do not print semicolons, except at the beginning of lines which may need them.\n" +
  246.       "  --single-quote           Use single quotes instead of double quotes.\n" +
  247.       "  --no-bracket-spacing     Do not print spaces between brackets.\n" +
  248.       "  --jsx-bracket-same-line  Put > on the last line instead of at a new line.\n" +
  249.       "  --trailing-comma <none|es5|all>\n" +
  250.       "                           Print trailing commas wherever possible. Defaults to none.\n" +
  251.       "  --parser <flow|babylon|typescript|postcss>\n" +
  252.       "                           Specify which parse to use. Defaults to babylon.\n" +
  253.       "  --cursor-offset <int>    Print (to stderr) where a cursor at the given position would move to after formatting.\n" +
  254.       "                           This option cannot be used with --range-start and --range-end\n" +
  255.       "  --range-start <int>      Format code starting at a given character offset.\n" +
  256.       "                           The range will extend backwards to the start of the first line containing the selected statement.\n" +
  257.       "                           This option cannot be used with --cursor-offset.\n" +
  258.       "                           Defaults to 0.\n" +
  259.       "  --range-end <int>        Format code ending at a given character offset (exclusive).\n" +
  260.       "                           The range will extend forwards to the end of the selected statement.\n" +
  261.       "                           This option cannot be used with --cursor-offset.\n" +
  262.       "                           Defaults to Infinity.\n" +
  263.       "  --no-color               Do not colorize error messages.\n" +
  264.       "  --with-node-modules      Process files inside `node_modules` directory.\n" +
  265.       "  --version or -v          Print Prettier version.\n" +
  266.       "\n"
  267.   );
  268.   process.exit(argv["help"] ? 0 : 1);
  269. }
  270.  
  271. if (stdin) {
  272.   getStdin().then(input => {
  273.     try {
  274.       writeOutput(format(input, options));
  275.     } catch (e) {
  276.       handleError("stdin", e);
  277.       return;
  278.     }
  279.   });
  280. } else {
  281.   eachFilename(filepatterns, filename => {
  282.     if (write || argv["debug-check"]) {
  283.       // Don't use `console.log` here since we need to replace this line.
  284.       process.stdout.write(filename);
  285.     }
  286.  
  287.     let input;
  288.     try {
  289.       input = fs.readFileSync(filename, "utf8");
  290.     } catch (e) {
  291.       // Add newline to split errors from filename line.
  292.       process.stdout.write("\n");
  293.  
  294.       console.error("Unable to read file: " + filename + "\n" + e);
  295.       // Don't exit the process if one file failed
  296.       process.exitCode = 2;
  297.       return;
  298.     }
  299.  
  300.     if (argv["list-different"]) {
  301.       if (!prettier.check(input, options)) {
  302.         if (!write) {
  303.           console.log(filename);
  304.         }
  305.         process.exitCode = 1;
  306.       }
  307.     }
  308.  
  309.     const start = Date.now();
  310.  
  311.     let result;
  312.     let output;
  313.  
  314.     try {
  315.       result = format(
  316.         input,
  317.         Object.assign({}, options, { filepath: filename })
  318.       );
  319.       output = result.formatted;
  320.     } catch (e) {
  321.       // Add newline to split errors from filename line.
  322.       process.stdout.write("\n");
  323.  
  324.       handleError(filename, e);
  325.       return;
  326.     }
  327.  
  328.     if (write) {
  329.       // Remove previously printed filename to log it with duration.
  330.       readline.clearLine(process.stdout, 0);
  331.       readline.cursorTo(process.stdout, 0, null);
  332.  
  333.       // Don't write the file if it won't change in order not to invalidate
  334.       // mtime based caches.
  335.       if (output === input) {
  336.         if (!argv["list-different"]) {
  337.           console.log(chalk.grey("%s %dms"), filename, Date.now() - start);
  338.         }
  339.       } else {
  340.         if (argv["list-different"]) {
  341.           console.log(filename);
  342.         } else {
  343.           console.log("%s %dms", filename, Date.now() - start);
  344.         }
  345.  
  346.         try {
  347.           fs.writeFileSync(filename, output, "utf8");
  348.         } catch (err) {
  349.           console.error("Unable to write file: " + filename + "\n" + err);
  350.           // Don't exit the process if one file failed
  351.           process.exitCode = 2;
  352.         }
  353.       }
  354.     } else if (argv["debug-check"]) {
  355.       process.stdout.write("\n");
  356.       if (output) {
  357.         console.log(output);
  358.       } else {
  359.         process.exitCode = 2;
  360.       }
  361.     } else if (!argv["list-different"]) {
  362.       writeOutput(result);
  363.     }
  364.   });
  365. }
  366.  
  367. function writeOutput(result) {
  368.   // Don't use `console.log` here since it adds an extra newline at the end.
  369.   process.stdout.write(result.formatted);
  370.  
  371.   if (options.cursorOffset) {
  372.     process.stderr.write(result.cursorOffset + "\n");
  373.   }
  374. }
  375.  
  376. function eachFilename(patterns, callback) {
  377.   patterns.forEach(pattern => {
  378.     if (!glob.hasMagic(pattern)) {
  379.       if (shouldIgnorePattern(pattern)) {
  380.         return;
  381.       }
  382.       callback(pattern);
  383.       return;
  384.     }
  385.  
  386.     glob(pattern, globOptions, (err, filenames) => {
  387.       if (err) {
  388.         console.error("Unable to expand glob pattern: " + pattern + "\n" + err);
  389.         // Don't exit the process if one pattern failed
  390.         process.exitCode = 2;
  391.         return;
  392.       }
  393.  
  394.       filenames.forEach(filename => {
  395.         callback(filename);
  396.       });
  397.     });
  398.   });
  399. }
  400.  
  401. function shouldIgnorePattern(pattern) {
  402.   return ignoreNodeModules && path.resolve(pattern).includes("/node_modules/");
  403. }
  404.  
downloadprettier.js Source code - Download prettier Source code
Related Source Codes/Software:
storybook - 2017-06-07
ionicons - The premium icon font for Ionic ... 2017-06-07
AsyncDisplayKit - Smooth asynchronous user interfaces for iOS apps. ... 2017-06-07
lottie-android - Render After Effects animations natively on Androi... 2017-06-07
parse-server - Parse-compatible API server module for Node/Expres... 2017-06-07
inferno - An extremely fast, React-like JavaScript library f... 2017-06-08
guetzli - Perceptual JPEG encoder 2017-06-08
cs-video-courses - List of Computer Science courses with video lectur... 2017-06-08
interviews - Everything you need to know to get the job. 2017-06-08
prepack - Prepack is a partial evaluator for JavaScript. Pre... 2017-06-08
CRYENGINE - CRYENGINE is a powerful real-time game development... 2017-06-11
postal - 2017-06-11
reactide - Reactide is the first dedicated IDE for React web ... 2017-06-11
rkt - rkt is a pod-native container engine for Linux. It... 2017-06-11
uWebSockets - Tiny WebSockets https://for... 2017-06-11
realworld - TodoMVC for the RealWorld - Exemplary fullstack Me... 2017-06-11
goreplay - GoReplay is an open-source tool for capturing and ... 2017-06-10
pyenv - Simple Python version management 2017-06-10
redux-saga - An alternative side effect model for Redux apps ... 2017-06-10
angular-starter - 2017-06-10

 Back to top