Skip to content

Commit

Permalink
feat(bin): Support globs on windows and use smarter recursion
Browse files Browse the repository at this point in the history
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
  • Loading branch information
tmcw committed Dec 17, 2016
1 parent a4eddba commit 79f8b90
Show file tree
Hide file tree
Showing 9 changed files with 208 additions and 70 deletions.
25 changes: 25 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,28 @@ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

--------------------------------------------------------------------------------

Contains sections of eslint

ESLint
Copyright JS Foundation and other contributors, https://js.foundation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
8 changes: 0 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ var fs = require('fs'),
sort = require('./lib/sort'),
nest = require('./lib/nest'),
filterAccess = require('./lib/filter_access'),
filterJS = require('./lib/filter_js'),
dependency = require('./lib/input/dependency'),
shallow = require('./lib/input/shallow'),
parseJavaScript = require('./lib/parsers/javascript'),
Expand Down Expand Up @@ -214,8 +213,6 @@ function buildSync(indexes, options) {
options.github && github,
garbageCollect);

var jsFilterer = filterJS(options.extension, options.polyglot);

return filterAccess(options.access,
hierarchy(
sort(
Expand All @@ -231,10 +228,6 @@ function buildSync(indexes, options) {
indexObject = index;
}

if (!jsFilterer(indexObject)) {
return [];
}

return parseFn(indexObject, options).map(buildPipeline);
})
.filter(Boolean), options)));
Expand Down Expand Up @@ -309,7 +302,6 @@ function lint(indexes, options, callback) {
callback(null,
formatLint(hierarchy(
inputs
.filter(filterJS(options.extension, options.polyglot))
.reduce(function (memo, file) {
return memo.concat(parseFn(file, options).map(lintPipeline));
}, [])
Expand Down
34 changes: 19 additions & 15 deletions lib/input/dependency.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
'use strict';

var mdeps = require('module-deps-sortable'),
fs = require('fs'),
path = require('path'),
babelify = require('babelify'),
filterJS = require('../filter_js'),
concat = require('concat-stream'),
moduleFilters = require('../../lib/module_filters'),
expandDirectories = require('./expand_directories');
var mdeps = require('module-deps-sortable');
var fs = require('fs');
var path = require('path');
var babelify = require('babelify');
var filterJS = require('../filter_js');
var concat = require('concat-stream');
var moduleFilters = require('../../lib/module_filters');
var smartGlob = require('../smart_glob.js');

/**
* Returns a readable stream of dependencies, given an array of entry
Expand All @@ -23,7 +23,6 @@ var mdeps = require('module-deps-sortable'),
*/
function dependencyStream(indexes, options, callback) {
var filterer = filterJS(options.extension, options.polyglot);

var md = mdeps({
/**
* Determine whether a module should be included in documentation
Expand All @@ -34,6 +33,9 @@ function dependencyStream(indexes, options, callback) {
return !!options.external || moduleFilters.internalOnly(id);
},
extensions: [].concat(options.extension || [])
// We don't document JSON files, but we do include them in this list,
// because browserify & node both support unnamed requires to .json
// files: `require('foo')` can require `foo.json` automatically.
.concat(['js', 'es6', 'jsx', 'json'])
.map(function (ext) {
return '.' + ext;
Expand All @@ -55,19 +57,21 @@ function dependencyStream(indexes, options, callback) {
})],
postFilter: moduleFilters.externals(indexes, options)
});
expandDirectories(indexes, filterer).forEach(function (index) {
smartGlob(indexes, options.extension).forEach(function (index) {
md.write(path.resolve(index));
});
md.end();
md.once('error', function (error) {
return callback(error);
});
md.pipe(concat(function (inputs) {
callback(null, inputs.map(function (input) {
// un-transform babelify transformed source
input.source = fs.readFileSync(input.file, 'utf8');
return input;
}));
callback(null, inputs
.filter(filterer)
.map(function (input) {
// un-transform babelify transformed source
input.source = fs.readFileSync(input.file, 'utf8');
return input;
}));
}));
}

Expand Down
40 changes: 0 additions & 40 deletions lib/input/expand_directories.js

This file was deleted.

17 changes: 13 additions & 4 deletions lib/input/shallow.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
'use strict';

var filterJS = require('../filter_js');
var expandDirectories = require('./expand_directories');
var smartGlob = require('../smart_glob.js');

/**
* A readable source for content that doesn't do dependency resolution, but
Expand All @@ -21,6 +20,16 @@ var expandDirectories = require('./expand_directories');
* @return {undefined} calls callback
*/
module.exports = function (indexes, options, callback) {
var filterer = filterJS(options.extension, options.polyglot);
return callback(null, expandDirectories(indexes, filterer));
var objects = [];
var strings = [];
indexes.forEach(function (index) {
if (typeof index === 'string') {
strings.push(index);
} else if (typeof index === 'object') {
objects.push(index);
} else {
throw new Error('indexes should be either strings or objects');
}
});
return callback(null, objects.concat(smartGlob(strings, options.extension)));
};
137 changes: 137 additions & 0 deletions lib/smart_glob.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
var fs = require('fs');
var path = require('path');
var glob = require('glob');
var shell = require('shelljs');

/**
* Replace Windows with posix style paths
*
* @param {string} filepath Path to convert
* @returns {string} Converted filepath
*/
function convertPathToPosix(filepath) {
var normalizedFilepath = path.normalize(filepath);
var posixFilepath = normalizedFilepath.replace(/\\/g, '/');

return posixFilepath;
}

/**
* Checks if a provided path is a directory and returns a glob string matching
* all files under that directory if so, the path itself otherwise.
*
* Reason for this is that `glob` needs `/**` to collect all the files under a
* directory where as our previous implementation without `glob` simply walked
* a directory that is passed. So this is to maintain backwards compatibility.
*
* Also makes sure all path separators are POSIX style for `glob` compatibility.
*
* @param {Object} [options] An options object
* @param {string[]} [options.extensions=['.js']] An array of accepted extensions
* @param {string} [options.cwd=process.cwd()] The cwd to use to resolve relative pathnames
* @returns {Function} A function that takes a pathname and returns a glob that
* matches all files with the provided extensions if
* pathname is a directory.
*/
function processPath(options) {
var cwd = (options && options.cwd) || process.cwd();
var extensions = (options && options.extensions) || ['.js'];

extensions = extensions.map(function (ext) {
return ext.replace(/^\./, '');
});

var suffix = '/**';

if (extensions.length === 1) {
suffix += '/*.' + extensions[0];
} else {
suffix += '/*.{' + extensions.join(',') + '}';
}

/**
* A function that converts a directory name to a glob pattern
*
* @param {string} pathname The directory path to be modified
* @returns {string} The glob path or the file path itself
* @private
*/
return function (pathname) {
var newPath = pathname;
var resolvedPath = path.resolve(cwd, pathname);

if (shell.test('-d', resolvedPath)) {
newPath = pathname.replace(/[/\\]$/, '') + suffix;
}

return convertPathToPosix(newPath);
};
}

/**
* Resolves any directory patterns into glob-based patterns for easier handling.
* @param {string[]} patterns File patterns (such as passed on the command line).
* @param {Object} options An options object.
* @returns {string[]} The equivalent glob patterns and filepath strings.
*/
function resolveFileGlobPatterns(patterns, options) {
var processPathExtensions = processPath(options);
return patterns.map(processPathExtensions);
}

/**
* Build a list of absolute filesnames on which ESLint will act.
* Ignored files are excluded from the results, as are duplicates.
*
* @param {string[]} globPatterns Glob patterns.
* @returns {string[]} Resolved absolute filenames.
*/
function listFilesToProcess(globPatterns) {
var files = [],
added = Object.create(null);

var cwd = process.cwd();

/**
* Executes the linter on a file defined by the `filename`. Skips
* unsupported file extensions and any files that are already linted.
* @param {string} filename The file to be processed
* @returns {void}
*/
function addFile(filename) {
if (added[filename]) {
return;
}
files.push(filename);
added[filename] = true;
}

globPatterns.forEach(function (pattern) {
var file = path.resolve(cwd, pattern);
if (shell.test('-f', file)) {
addFile(fs.realpathSync(file), !shell.test('-d', file));
} else {
var globOptions = {
nodir: true,
dot: true,
cwd,
};

glob.sync(pattern, globOptions).forEach(function (globMatch) {
addFile(path.resolve(cwd, globMatch), false);
});
}
});

return files;
}

function smartGlob(indexes, extensions) {
return listFilesToProcess(
resolveFileGlobPatterns(indexes, {
extensions: extensions
})
);
}

module.exports = smartGlob;
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"git-url-parse": "^6.0.1",
"github-slugger": "1.1.1",
"globals-docs": "^2.3.0",
"glob": "^7.0.0",
"highlight.js": "^9.1.0",
"js-yaml": "^3.3.1",
"lodash": "^4.11.1",
Expand All @@ -43,6 +44,7 @@
"remark-toc": "^3.0.0",
"remote-origin-url": "0.4.0",
"resolve": "^1.1.6",
"shelljs": "^0.7.5",
"standard-changelog": "0.0.1",
"stream-array": "^1.1.0",
"strip-json-comments": "^2.0.0",
Expand All @@ -62,7 +64,6 @@
"documentation-schema": "0.0.1",
"eslint": "^3.1.0",
"fs-extra": "^1.0.0",
"glob": "^7.0.0",
"json-schema": "0.2.3",
"mock-fs": "^3.5.0",
"tap": "^8.0.0",
Expand Down
5 changes: 3 additions & 2 deletions test/bin-readme.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,9 @@ test('readme command', function (group) {
});
});

group.test('errors if specified readme section is missing', function (t) {
documentation(['readme index.js -s DUMMY'], {cwd: d}, function (err, stdout, stderr) {
var badFixturePath = path.join(__dirname, 'fixture/bad/syntax.input.js');
group.test('errors on invalid syntax', function (t) {
documentation(['readme ' + badFixturePath + ' -s API'], {cwd: d}, function (err, stdout, stderr) {
t.ok(err);
t.ok(err.code !== 0, 'exit nonzero');
t.end();
Expand Down
9 changes: 9 additions & 0 deletions test/lib/input/shallow.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@ test('shallow deps not found', function (t) {
t.end();
});

test('throws on non-string or object input', function (t) {
t.throws(function () {
shallow([
true
], {});
}, 'indexes should be either strings or objects');
t.end();
});

test('shallow deps literal', function (t) {
var obj = {
file: 'foo.js',
Expand Down

0 comments on commit 79f8b90

Please sign in to comment.