Skip to content

Commit 79f8b90

Browse files
committed
feat(bin): Support globs on windows and use smarter recursion
This brings logic from eslint over to documentation: instead of readdirSync, we're using the glob module. This also, I hope, will let us support globs on Windows without changing OSX/Linux behavior. Fixes #607
1 parent a4eddba commit 79f8b90

File tree

9 files changed

+208
-70
lines changed

9 files changed

+208
-70
lines changed

LICENSE

+25
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,28 @@ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
1313
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
1414
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
1515
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16+
17+
--------------------------------------------------------------------------------
18+
19+
Contains sections of eslint
20+
21+
ESLint
22+
Copyright JS Foundation and other contributors, https://js.foundation
23+
24+
Permission is hereby granted, free of charge, to any person obtaining a copy
25+
of this software and associated documentation files (the "Software"), to deal
26+
in the Software without restriction, including without limitation the rights
27+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
28+
copies of the Software, and to permit persons to whom the Software is
29+
furnished to do so, subject to the following conditions:
30+
31+
The above copyright notice and this permission notice shall be included in
32+
all copies or substantial portions of the Software.
33+
34+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
35+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
36+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
37+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
38+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
39+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
40+
THE SOFTWARE.

index.js

-8
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ var fs = require('fs'),
55
sort = require('./lib/sort'),
66
nest = require('./lib/nest'),
77
filterAccess = require('./lib/filter_access'),
8-
filterJS = require('./lib/filter_js'),
98
dependency = require('./lib/input/dependency'),
109
shallow = require('./lib/input/shallow'),
1110
parseJavaScript = require('./lib/parsers/javascript'),
@@ -214,8 +213,6 @@ function buildSync(indexes, options) {
214213
options.github && github,
215214
garbageCollect);
216215

