<commit_before>#!/usr/bin/env node

"use strict";
const fs = require("fs");
const getStdin = require("get-stdin");
const glob = require("glob");
const minimist = require("minimist");
const prettier = require("../index");

const argv = minimist(process.argv.slice(2), {
  boolean: [
    "write",
    "stdin",
    "single-quote",
    "trailing-comma",
    "bracket-spacing",
    // The supports-color package (a sub sub dependency) looks directly at
    // `process.argv` for `--no-color` and such-like options. The reason it is
    // listed here is to avoid "Ignored unknown option: --no-color" warnings.
    // See https://github.com/chalk/supports-color/#info for more information.
    "color",
    "version",
    "debug-print-doc",
    // Deprecated in 0.0.10
    "flow-parser"
  ],
  string: [ "print-width", "tab-width", "parser" ],
  default: { color: true, "bracket-spacing": true, parser: "babylon" },
  unknown: param => {
    if (param.startsWith("-")) {
      console.warn("Ignored unknown option: " + param + "\n");
    }
  }
});

if (argv["version"]) {
  console.log(prettier.version);
  process.exit(0);
}

const filepatterns = argv["_"];
const write = argv["write"];
const stdin = argv["stdin"];

if (!filepatterns.length && !stdin) {
  console.log(
    "Usage: prettier [opts] [filename ...]\n\n" +
      "Available options:\n" +
      "  --write                  Edit the file in-place. (Beware!)\n" +
      "  --stdin                  Read input from stdin.\n" +
      "  --print-width <int>      Specify the length of line that the printer will wrap on. Defaults to 80.\n" +
      "  --tab-width <int>        Specify the number of spaces per indentation-level. Defaults to 2.\n" +
      "  --single-quote           Use single quotes instead of double.\n" +
      "  --trailing-comma         Print trailing commas wherever possible.\n" +
      "  --bracket-spacing        Put spaces between brackets. Defaults to true.\n" +
      "  --parser <flow|babylon>  Specify which parse to use. Defaults to babylon.\n" +
      "  --color                  Colorize error messages. Defaults to true.\n" +
      "  --version                Print prettier version.\n" +
      "\n" +
      "Boolean options can be turned off like this:\n" +
      "  --no-bracket-spacing\n" +
      "  --bracket-spacing=false"
  );
  process.exit(1);
}

function getParser() {
  // For backward compatibility. Deprecated in 0.0.10
  if (argv["flow-parser"]) {
    console.warn("`--flow-parser` is deprecated. Use `--parser flow` instead.");
    return "flow";
  }

  if (argv["parser"] === "flow") {
    return "flow";
  }

  return "babylon";
}

const options = {
  printWidth: argv["print-width"] && parseInt(argv["print-width"]),
  tabWidth: argv["tab-width"] && parseInt(argv["tab-width"]),
  bracketSpacing: argv["bracket-spacing"],
  parser: getParser(),
  singleQuote: argv["single-quote"],
  trailingComma: argv["trailing-comma"]
};

function format(input) {
  if (argv["debug-print-doc"]) {
    const doc = prettier.__debug.printToDoc(input, options);
    return prettier.__debug.formatDoc(doc);
  }
  return prettier.format(input, options);
}

if (stdin) {
  getStdin().then(input => {
    try {
      // Don't use `console.log` here since it adds an extra newline at the end.
      process.stdout.write(format(input));
    } catch (e) {
      process.exitCode = 2;
      console.error("stdin: " + e);
      return;
    }
  });
} else {
  eachFilename(filepatterns, filename => {
    fs.readFile(filename, "utf8", (err, input) => {
      if (write) {
        console.log(filename);
      }

      if (err) {
        console.error("Unable to read file: " + filename + "\n" + err);
        // Don't exit the process if one file failed
        process.exitCode = 2;
        return;
      }

      let output;
      try {
        output = format(input);
      } catch (e) {
        process.exitCode = 2;
        if(e.loc) {
          console.error(filename + ": " + e);
        }
        else {
          console.error(filename + ":", e);
        }
        return;
      }

      if (write) {
        fs.writeFile(filename, output, "utf8", err => {
          if (err) {
            console.error("Unable to write file: " + filename + "\n" + err);
            // Don't exit the process if one file failed
            process.exitCode = 2;
          }
        });
      } else {
        // Don't use `console.log` here since it adds an extra newline at the end.
        process.stdout.write(output);
      }
    });
  });
}

