help.js
This file
Path
lib/help.js
457 lines · 13.9 KiB · JavaScript
Last changed by
Refactor help option implementation to hold actual Option (#2006)John Geebefore adoption09244af
History of this fileTake it
Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1–16why, one step back1const { humanReadableArgName } = require('./argument.js');23/**4 * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`5 * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types6 * @typedef { import("./argument.js").Argument } Argument7 * @typedef { import("./command.js").Command } Command8 * @typedef { import("./option.js").Option } Option9 */1011// Although this is a class, methods are static in style to allow override using subclass or just functions.12class Help {13 constructor() {14 this.helpWidth = undefined;15 this.sortSubcommands = false;16 this.sortOptions = false;Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
line 17why, one step back17 this.showGlobalOptions = false;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 18–28why, one step back18 }1920 /**21 * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.22 *23 * @param {Command} cmd24 * @returns {Command[]}25 */2627 visibleCommands(cmd) {28 const visibleCommands = cmd.commands.filter(cmd => !cmd._hidden);Refactor help command implementation to hold actual Command (#2087)John Geebefore adoptionff08a02
lines 29–30why, one step back29 const helpCommand = cmd._getHelpCommand();30 if (helpCommand && !helpCommand._hidden) {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 31–34why, one step back31 visibleCommands.push(helpCommand);32 }33 if (this.sortSubcommands) {34 visibleCommands.sort((a, b) => {Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 35why, one step back35 // @ts-ignore: overloaded return typeRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 36–42why, one step back36 return a.name().localeCompare(b.name());37 });38 }39 return visibleCommands;40 }4142 /**Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 43–57why, one step back43 * Compare options for sort.44 *45 * @param {Option} a46 * @param {Option} b47 * @returns number48 */49 compareOptions(a, b) {50 const getSortKey = (option) => {51 // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.52 return option.short ? option.short.replace(/^-/, '') : option.long.replace(/^--/, '');53 };54 return getSortKey(a).localeCompare(getSortKey(b));55 }5657 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 58–65why, one step back58 * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.59 *60 * @param {Command} cmd61 * @returns {Option[]}62 */6364 visibleOptions(cmd) {65 const visibleOptions = cmd.options.filter((option) => !option.hidden);Refactor help option implementation to hold actual Option (#2006)John Geebefore adoption09244af
lines 66–77why, one step back66 // Built-in help option.67 const helpOption = cmd._getHelpOption();68 if (helpOption && !helpOption.hidden) {69 // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.70 const removeShort = helpOption.short && cmd._findOption(helpOption.short);71 const removeLong = helpOption.long && cmd._findOption(helpOption.long);72 if (!removeShort && !removeLong) {73 visibleOptions.push(helpOption); // no changes needed74 } else if (helpOption.long && !removeLong) {75 visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));76 } else if (helpOption.short && !removeShort) {77 visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 78–80why, one step back78 }79 }80 if (this.sortOptions) {Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
line 81why, one step back81 visibleOptions.sort(this.compareOptions);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 82–86why, one step back82 }83 return visibleOptions;84 }8586 /**Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 87–96why, one step back87 * Get an array of the visible global options. (Not including help.)88 *89 * @param {Command} cmd90 * @returns {Option[]}91 */9293 visibleGlobalOptions(cmd) {94 if (!this.showGlobalOptions) return [];9596 const globalOptions = [];Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
lines 97–98why, one step back97 for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {98 const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 99–107why, one step back99 globalOptions.push(...visibleOptions);100 }101 if (this.sortOptions) {102 globalOptions.sort(this.compareOptions);103 }104 return globalOptions;105 }106107 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 108–116why, one step back108 * Get an array of the arguments if any have a description.109 *110 * @param {Command} cmd111 * @returns {Argument[]}112 */113114 visibleArguments(cmd) {115 // Side effect! Apply the legacy descriptions before the arguments are displayed.116 if (cmd._argsDescription) {Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
line 117why, one step back117 cmd.registeredArguments.forEach(argument => {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 118–122why, one step back118 argument.description = argument.description || cmd._argsDescription[argument.name()] || '';119 });120 }121122 // If there are any arguments with a description then return all the arguments.Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
lines 123–124why, one step back123 if (cmd.registeredArguments.find(argument => argument.description)) {124 return cmd.registeredArguments;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 125why, one step back125 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 126–137why, one step back126 return [];127 }128129 /**130 * Get the command term to show in the list of subcommands.131 *132 * @param {Command} cmd133 * @returns {string}134 */135136 subcommandTerm(cmd) {137 // Legacy. Ignores custom usage string, and nested commands.Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
line 138why, one step back138 const args = cmd.registeredArguments.map(arg => humanReadableArgName(arg)).join(' ');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 139–178why, one step back139 return cmd._name +140 (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +141 (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option142 (args ? ' ' + args : '');143 }144145 /**146 * Get the option term to show in the list of options.147 *148 * @param {Option} option149 * @returns {string}150 */151152 optionTerm(option) {153 return option.flags;154 }155156 /**157 * Get the argument term to show in the list of arguments.158 *159 * @param {Argument} argument160 * @returns {string}161 */162163 argumentTerm(argument) {164 return argument.name();165 }166167 /**168 * Get the longest command term length.169 *170 * @param {Command} cmd171 * @param {Help} helper172 * @returns {number}173 */174175 longestSubcommandTermLength(cmd, helper) {176 return helper.visibleCommands(cmd).reduce((max, command) => {177 return Math.max(max, helper.subcommandTerm(command).length);178 }, 0);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 179why, one step back179 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 180–192why, one step back180181 /**182 * Get the longest option term length.183 *184 * @param {Command} cmd185 * @param {Help} helper186 * @returns {number}187 */188189 longestOptionTermLength(cmd, helper) {190 return helper.visibleOptions(cmd).reduce((max, option) => {191 return Math.max(max, helper.optionTerm(option).length);192 }, 0);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 193why, one step back193 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 194–195why, one step back194195 /**Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 196–209why, one step back196 * Get the longest global option term length.197 *198 * @param {Command} cmd199 * @param {Help} helper200 * @returns {number}201 */202203 longestGlobalOptionTermLength(cmd, helper) {204 return helper.visibleGlobalOptions(cmd).reduce((max, option) => {205 return Math.max(max, helper.optionTerm(option).length);206 }, 0);207 }208209 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 210–220why, one step back210 * Get the longest argument term length.211 *212 * @param {Command} cmd213 * @param {Help} helper214 * @returns {number}215 */216217 longestArgumentTermLength(cmd, helper) {218 return helper.visibleArguments(cmd).reduce((max, argument) => {219 return Math.max(max, helper.argumentTerm(argument).length);220 }, 0);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 221why, one step back221 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 222–235why, one step back222223 /**224 * Get the command usage to be displayed at the top of the built-in help.225 *226 * @param {Command} cmd227 * @returns {string}228 */229230 commandUsage(cmd) {231 // Usage232 let cmdName = cmd._name;233 if (cmd._aliases[0]) {234 cmdName = cmdName + '|' + cmd._aliases[0];235 }Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
lines 236–238why, one step back236 let ancestorCmdNames = '';237 for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {238 ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 239why, one step back239 }Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 240why, one step back240 return ancestorCmdNames + cmdName + ' ' + cmd.usage();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 241–255why, one step back241 }242243 /**244 * Get the description for the command.245 *246 * @param {Command} cmd247 * @returns {string}248 */249250 commandDescription(cmd) {251 // @ts-ignore: overloaded return type252 return cmd.description();253 }254255 /**Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
line 256why, one step back256 * Get the subcommand summary to show in the list of subcommands.Merge remote-tracking branch 'origin/develop' into release/10.xJohn Geebefore adoptione0f6173
line 257why, one step back257 * (Fallback to description for backwards compatibility.)Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 258–264why, one step back258 *259 * @param {Command} cmd260 * @returns {string}261 */262263 subcommandDescription(cmd) {264 // @ts-ignore: overloaded return typeAdd optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
line 265why, one step back265 return cmd.summary() || cmd.description();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 266–276why, one step back266 }267268 /**269 * Get the option description to show in the list of options.270 *271 * @param {Option} option272 * @return {string}273 */274275 optionDescription(option) {276 const extraInfo = [];Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
line 277why, one step back277Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 278why, one step back278 if (option.argChoices) {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 279–282why, one step back279 extraInfo.push(280 // use stringify to match the display of the default value281 `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);282 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 283–290why, one step back283 if (option.defaultValue !== undefined) {284 // default for boolean and negated more for programmer than end user,285 // but show true/false for boolean option as may be for hand-rolled env or config processing.286 const showDefault = option.required || option.optional ||287 (option.isBoolean() && typeof option.defaultValue === 'boolean');288 if (showDefault) {289 extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);290 }Refactor classes into files (#1522)John Geebefore adoption08245cc
line 291why, one step back291 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 292–295why, one step back292 // preset for boolean and negated are more for programmer than end user293 if (option.presetArg !== undefined && option.optional) {294 extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);295 }Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 296–298why, one step back296 if (option.envVar !== undefined) {297 extraInfo.push(`env: ${option.envVar}`);298 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 299–301why, one step back299 if (extraInfo.length > 0) {300 return `${option.description} (${extraInfo.join(', ')})`;301 }Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
line 302why, one step back302Refactor classes into files (#1522)John Geebefore adoption08245cc
line 303why, one step back303 return option.description;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 304why, one step back304 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 305–314why, one step back305306 /**307 * Get the argument description to show in the list of arguments.308 *309 * @param {Argument} argument310 * @return {string}311 */312313 argumentDescription(argument) {314 const extraInfo = [];Choices for arguments (#1525)John Geebefore adoption708527e
lines 315–319why, one step back315 if (argument.argChoices) {316 extraInfo.push(317 // use stringify to match the display of the default value318 `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);319 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 320–323why, one step back320 if (argument.defaultValue !== undefined) {321 extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);322 }323 if (extraInfo.length > 0) {Choices for arguments (#1525)John Geebefore adoption708527e
lines 324–328why, one step back324 const extraDescripton = `(${extraInfo.join(', ')})`;325 if (argument.description) {326 return `${argument.description} ${extraDescripton}`;327 }328 return extraDescripton;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 329–351why, one step back329 }330 return argument.description;331 }332333 /**334 * Generate the built-in help text.335 *336 * @param {Command} cmd337 * @param {Help} helper338 * @returns {string}339 */340341 formatHelp(cmd, helper) {342 const termWidth = helper.padWidth(cmd, helper);343 const helpWidth = helper.helpWidth || 80;344 const itemIndentWidth = 2;345 const itemSeparatorWidth = 2; // between term and description346 function formatItem(term, description) {347 if (description) {348 const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;349 return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);350 }351 return term;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 352why, one step back352 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 353–362why, one step back353 function formatList(textArray) {354 return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth));355 }356357 // Usage358 let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];359360 // Description361 const commandDescription = helper.commandDescription(cmd);362 if (commandDescription.length > 0) {Wrap command description in help (#1804)John Geebefore adoption186f0c8
line 363why, one step back363 output = output.concat([helper.wrap(commandDescription, helpWidth, 0), '']);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 364–381why, one step back364 }365366 // Arguments367 const argumentList = helper.visibleArguments(cmd).map((argument) => {368 return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));369 });370 if (argumentList.length > 0) {371 output = output.concat(['Arguments:', formatList(argumentList), '']);372 }373374 // Options375 const optionList = helper.visibleOptions(cmd).map((option) => {376 return formatItem(helper.optionTerm(option), helper.optionDescription(option));377 });378 if (optionList.length > 0) {379 output = output.concat(['Options:', formatList(optionList), '']);380 }381Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 382–390why, one step back382 if (this.showGlobalOptions) {383 const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {384 return formatItem(helper.optionTerm(option), helper.optionDescription(option));385 });386 if (globalOptionList.length > 0) {387 output = output.concat(['Global Options:', formatList(globalOptionList), '']);388 }389 }390Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 391–412why, one step back391 // Commands392 const commandList = helper.visibleCommands(cmd).map((cmd) => {393 return formatItem(helper.subcommandTerm(cmd), helper.subcommandDescription(cmd));394 });395 if (commandList.length > 0) {396 output = output.concat(['Commands:', formatList(commandList), '']);397 }398399 return output.join('\n');400 }401402 /**403 * Calculate the pad width from the maximum term length.404 *405 * @param {Command} cmd406 * @param {Help} helper407 * @returns {number}408 */409410 padWidth(cmd, helper) {411 return Math.max(412 helper.longestOptionTermLength(cmd, helper),Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
line 413why, one step back413 helper.longestGlobalOptionTermLength(cmd, helper),Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 414–416why, one step back414 helper.longestSubcommandTermLength(cmd, helper),415 helper.longestArgumentTermLength(cmd, helper)416 );Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 417why, one step back417 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 418–431why, one step back418419 /**420 * Wrap the given string to width characters per line, with lines after the first indented.421 * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.422 *423 * @param {string} str424 * @param {number} width425 * @param {number} indent426 * @param {number} [minColumnWidth=40]427 * @return {string}428 *429 */430431 wrap(str, width, indent, minColumnWidth = 40) {Wrap command description in help (#1804)John Geebefore adoption186f0c8
lines 432–436why, one step back432 // Full \s characters, minus the linefeeds.433 const indents = ' \\f\\t\\v\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff';434 // Detect manually wrapped and indented strings by searching for line break followed by spaces.435 const manualIndent = new RegExp(`[\\n][${indents}]+`);436 if (str.match(manualIndent)) return str;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 437–440why, one step back437 // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).438 const columnWidth = width - indent;439 if (columnWidth < minColumnWidth) return str;440refactor: replace deprecated String.prototype.substr()Tobias Speicherbefore adoption961c45e
line 441why, one step back441 const leadingStr = str.slice(0, indent);Wrap command description in help (#1804)John Geebefore adoption186f0c8
line 442why, one step back442 const columnText = str.slice(indent).replace('\r\n', '\n');Refactor classes into files (#1522)John Geebefore adoption08245cc
line 443why, one step back443 const indentString = ' '.repeat(indent);Wrap command description in help (#1804)John Geebefore adoption186f0c8
lines 444–448why, one step back444 const zeroWidthSpace = '\u200B';445 const breaks = `\\s${zeroWidthSpace}`;446 // Match line end (so empty lines don't collapse),447 // or as much text as will fit in column, or excess text up to first break.448 const regex = new RegExp(`\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, 'g');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 449–450why, one step back449 const lines = columnText.match(regex) || [];450 return leadingStr + lines.map((line, i) => {Wrap command description in help (#1804)John Geebefore adoption186f0c8
lines 451–452why, one step back451 if (line === '\n') return ''; // preserve empty lines452 return ((i > 0) ? indentString : '') + line.trimEnd();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 453–457why, one step back453 }).join('\n');454 }455}456457exports.Help = Help;