From eff5af6ca9d2b35b187c21d5e199416af806a986 Mon Sep 17 00:00:00 2001 From: Brian Holt Date: Mon, 3 Apr 2017 09:54:10 -0700 Subject: [PATCH] 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 --- README.md | 5 ++++- bin/prettier.js | 13 ++++++++----- index.js | 8 ++++++++ 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 33f76b12..96fc88f9 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/bin/prettier.js b/bin/prettier.js index e2e73572..73017658 100755 --- a/bin/prettier.js +++ b/bin/prettier.js @@ -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); diff --git a/index.js b/index.js index 8fc86a56..67350517 100644 --- a/index.js +++ b/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) {