function eachFilename(patterns, callback) {
  patterns.forEach(pattern => {<commit_msg>CLI improvements (#478)<commit_after>#!/usr/bin/env node

"use strict";
const fs = require("fs");
const getStdin = require("get-stdin");
const glob = require("glob");
const minimist = require("minimist");
const prettier = require("../index");

const argv = minimist(process.argv.slice(2), {
  boolean: [
    "write",
    "stdin",
    "single-quote",
    "trailing-comma",
    "bracket-spacing",
    // The supports-color package (a sub sub dependency) looks directly at
    // `process.argv` for `--no-color` and such-like options. The reason it is
    // listed here is to avoid "Ignored unknown option: --no-color" warnings.
    // See https://github.com/chalk/supports-color/#info for more information.
    "color",
    "help",
    "version",
    "debug-print-doc",
    // Deprecated in 0.0.10
    "flow-parser"
  ],
  string: ["print-width", "tab-width", "parser"],
  default: { color: true, "bracket-spacing": true, parser: "babylon" },
  alias: { help: "h", version: "v" },
  unknown: param => {
    if (param.startsWith("-")) {
      console.warn("Ignored unknown option: " + param + "\n");
      return false;
    }
  }
});

if (argv["version"]) {
  console.log(prettier.version);
  process.exit(0);
}

const filepatterns = argv["_"];
const write = argv["write"];
const stdin = argv["stdin"] || !filepatterns.length && !process.stdin.isTTY;

if (argv["help"] || !filepatterns.length && !stdin) {
  console.log(
    "Usage: prettier [opts] [filename ...]\n\n" +
      "Available options:\n" +
      "  --write                  Edit the file in-place. (Beware!)\n" +
      "  --stdin                  Read input from stdin.\n" +
      "  --print-width <int>      Specify the length of line that the printer will wrap on. Defaults to 80.\n" +
      "  --tab-width <int>        Specify the number of spaces per indentation-level. Defaults to 2.\n" +
      "  --single-quote           Use single quotes instead of double.\n" +
      "  --trailing-comma         Print trailing commas wherever possible.\n" +
      "  --bracket-spacing        Put spaces between brackets. Defaults to true.\n" +
      "  --parser <flow|babylon>  Specify which parse to use. Defaults to babylon.\n" +
      "  --color                  Colorize error messages. Defaults to true.\n" +
      "  --version                Print prettier version.\n" +
      "\n" +
      "Boolean options can be turned off like this:\n" +
      "  --no-bracket-spacing\n" +
      "  --bracket-spacing=false"
  );
  process.exit(argv["help"] ? 0 : 1);
}

function getParserOption() {
  const optionName = "parser";
  const value = argv[optionName];

  if (value === undefined) {
    return value;
  }

  // For backward compatibility. Deprecated in 0.0.10
  if (argv["flow-parser"]) {
    console.warn("`--flow-parser` is deprecated. Use `--parser flow` instead.");
    return "flow";
  }

  if (value === "flow" || value === "babylon") {
    return value;
  }

  console.warn(
    "Ignoring unknown --" +
      optionName +
      ' value, falling back to "babylon":\n' +
      '  Expected "flow" or "babylon", but received: ' +
      JSON.stringify(value)
  );

  return "babylon";
}

function getIntOption(optionName) {
  const value = argv[optionName];

  if (value === undefined) {
    return value;
  }

  if (/^\d+$/.test(value)) {
    return Number(value);
  }

  console.error(
    "Invalid --" +
      optionName +
      " value. Expected an integer, but received: " +
      JSON.stringify(value)
  );
  process.exit(1);
}

const options = {
  printWidth: getIntOption("print-width"),
  tabWidth: getIntOption("tab-width"),
  bracketSpacing: argv["bracket-spacing"],
  parser: getParserOption(),
  singleQuote: argv["single-quote"],
  trailingComma: argv["trailing-comma"]
};

function format(input) {
  if (argv["debug-print-doc"]) {
    const doc = prettier.__debug.printToDoc(input, options);
    return prettier.__debug.formatDoc(doc);
  }
  return prettier.format(input, options);
}

function handleError(filename, e) {
  const isParseError = Boolean(e && e.loc);
  const isValidationError = /Validation Error/.test(e && e.message);

  // For parse errors and validation errors, we only want to show the error
  // message formatted in a nice way. `String(e)` takes care of that. Other
  // (unexpected) errors are passed as-is as a separate argument to
  // `console.error`. That includes the stack trace (if any), and shows a nice
  // `util.inspect` of throws things that aren't `Error` objects. (The Flow
  // parser has mistakenly thrown arrays sometimes.)
  if (isParseError) {
    console.error(filename + ": " + String(e));
  } else if (isValidationError) {
    console.error(String(e));
    // If validation fails for one file, it will fail for all of them.
    process.exit(1);
  } else {
    console.error(filename + ":", e);
  }

  // Don't exit the process if one file failed
  process.exitCode = 2;
}

if (stdin) {
  getStdin().then(input => {
    try {
      // Don't use `console.log` here since it adds an extra newline at the end.
      process.stdout.write(format(input));
    } catch (e) {
      handleError("stdin", e);
      return;
    }
  });
} else {
  eachFilename(filepatterns, filename => {
    fs.readFile(filename, "utf8", (err, input) => {
      if (write) {
        console.log(filename);
      }

      if (err) {
        console.error("Unable to read file: " + filename + "\n" + err);
        // Don't exit the process if one file failed
        process.exitCode = 2;
        return;
      }

      let output;
      try {
        output = format(input);
      } catch (e) {
        handleError(filename, e);
        return;
      }

      if (write) {
        fs.writeFile(filename, output, "utf8", err => {
          if (err) {
            console.error("Unable to write file: " + filename + "\n" + err);
            // Don't exit the process if one file failed
            process.exitCode = 2;
          }
        });
      } else {
        // Don't use `console.log` here since it adds an extra newline at the end.
        process.stdout.write(output);
      }
    });
  });
}

function eachFilename(patterns, callback) {
  patterns.forEach(pattern => {
{'fraction_non_alphanumeric': 0.15425334323922735, 'fraction_numerical': 0.004179049034175334, 'mean_word_length': 2.3854133920150895, 'pattern_counts': {'":': 7, '<': 9, '<?xml version=': 0, '>': 21, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '569040', 'n_tokens_mistral': 3486, 'n_tokens_neox': 3380, 'n_words': 923}