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-differentmaster
parent
2c9af5ffcc
commit
eff5af6ca9
|
@ -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.
|
||||
|
|
|
@ -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);
|
||||
|
|
8
index.js
8
index.js
|
@ -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) {
|
||||
|
|
Loading…
Reference in New Issue