From 6b3d3bc066c415c8a5f9dc96c3984e0b5fc8ef5e Mon Sep 17 00:00:00 2001 From: Simon Lydell Date: Mon, 23 Jan 2017 16:37:57 +0100 Subject: [PATCH] Add glob support to the CLI (#363) * Add glob support to the CLI Fixes #145. Fixes #362. * Update README.md regarding globs * Use exact dependency for glob --- README.md | 4 ++-- bin/prettier.js | 24 +++++++++++++++++++++--- package.json | 1 + yarn.lock | 2 +- 4 files changed, 25 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 832c6e6d8..ffdbbddb4 100644 --- a/README.md +++ b/README.md @@ -117,9 +117,9 @@ should probably commit your code before doing that. prettier [opts] [filename ...] ``` -For example, you could format your source using bash filename expansion: +For easier cross-platform usage, prettier has built-in glob support: ```bash -prettier --write src/**/*.js bin/*.js +prettier --write 'src/**/*.js' 'bin/*.js' ``` In the future we will have better support for formatting whole projects. diff --git a/bin/prettier.js b/bin/prettier.js index 781b721ed..faff9be4e 100755 --- a/bin/prettier.js +++ b/bin/prettier.js @@ -3,6 +3,7 @@ "use strict"; const fs = require("fs"); const getStdin = require("get-stdin"); +const glob = require("glob"); const minimist = require("minimist"); const prettier = require("../index"); @@ -32,11 +33,11 @@ if (argv["version"]) { process.exit(0); } -const filenames = argv["_"]; +const filepatterns = argv["_"]; const write = argv["write"]; const stdin = argv["stdin"]; -if (!filenames.length && !stdin) { +if (!filepatterns.length && !stdin) { console.log( "Usage: prettier [opts] [filename ...]\n\n" + "Available options:\n" + @@ -95,7 +96,7 @@ if (stdin) { } }); } else { - filenames.forEach(filename => { + eachFilename(filepatterns, filename => { fs.readFile(filename, "utf8", (err, input) => { if (write) { console.log(filename); @@ -131,3 +132,20 @@ if (stdin) { }); }); } + +function eachFilename(patterns, callback) { + patterns.forEach(pattern => { + glob(pattern, (err, filenames) => { + if (err) { + console.error("Unable to expand glob pattern: " + pattern + "\n" + err); + // Don't exit the process if one pattern failed + process.exitCode = 2; + return; + } + + filenames.forEach(filename => { + callback(filename); + }); + }); + }); +} diff --git a/package.json b/package.json index b28bbdab8..95d1c7cc1 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "esutils": "2.0.2", "flow-parser": "0.38.0", "get-stdin": "5.0.1", + "glob": "7.1.1", "minimist": "1.2.0" }, "devDependencies": { diff --git a/yarn.lock b/yarn.lock index d35940e96..3db576063 100644 --- a/yarn.lock +++ b/yarn.lock @@ -963,7 +963,7 @@ glob-parent@^2.0.0: dependencies: is-glob "^2.0.0" -glob@^7.0.3, glob@^7.0.5: +glob@^7.0.3, glob@^7.0.5, glob@^7.1.1: version "7.1.1" resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.1.tgz#805211df04faaf1c63a3600306cdf5ade50b2ec8" dependencies: