Add check method to Prettier Node API. (#1104)

* Add check method to Prettier. Make CLI use that method for list-different

* Catch in check and return false if it throws

* Remove catch/finally from Prettier list-different bin

* remove try catch in prettier bin for list-different
master
Brian Holt 2017-04-03 09:54:10 -07:00 committed by Christopher Chedeau
parent 2c9af5ffcc
commit eff5af6ca9
3 changed files with 20 additions and 6 deletions

View File

@ -175,7 +175,7 @@ exit 1
### API
The API is a single function exported as `format`. The options
The API has two functions, exported as `format` and `check`. The options
argument is optional, and all of the defaults are shown below:
```js
@ -212,6 +212,9 @@ prettier.format(source, {
});
```
`check` checks to see if the file has been formatted with prettier given the those options and returns a Boolean.
This is similar to the `--list-different` parameter in the CLI and is useful for running Prettier in CI scenarios.
### Excluding code from formatting
A JavaScript comment of `// prettier-ignore` will exclude the next node in the abstract syntax tree from formatting.

View File

@ -228,6 +228,14 @@ if (stdin) {
return;
}
if (argv["list-different"]) {
if (!prettier.check(input, options)) {
console.log(filename);
process.exitCode = 1;
}
return;
}
const start = Date.now();
let output;
@ -267,11 +275,6 @@ if (stdin) {
if (output) {
console.log(output);
}
} else if (argv["list-different"]) {
if (input !== output) {
console.log(filename);
process.exitCode = 1;
}
} else {
// Don't use `console.log` here since it adds an extra newline at the end.
process.stdout.write(output);

View File

@ -95,6 +95,14 @@ module.exports = {
format: function(text, opts) {
return formatWithShebang(text, normalizeOptions(opts));
},
check: function(text, opts) {
try {
const formatted = this.format(text, opts);
return formatted === text;
} catch (e) {
return false;
}
},
version: version,
__debug: {
formatAST: function(ast, opts) {