diff --git a/LICENSE b/LICENSE index 0604a1314..e9b9b142d 100644 --- a/LICENSE +++ b/LICENSE @@ -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. diff --git a/docs/POLYGLOT.md b/docs/POLYGLOT.md new file mode 100644 index 000000000..c2c9373ce --- /dev/null +++ b/docs/POLYGLOT.md @@ -0,0 +1,39 @@ +# About documentation.js, polyglot mode, and file extensions + +Base assumptions: + +* documentation.js subsists on a combination of _source comments_ and + _smart inferences from source code_. +* The default mode of documentation.js is parsing JavaScript, but it has another + mode, called `--polyglot` mode, that doesn't include any inference at all + and lets you document other kinds of source code. +* The default settings for everything should work for most projects, but + this is a guide for if you have a particular setup. + +## File extensions + +Let's talk about file extensions. We have two different flags for controlling +file extensions: `requireExtension` and `parseExtension`. + +* requireExtension adds additional filetypes to the node.js `require()` method. + By default, you can call, for instance, `require('foo')`, and the require algorithm + will look for `foo.js`, `foo` the module, and `foo.json`. Adding another + extension in requireExtension lets it look for `foo.otherextension`. +* parseExtension adds additional filetypes to the list of filetypes documentation.js + thinks it can parse, and it also adds those additional filetypes to the default + files it looks for when you specify a directory or glob as input. + +## Polyglot + +Polyglot mode switches documentation.js from running on babylon and [babel](https://babeljs.io/) +as a JavaScript parser, to using [get-comments](https://github.com/tunnckocore/get-comments). +This lets it grab comments formatted in the `/** Comment */` style from source +code that _isn't_ JavaScript, like C++ or CSS code. + +Since documentation.js doesn't _parse_ C++ and lots of other languages (parsing JavaScript is complicated enough!), +it can't make any of its smart inferences about their source code: it just +takes documentation comments and shows them as-is. + +You _can_ use polyglot mode to turn off inference across the board, but I don't recommend +it. See the 'too much inference' topic in [TROUBLESHOOTING.md](TROUBLESHOOTING.md) +for detail about that. diff --git a/index.js b/index.js index c962c0824..f79a7e30c 100644 --- a/index.js +++ b/index.js @@ -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'), @@ -27,6 +26,8 @@ var fs = require('fs'), markdownAST = require('./lib/output/markdown_ast'), loadConfig = require('./lib/load_config'); +var parseExtensions = ['js', 'jsx', 'es5', 'es6']; + /** * Build a pipeline of comment handlers. * @param {...Function|null} args - Pipeline elements. Each is a function that accepts @@ -62,6 +63,8 @@ function expandInputs(indexes, options, callback) { } else { inputFn = dependency; } + options.parseExtensions = parseExtensions + .concat(options.parseExtension || []); inputFn(indexes, options, callback); } @@ -214,8 +217,6 @@ function buildSync(indexes, options) { options.github && github, garbageCollect); - var jsFilterer = filterJS(options.extension, options.polyglot); - return filterAccess(options.access, hierarchy( sort( @@ -231,10 +232,6 @@ function buildSync(indexes, options) { indexObject = index; } - if (!jsFilterer(indexObject)) { - return []; - } - return parseFn(indexObject, options).map(buildPipeline); }) .filter(Boolean), options))); @@ -309,7 +306,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)); }, []) diff --git a/lib/commands/shared_options.js b/lib/commands/shared_options.js index 5550eb417..192757f27 100644 --- a/lib/commands/shared_options.js +++ b/lib/commands/shared_options.js @@ -24,10 +24,22 @@ module.exports.sharedInputOptions = { 'modules will be whitelisted and included in the generated documentation.', default: null }, - 'extension': { - describe: 'only input source files matching this extension will be parsed, ' + - 'this option can be used multiple times.', - alias: 'e' + 'requireExtension': { + describe: 'additional extensions to include in require() and import\'s search algorithm.' + + 'For instance, adding .es5 would allow require("adder") to find "adder.es5"', + coerce: function (value) { + // Ensure that the value is an array + return [].concat(value); + }, + alias: 're' + }, + 'parseExtension': { + describe: 'additional extensions to parse as source code.', + coerce: function (value) { + // Ensure that the value is an array + return [].concat(value); + }, + alias: 'pe' }, 'polyglot': { type: 'boolean', diff --git a/lib/filter_js.js b/lib/filter_js.js deleted file mode 100644 index f824d0f61..000000000 --- a/lib/filter_js.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -var path = require('path'); - -/** - * Node & browserify support requiring JSON files. JSON files can't be documented - * with JSDoc or parsed with espree, so we filter them out before - * they reach documentation's machinery. - * This creates a filter function for use with Array.prototype.filter, which - * expect as argument a file as an objectg with the 'file' property - * - * @private - * @param {string|Array} extension to be filtered - * @param {boolean} allowAll ignore the entire extension check and always - * pass through files. This is used by the polglot mode. - * @return {Function} a filter function, this function returns true if the input filename extension - * is in the extension whitelist - */ -function filterJS(extension, allowAll) { - - if (allowAll) { - return function () { - return true; - }; - } - - var extensions = [].concat(extension || []).concat(['js', 'es6', 'jsx']); - - return function (data) { - return extensions.indexOf(path.extname(data.file).substring(1)) !== -1; - }; -} - -module.exports = filterJS; diff --git a/lib/input/dependency.js b/lib/input/dependency.js index 57f932534..e7b81433e 100644 --- a/lib/input/dependency.js +++ b/lib/input/dependency.js @@ -1,13 +1,12 @@ '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 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 @@ -22,8 +21,6 @@ var mdeps = require('module-deps-sortable'), * @returns {undefined} calls callback */ function dependencyStream(indexes, options, callback) { - var filterer = filterJS(options.extension, options.polyglot); - var md = mdeps({ /** * Determine whether a module should be included in documentation @@ -33,11 +30,11 @@ function dependencyStream(indexes, options, callback) { filter: function (id) { return !!options.external || moduleFilters.internalOnly(id); }, - extensions: [].concat(options.extension || []) - .concat(['js', 'es6', 'jsx', 'json']) + extensions: [].concat(options.requireExtension || []) .map(function (ext) { - return '.' + ext; - }), + return '.' + ext.replace(/^\./, ''); + }) + .concat(['.js', '.json', '.es6', '.jsx']), transform: [babelify.configure({ sourceMap: false, compact: false, @@ -55,7 +52,7 @@ function dependencyStream(indexes, options, callback) { })], postFilter: moduleFilters.externals(indexes, options) }); - expandDirectories(indexes, filterer).forEach(function (index) { + smartGlob(indexes, options.parseExtensions).forEach(function (index) { md.write(path.resolve(index)); }); md.end(); @@ -63,11 +60,22 @@ function dependencyStream(indexes, options, callback) { 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(function (input) { + // At this point, we may have allowed a JSON file to be caught by + // module-deps, or anything else allowed by requireExtension. + // otherwise module-deps would complain about + // it not being found. But Babel can't parse JSON, so we filter non-JavaScript + // files away. + return options.parseExtensions.indexOf( + path.extname(input.file).replace(/^\./, '') + ) > -1; + }) + .map(function (input) { + // un-transform babelify transformed source + input.source = fs.readFileSync(input.file, 'utf8'); + return input; + })); })); } diff --git a/lib/input/expand_directories.js b/lib/input/expand_directories.js deleted file mode 100644 index 5b366ec6d..000000000 --- a/lib/input/expand_directories.js +++ /dev/null @@ -1,40 +0,0 @@ -var fs = require('fs'); -var path = require('path'); -var _ = require('lodash'); - -/** - * Given a list of indexes, expand those indexes that are paths - * to directories into sub-lists of files. This does _not_ work - * recursively and will throw an error if an index is not found - * - * @private - * @throws {Error} if index is not found - * @param {Array} indexes entry points given to documentatino - * @param {Function} filterer method that avoids evaluating non-JavaScript files - * @returns {Array} flattened array of file sources - */ -function expandDirectories(indexes, filterer) { - return _.flatMap(indexes, function (index) { - if (typeof index !== 'string') { - return index; - } - try { - var stat = fs.statSync(index); - if (stat.isFile()) { - return index; - } else if (stat.isDirectory()) { - return fs.readdirSync(index) - .filter(function (file) { - return filterer({ file: file }); - }) - .map(function (file) { - return path.join(index, file); - }); - } - } catch (e) { - throw new Error('Input file ' + index + ' not found!'); - } - }); -} - -module.exports = expandDirectories; diff --git a/lib/input/shallow.js b/lib/input/shallow.js index 532ef2d91..ec52d2239 100644 --- a/lib/input/shallow.js +++ b/lib/input/shallow.js @@ -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 @@ -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.parseExtensions))); }; diff --git a/lib/smart_glob.js b/lib/smart_glob.js new file mode 100644 index 000000000..72f81277f --- /dev/null +++ b/lib/smart_glob.js @@ -0,0 +1,133 @@ +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 {string[]} [extensions=['.js']] An array of accepted extensions + * @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(extensions) { + var cwd = process.cwd(); + extensions = 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 {Array} extensions A list of file extensions + * @returns {string[]} The equivalent glob patterns and filepath strings. + */ +function resolveFileGlobPatterns(patterns, extensions) { + var processPathExtensions = processPath(extensions); + 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) + ); +} + +module.exports = smartGlob; diff --git a/package.json b/package.json index 9018e802c..ff4de303f 100644 --- a/package.json +++ b/package.json @@ -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", @@ -43,6 +44,7 @@ "remark-toc": "^3.0.0", "remote-origin-url": "0.4.0", "resolve": "^1.1.6", + "shelljs": "^0.7.5", "stream-array": "^1.1.0", "strip-json-comments": "^2.0.0", "tiny-lr": "^1.0.3", @@ -60,9 +62,8 @@ "standard-changelog": "0.0.1", "cz-conventional-changelog": "1.2.0", "documentation-schema": "0.0.1", - "eslint": "^3.1.0", + "eslint": "^3.12.2", "fs-extra": "^1.0.0", - "glob": "^7.0.0", "json-schema": "0.2.3", "mock-fs": "^3.5.0", "tap": "^8.0.0", diff --git a/test/bin-readme.js b/test/bin-readme.js index 2337ac8c7..e930df13c 100644 --- a/test/bin-readme.js +++ b/test/bin-readme.js @@ -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(); diff --git a/test/bin.js b/test/bin.js index fc10577f9..f2a9aa113 100644 --- a/test/bin.js +++ b/test/bin.js @@ -141,7 +141,20 @@ test('external modules option', function (t) { test('extension option', function (t) { documentation(['build fixture/extension/index.otherextension ' + - '--extension=otherextension'], function (err, data) { + '--requireExtension=otherextension --parseExtension=otherextension'], function (err, data) { + t.ifError(err); + t.equal(data.length, 1, 'includes a file with an arbitrary extension'); + t.end(); + }); +}); + +/* + * This tests that parseExtension adds extensions to smartGlob's + * look through directories. + */ +test('polyglot + parseExtension + smartGlob', function (t) { + documentation(['build fixture/polyglot ' + + '--polyglot --parseExtension=cpp'], function (err, data) { t.ifError(err); t.equal(data.length, 1, 'includes a file with an arbitrary extension'); t.end(); diff --git a/test/fixture/require-json.json b/test/fixture/require-json.json index 0967ef424..2393cd01d 100644 --- a/test/fixture/require-json.json +++ b/test/fixture/require-json.json @@ -1 +1 @@ -{} +{"foo":"bar"} diff --git a/test/lib/input/shallow.js b/test/lib/input/shallow.js index 6eb9fc491..2c0fef558 100644 --- a/test/lib/input/shallow.js +++ b/test/lib/input/shallow.js @@ -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', diff --git a/test/lib/parsers/polyglot.js b/test/lib/parsers/polyglot.js index 028abd122..b9378271e 100644 --- a/test/lib/parsers/polyglot.js +++ b/test/lib/parsers/polyglot.js @@ -27,11 +27,11 @@ test('polyglot', function (t) { description: remark().parse('color'), type: { name: 'number', type: 'NameExpression' } } ], tags: [ { description: null, lineNumber: 2, name: 'hexToUInt32Color', title: 'name' }, - { description: null, lineNumber: 3, name: 'hex', title: 'param', type: { - name: 'string', type: 'NameExpression' - } }, - { description: 'color', lineNumber: 4, title: 'returns', type: { - name: 'number', type: 'NameExpression' - } } ] } ], 'polyglot parser'); + { description: null, lineNumber: 3, name: 'hex', title: 'param', type: { + name: 'string', type: 'NameExpression' + } }, + { description: 'color', lineNumber: 4, title: 'returns', type: { + name: 'number', type: 'NameExpression' + } } ] } ], 'polyglot parser'); t.end(); });