From e07a89b56b65f96295f421141f5b02e360d2e7d0 Mon Sep 17 00:00:00 2001 From: "(quasar) nebula" Date: Wed, 29 May 2024 16:54:43 -0300 Subject: upd8, util, cli: factor out help internals; no default build mode Sorry these changes are packed together in one commit! We have no excuse. :+1: --- src/util/cli.js | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) (limited to 'src/util/cli.js') diff --git a/src/util/cli.js b/src/util/cli.js index ce513f08..72979d3f 100644 --- a/src/util/cli.js +++ b/src/util/cli.js @@ -201,6 +201,79 @@ export async function parseOptions(options, optionDescriptorMap) { return result; } +// Takes precisely the same sort of structure as `parseOptions` above, +// and displays associated help messages. Radical! +// +// 'indentWrap' should be the function from '#sugar', with its wrap option +// already bound. +// +// 'sort' should take care of sorting a list of {name, descriptor} entries. +export function showHelpForOptions({ + heading, + options, + indentWrap, + sort = entries => entries, +}) { + if (heading) { + console.log(colors.bright(heading)); + } + + const sortedOptions = + sort( + Object.entries(options) + .map(([name, descriptor]) => ({name, descriptor}))); + + if (!sortedOptions.length) { + console.log(`(No options available)`) + } + + let justInsertedPaddingLine = false; + + for (const {name, descriptor} of sortedOptions) { + if (descriptor.alias) { + continue; + } + + const aliases = + Object.entries(options) + .filter(([_name, {alias}]) => alias === name) + .map(([name]) => name); + + let wrappedHelp, wrappedHelpLines = 0; + if (descriptor.help) { + wrappedHelp = indentWrap(descriptor.help, {spaces: 4}); + wrappedHelpLines = wrappedHelp.split('\n').length; + } + + if (wrappedHelpLines > 0 && !justInsertedPaddingLine) { + console.log(''); + } + + console.log(colors.bright(` --` + name) + + (aliases.length + ? ` (or: ${aliases.map(alias => colors.bright(`--` + alias)).join(', ')})` + : '') + + (descriptor.help + ? '' + : colors.dim(' (no help provided)'))); + + if (wrappedHelp) { + console.log(wrappedHelp); + } + + if (wrappedHelpLines > 1) { + console.log(''); + justInsertedPaddingLine = true; + } else { + justInsertedPaddingLine = false; + } + } + + if (!justInsertedPaddingLine) { + console.log(``); + } +} + export const handleDashless = Symbol(); export const handleUnknown = Symbol(); -- cgit 1.3.0-6-gf8a5