217-
var jsFilterer = filterJS(options.extension, options.polyglot);
218-
219216
return filterAccess(options.access,
220217
hierarchy(
221218
sort(
@@ -231,10 +228,6 @@ function buildSync(indexes, options) {
231228
indexObject = index;
232229
}
233230

234-
if (!jsFilterer(indexObject)) {
235-
return [];
236-
}
237-
238231
return parseFn(indexObject, options).map(buildPipeline);
239232
})
240233
.filter(Boolean), options)));
@@ -309,7 +302,6 @@ function lint(indexes, options, callback) {
309302
callback(null,
310303
formatLint(hierarchy(
311304
inputs
312-
.filter(filterJS(options.extension, options.polyglot))
313305
.reduce(function (memo, file) {
314306
return memo.concat(parseFn(file, options).map(lintPipeline));
315307
}, [])

lib/input/dependency.js

+19-15
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
'use strict';
22

3-
var mdeps = require('module-deps-sortable'),
4-
fs = require('fs'),
5-
path = require('path'),
6-
babelify = require('babelify'),
7-
filterJS = require('../filter_js'),
8-
concat = require('concat-stream'),
9-
moduleFilters = require('../../lib/module_filters'),
10-
expandDirectories = require('./expand_directories');
3+
var mdeps = require('module-deps-sortable');
4+
var fs = require('fs');
5+
var path = require('path');
6+
var babelify = require('babelify');
7+
var filterJS = require('../filter_js');
8+
var concat = require('concat-stream');
9+
var moduleFilters = require('../../lib/module_filters');
10+
var smartGlob = require('../smart_glob.js');
1111

1212
/**
1313
* Returns a readable stream of dependencies, given an array of entry
@@ -23,7 +23,6 @@ var mdeps = require('module-deps-sortable'),
2323
*/
2424
function dependencyStream(indexes, options, callback) {
2525
var filterer = filterJS(options.extension, options.polyglot);
26-
2726
var md = mdeps({
2827
/**
2928
* Determine whether a module should be included in documentation
@@ -34,6 +33,9 @@ function dependencyStream(indexes, options, callback) {
3433
return !!options.external || moduleFilters.internalOnly(id);
3534
},
3635
extensions: [].concat(options.extension || [])
36+
// We don't document JSON files, but we do include them in this list,
37+
// because browserify & node both support unnamed requires to .json
38+
// files: `require('foo')` can require `foo.json` automatically.
3739
.concat(['js', 'es6', 'jsx', 'json'])
3840
.map(function (ext) {
3941
return '.' + ext;
@@ -55,19 +57,21 @@ function dependencyStream(indexes, options, callback) {
5557
})],
5658
postFilter: moduleFilters.externals(indexes, options)
5759
});
58-
expandDirectories(indexes, filterer).forEach(function (index) {
60+
smartGlob(indexes, options.extension).forEach(function (index) {
5961
md.write(path.resolve(index));
6062
});
6163
md.end();
6264
md.once('error', function (error) {
6365
return callback(error);
6466
});
6567
md.pipe(concat(function (inputs) {
66-
callback(null, inputs.map(function (input) {
67-
// un-transform babelify transformed source
68-
input.source = fs.readFileSync(input.file, 'utf8');
69-
return input;
70-
}));
68+
callback(null, inputs
69+
.filter(filterer)
70+
.map(function (input) {
71+
// un-transform babelify transformed source
72+
input.source = fs.readFileSync(input.file, 'utf8');
73+
return input;
74+
}));
7175
}));
7276
}
7377

lib/input/expand_directories.js

-40
This file was deleted.

lib/input/shallow.js

+13-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
'use strict';
22

3-
var filterJS = require('../filter_js');
4-
var expandDirectories = require('./expand_directories');
3+
var smartGlob = require('../smart_glob.js');
54

65
/**
76
* A readable source for content that doesn't do dependency resolution, but
@@ -21,6 +20,16 @@ var expandDirectories = require('./expand_directories');
2120
* @return {undefined} calls callback
2221
*/
2322
module.exports = function (indexes, options, callback) {
24-
var filterer = filterJS(options.extension, options.polyglot);
25-
return callback(null, expandDirectories(indexes, filterer));
23+
var objects = [];
24+
var strings = [];
25+
indexes.forEach(function (index) {
26+
if (typeof index === 'string') {
27+
strings.push(index);
28+
} else if (typeof index === 'object') {
29+
objects.push(index);
30+
} else {
31+
throw new Error('indexes should be either strings or objects');
32+
}
33+
});
34+
return callback(null, objects.concat(smartGlob(strings, options.extension)));
2635
};

lib/smart_glob.js

+137
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
var fs = require('fs');
2+
var path = require('path');
3+
var glob = require('glob');
4+
var shell = require('shelljs');
5+
6+
/**
7+
* Replace Windows with posix style paths
8+
*
9+
* @param {string} filepath Path to convert
10+
* @returns {string} Converted filepath
11+
*/
12+
function convertPathToPosix(filepath) {
13+
var normalizedFilepath = path.normalize(filepath);
14+
var posixFilepath = normalizedFilepath.replace(/\\/g, '/');
15+
16+
return posixFilepath;
17+
}
18+
19+
/**
20+
* Checks if a provided path is a directory and returns a glob string matching
21+
* all files under that directory if so, the path itself otherwise.
22+
*
23+
* Reason for this is that `glob` needs `/**` to collect all the files under a
24+
* directory where as our previous implementation without `glob` simply walked
25+
* a directory that is passed. So this is to maintain backwards compatibility.
26+
*
27+
* Also makes sure all path separators are POSIX style for `glob` compatibility.
28+
*
29+
* @param {Object} [options] An options object
30+
* @param {string[]} [options.extensions=['.js']] An array of accepted extensions
31+
* @param {string} [options.cwd=process.cwd()] The cwd to use to resolve relative pathnames
32+
* @returns {Function} A function that takes a pathname and returns a glob that
33+
* matches all files with the provided extensions if
34+
* pathname is a directory.
35+
*/
36+
function processPath(options) {
37+
var cwd = (options && options.cwd) || process.cwd();
38+
var extensions = (options && options.extensions) || ['.js'];
39+
40+
extensions = extensions.map(function (ext) {
41+
return ext.replace(/^\./, '');
42+
});
43+
44+
var suffix = '/**';
45+
46+
if (extensions.length === 1) {
47+
suffix += '/*.' + extensions[0];
48+
} else {
49+
suffix += '/*.{' + extensions.join(',') + '}';
50+
}
51+
52+
/**
53+
* A function that converts a directory name to a glob pattern
54+
*
55+
* @param {string} pathname The directory path to be modified
56+
* @returns {string} The glob path or the file path itself
57+
* @private
58+
*/
59+
return function (pathname) {
60+
var newPath = pathname;
61+
var resolvedPath = path.resolve(cwd, pathname);
62+
63+
if (shell.test('-d', resolvedPath)) {
64+
newPath = pathname.replace(/[/\\]$/, '') + suffix;
65+
}
66+
67+
return convertPathToPosix(newPath);
68+
};
69+
}
70+
71+
/**
72+
* Resolves any directory patterns into glob-based patterns for easier handling.
73+
* @param {string[]} patterns File patterns (such as passed on the command line).
74+
* @param {Object} options An options object.
75+
* @returns {string[]} The equivalent glob patterns and filepath strings.
76+
*/
77+
function resolveFileGlobPatterns(patterns, options) {
78+
var processPathExtensions = processPath(options);
79+
return patterns.map(processPathExtensions);
80+
}
81+
82+
/**
83+
* Build a list of absolute filesnames on which ESLint will act.
84+
* Ignored files are excluded from the results, as are duplicates.
85+
*
86+
* @param {string[]} globPatterns Glob patterns.
87+
* @returns {string[]} Resolved absolute filenames.
88+
*/
89+
function listFilesToProcess(globPatterns) {
90+
var files = [],
91+
added = Object.create(null);
92+
93+
var cwd = process.cwd();
94+
95+
/**
96+
* Executes the linter on a file defined by the `filename`. Skips
97+
* unsupported file extensions and any files that are already linted.
98+
* @param {string} filename The file to be processed
99+
* @returns {void}
100+
*/
101+
function addFile(filename) {
102+
if (added[filename]) {
103+
return;
104+
}
105+
files.push(filename);
106+
added[filename] = true;
107+
}
108+
109+
globPatterns.forEach(function (pattern) {
110+
var file = path.resolve(cwd, pattern);
111+
if (shell.test('-f', file)) {
112+
addFile(fs.realpathSync(file), !shell.test('-d', file));
113+
} else {
114+
var globOptions = {
115+
nodir: true,
116+
dot: true,
117+
cwd,
118+
};
119+
120+
glob.sync(pattern, globOptions).forEach(function (globMatch) {
121+
addFile(path.resolve(cwd, globMatch), false);
122+
});
123+
}
124+
});
125+
126+
return files;
127+
}
128+
129+
function smartGlob(indexes, extensions) {
130+
return listFilesToProcess(
131+
resolveFileGlobPatterns(indexes, {
132+
extensions: extensions
133+
})
134+
);
135+
}
136+
137+
module.exports = smartGlob;

package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
"git-url-parse": "^6.0.1",
3131
"github-slugger": "1.1.1",
3232
"globals-docs": "^2.3.0",
33+
"glob": "^7.0.0",
3334
"highlight.js": "^9.1.0",
3435
"js-yaml": "^3.3.1",
3536
"lodash": "^4.11.1",
@@ -43,6 +44,7 @@
4344
"remark-toc": "^3.0.0",
4445
"remote-origin-url": "0.4.0",
4546
"resolve": "^1.1.6",
47+
"shelljs": "^0.7.5",
4648
"standard-changelog": "0.0.1",
4749
"stream-array": "^1.1.0",
4850
"strip-json-comments": "^2.0.0",
@@ -62,7 +64,6 @@
6264
"documentation-schema": "0.0.1",
6365
"eslint": "^3.1.0",
6466
"fs-extra": "^1.0.0",
65-
"glob": "^7.0.0",
6667
"json-schema": "0.2.3",
6768
"mock-fs": "^3.5.0",
6869
"tap": "^8.0.0",

test/bin-readme.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,9 @@ test('readme command', function (group) {
100100
});
101101
});
102102

103-
group.test('errors if specified readme section is missing', function (t) {
104-
documentation(['readme index.js -s DUMMY'], {cwd: d}, function (err, stdout, stderr) {
103+
var badFixturePath = path.join(__dirname, 'fixture/bad/syntax.input.js');
104+
group.test('errors on invalid syntax', function (t) {
105+
documentation(['readme ' + badFixturePath + ' -s API'], {cwd: d}, function (err, stdout, stderr) {
105106
t.ok(err);
106107
t.ok(err.code !== 0, 'exit nonzero');
107108
t.end();

test/lib/input/shallow.js

+9
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,15 @@ test('shallow deps not found', function (t) {
4545
t.end();
4646
});
4747

48+
test('throws on non-string or object input', function (t) {
49+
t.throws(function () {
50+
shallow([
51+
true
52+
], {});
53+
}, 'indexes should be either strings or objects');
54+
t.end();
55+
});
56+
4857
test('shallow deps literal', function (t) {
4958
var obj = {
5059
file: 'foo.js',

0 commit comments

Comments
 (0)