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
This commit is contained in:
Simon Lydell authored and James Long committed 2017-01-23 10:37:57 -05:00
1 parent 515379435c
commit 6b3d3bc066
4 files changed
+25 -6

No files matched your search

+2 -2
View File
@@ -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.
+21 -3
View File
@@ -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);
});
});
});
}
+1
View File
@@ -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": {
+1 -1
View File
@@ -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: