From 699e748108df5a3c0c2c2b9ffa1436c73d41b1a2 Mon Sep 17 00:00:00 2001 From: Tom MacWright Date: Fri, 11 Aug 2017 13:35:27 -0700 Subject: [PATCH] style: Use await/async instead of Promises --- src/commands/build.js | 48 +++++++++++++------------- src/commands/lint.js | 28 +++++++-------- src/commands/readme.js | 69 +++++++++++++++++------------------- src/commands/serve.js | 71 ++++++++++++++++++-------------------- src/merge_config.js | 43 +++++++++++------------ src/output/markdown.js | 5 +-- src/output/markdown_ast.js | 5 +-- 7 files changed, 128 insertions(+), 141 deletions(-) diff --git a/src/commands/build.js b/src/commands/build.js index 17b89611b..e298cf63a 100644 --- a/src/commands/build.js +++ b/src/commands/build.js @@ -25,7 +25,8 @@ module.exports.builder = _.assign( { example: 'documentation build foo.js -f md > API.md', output: { - describe: 'output location. omit for stdout, otherwise is a filename ' + + describe: + 'output location. omit for stdout, otherwise is a filename ' + 'for single-file outputs and a directory name for multi-file outputs like html', default: 'stdout', alias: 'o' @@ -64,21 +65,23 @@ module.exports.handler = function build(argv: Object) { ); } - function generator() { - return documentation - .build(argv.input, argv) - .then(comments => - documentation.formats[argv.format](comments, argv).then(onFormatted) - ) - .catch(err => { - /* eslint no-console: 0 */ - if (err instanceof Error) { - console.error(err.stack); - } else { - console.error(err); - } - process.exit(1); - }); + async function generator() { + try { + const comments = await documentation.build(argv.input, argv); + const formatted = await documentation.formats[argv.format]( + comments, + argv + ); + onFormatted(formatted); + } catch (err) { + /* eslint no-console: 0 */ + if (err instanceof Error) { + console.error(err.stack); + } else { + console.error(err); + } + process.exit(1); + } } function onFormatted(output) { @@ -100,18 +103,15 @@ module.exports.handler = function build(argv: Object) { } } - function updateWatcher() { + async function updateWatcher() { if (!watcher) { watcher = chokidar.watch(argv.input); watcher.on('all', _.debounce(generator, 300)); } - documentation - .expandInputs(argv.input, argv) - .then(files => - watcher.add( - files.map(data => (typeof data === 'string' ? data : data.file)) - ) - ); + const files = await documentation.expandInputs(argv.input, argv); + watcher.add( + files.map(data => (typeof data === 'string' ? data : data.file)) + ); } return generator(); diff --git a/src/commands/lint.js b/src/commands/lint.js index 3e465cc9c..c3185fe89 100644 --- a/src/commands/lint.js +++ b/src/commands/lint.js @@ -18,7 +18,7 @@ module.exports.builder = {}; * @returns {undefined} has side-effects * @private */ -module.exports.handler = function(argv: Object) { +module.exports.handler = async function(argv: Object) { argv._handled = true; if (!argv.input.length) { try { @@ -32,19 +32,17 @@ module.exports.handler = function(argv: Object) { ); } } - documentation - .lint(argv.input, argv) - .then(lintOutput => { - if (lintOutput) { - console.log(lintOutput); - process.exit(1); - } else { - process.exit(0); - } - }) - .catch(err => { - /* eslint no-console: 0 */ - console.error(err); + try { + const lintOutput = await documentation.lint(argv.input, argv); + if (lintOutput) { + console.log(lintOutput); process.exit(1); - }); + } else { + process.exit(0); + } + } catch (err) { + /* eslint no-console: 0 */ + console.error(err); + process.exit(1); + } }; diff --git a/src/commands/readme.js b/src/commands/readme.js index ada303bb6..4cec3bb03 100644 --- a/src/commands/readme.js +++ b/src/commands/readme.js @@ -51,7 +51,7 @@ module.exports.builder = { * @param {Object} argv args from the CLI option parser * @return {undefined} has the side-effect of writing a file or printing to stdout */ -module.exports.handler = function readme(argv: Object) { +module.exports.handler = async function readme(argv: Object) { argv._handled = true; if (!argv.input.length) { @@ -75,44 +75,39 @@ module.exports.handler = function readme(argv: Object) { } }; - var readmeContent = fs.readFileSync(argv.readmeFile, 'utf8'); - - documentation - .build(argv.input, argv) - .then(comments => documentation.formats.remark(comments, argv)) - .then(docsAst => - remark() - .use(plugin, { - section: argv.section, - toInject: JSON.parse(docsAst) - }) - .process(readmeContent) - ) - .then(file => { - var diffOutput = disparity.unified(readmeContent, file.contents, { - paths: [argv.readmeFile, argv.readmeFile] - }); - if (!diffOutput.length) { - log(`${argv.readmeFile} is up to date.`); - process.exit(0); - } - - if (argv.d) { - log( - chalk.bold(`${argv.readmeFile} needs the following updates:`), - `\n${diffOutput}` - ); - process.exit(1); - } else { - log(chalk.bold(`Updating ${argv.readmeFile}`), `\n${diffOutput}`); - } + try { + var readmeContent = fs.readFileSync(argv.readmeFile, 'utf8'); + const comments = await documentation.build(argv.input, argv); + const docsAst = await documentation.formats.remark(comments, argv); + const file = await remark() + .use(plugin, { + section: argv.section, + toInject: JSON.parse(docsAst) + }) + .process(readmeContent); + var diffOutput = disparity.unified(readmeContent, file.contents, { + paths: [argv.readmeFile, argv.readmeFile] + }); + if (!diffOutput.length) { + log(`${argv.readmeFile} is up to date.`); + process.exit(0); + } - fs.writeFileSync(argv.readmeFile, file.contents); - }) - .catch(err => { - console.error(err); + if (argv.d) { + log( + chalk.bold(`${argv.readmeFile} needs the following updates:`), + `\n${diffOutput}` + ); process.exit(1); - }); + } else { + log(chalk.bold(`Updating ${argv.readmeFile}`), `\n${diffOutput}`); + } + + fs.writeFileSync(argv.readmeFile, file.contents); + } catch (err) { + console.error(err); + process.exit(1); + } }; // wrap the inject utility as an remark plugin diff --git a/src/commands/serve.js b/src/commands/serve.js index b83c8488f..6323e1323 100644 --- a/src/commands/serve.js +++ b/src/commands/serve.js @@ -38,7 +38,7 @@ module.exports.builder = _.assign( * @param {Object} argv cli input * @returns {undefined} has side effects */ -module.exports.handler = function serve(argv: Object) { +module.exports.handler = async function serve(argv: Object) { argv._handled = true; if (!argv.input.length) { @@ -54,48 +54,43 @@ module.exports.handler = function serve(argv: Object) { } } - getPort(argv.port).then(port => { - var server = new Server(port); - var watcher; + const port = await getPort(argv.port); + var server = new Server(port); + var watcher; - server.on('listening', function() { - process.stdout.write(`documentation.js serving on port ${port}\n`); - }); + server.on('listening', function() { + process.stdout.write(`documentation.js serving on port ${port}\n`); + }); - function updateWatcher() { - if (!watcher) { - watcher = chokidar.watch(argv.input); - watcher.on('all', _.debounce(updateServer, 300)); - } + async function updateWatcher() { + if (!watcher) { + watcher = chokidar.watch(argv.input); + watcher.on('all', _.debounce(updateServer, 300)); + } - documentation - .expandInputs(argv.input, argv) - .then(files => { - watcher.add( - files.map(data => (typeof data === 'string' ? data : data.file)) - ); - }) - .catch(err => { - /* eslint no-console: 0 */ - return server.setFiles([errorPage(err)]).start(); - }); + try { + const files = await documentation.expandInputs(argv.input, argv); + watcher.add( + files.map(data => (typeof data === 'string' ? data : data.file)) + ); + } catch (err) { + /* eslint no-console: 0 */ + return server.setFiles([errorPage(err)]).start(); } + } - function updateServer() { - documentation - .build(argv.input, argv) - .then(comments => documentation.formats.html(comments, argv)) - .then(files => { - if (argv.watch) { - updateWatcher(); - } - server.setFiles(files).start(); - }) - .catch(err => { - return server.setFiles([errorPage(err)]).start(); - }); + async function updateServer() { + try { + const comments = await documentation.build(argv.input, argv); + const files = await documentation.formats.html(comments, argv); + if (argv.watch) { + updateWatcher(); + } + server.setFiles(files).start(); + } catch (err) { + return server.setFiles([errorPage(err)]).start(); } + } - updateServer(); - }); + updateServer(); }; diff --git a/src/merge_config.js b/src/merge_config.js index 65dcf733d..55ce60c58 100644 --- a/src/merge_config.js +++ b/src/merge_config.js @@ -31,21 +31,19 @@ function processToc(config: DocumentationConfig, absFilePath: string) { * @returns {Promise} configuration with inferred parameters * @throws {Error} if the file cannot be read. */ -function mergePackage(config: Object): Promise { +async function mergePackage(config: Object): Promise { if (config.noPackage) { return Promise.resolve(config); } - return ( - readPkgUp() - .then(pkg => { - ['name', 'homepage', 'version'].forEach(key => { - config[`project-${key}`] = config[`project-${key}`] || pkg.pkg[key]; - }); - return config; - }) - // Allow this to fail: this inference is not required. - .catch(() => config) - ); + try { + const pkg = await readPkgUp(); + ['name', 'homepage', 'version'].forEach(key => { + config[`project-${key}`] = config[`project-${key}`] || pkg.pkg[key]; + }); + } catch (_) { + return config; + } + return config; } /** @@ -56,25 +54,24 @@ function mergePackage(config: Object): Promise { * @returns {Promise} configuration, if it can be parsed * @throws {Error} if the file cannot be read. */ -function mergeConfigFile(config): Promise { +async function mergeConfigFile(config): Promise { if (config && typeof config.config === 'string') { var filePath = config.config; var ext = path.extname(filePath); var absFilePath = path.resolve(process.cwd(), filePath); - return pify(fs).readFile(absFilePath, 'utf8').then(rawFile => { - if (ext === '.json') { - return Object.assign( - {}, - config, - processToc(JSON.parse(stripComments(rawFile)), absFilePath) - ); - } + const rawFile = await pify(fs).readFile(absFilePath, 'utf8'); + if (ext === '.json') { return Object.assign( {}, config, - processToc(yaml.safeLoad(rawFile), absFilePath) + processToc(JSON.parse(stripComments(rawFile)), absFilePath) ); - }); + } + return Object.assign( + {}, + config, + processToc(yaml.safeLoad(rawFile), absFilePath) + ); } return Promise.resolve(config || {}); diff --git a/src/output/markdown.js b/src/output/markdown.js index f496be07f..d8c46c703 100644 --- a/src/output/markdown.js +++ b/src/output/markdown.js @@ -23,11 +23,12 @@ var remark = require('remark'), * fs.writeFileSync('./output.md', output); * }); */ -function markdown( +async function markdown( comments: Array, args: Object = {} ): Promise { - return markdownAST(comments, args).then(ast => remark().stringify(ast)); + const ast = await markdownAST(comments, args); + return remark().stringify(ast); } module.exports = markdown; diff --git a/src/output/markdown_ast.js b/src/output/markdown_ast.js index ab1b1dae7..224fd3e0d 100644 --- a/src/output/markdown_ast.js +++ b/src/output/markdown_ast.js @@ -24,8 +24,9 @@ var DEFAULT_LANGUAGE = 'javascript'; * consult hljs.configure for the full list. * @returns {Promise} returns an eventual Markdown value */ -function markdownAST(comments: Array, args: Object) { - return mergeConfig(args).then(config => buildMarkdownAST(comments, config)); +async function markdownAST(comments: Array, args: Object) { + const config = await mergeConfig(args); + return buildMarkdownAST(comments, config); } function buildMarkdownAST(