Allow `--write` to be used with `--list-different` (#1633)

* Allow `--write` to be used with `--list-different`

This makes it possible to simultaneously check for formatting errors and
fix them, which can be useful for CI services. For example, a CI service
could run:

    prettier --list-different --write $FILES || git diff --exit-code

to show the formatting errors. Before this change, it would be necessary
to do:

    prettier --list-different $FILES || (prettier --write $FILES; git diff --exit-code)

Here are some commands which are useful to verify that the outputs and
exit codes of `prettier --list-different` and `prettier --write` have
not changed:

    ./bin/prettier.js --list-different index.js src/*.js bin/*.js; echo $?
    ./bin/prettier.js --write index.js src/*.js bin/*.js; echo $?

* fixup! Allow `--write` to be used with `--list-different`
master
Joseph Frazier 2017-05-21 11:12:00 -04:00 committed by Christopher Chedeau
parent 83fe8d3d18
commit 226adb2e81
1 changed files with 12 additions and 5 deletions

View File

@ -256,10 +256,11 @@ if (stdin) {
if (argv["list-different"]) {
if (!prettier.check(input, options)) {
console.log(filename);
if (!write) {
console.log(filename);
}
process.exitCode = 1;
}
return;
}
const start = Date.now();
@ -284,9 +285,15 @@ if (stdin) {
// Don't write the file if it won't change in order not to invalidate
// mtime based caches.
if (output === input) {
console.log(chalk.grey("%s %dms"), filename, Date.now() - start);
if (!argv["list-different"]) {
console.log(chalk.grey("%s %dms"), filename, Date.now() - start);
}
} else {
console.log("%s %dms", filename, Date.now() - start);
if (argv["list-different"]) {
console.log(filename);
} else {
console.log("%s %dms", filename, Date.now() - start);
}
try {
fs.writeFileSync(filename, output, "utf8");
@ -303,7 +310,7 @@ if (stdin) {
} else {
process.exitCode = 2;
}
} else {
} else if (!argv["list-different"]) {
// Don't use `console.log` here since it adds an extra newline at the end.
process.stdout.write(output);
}