Skip to content
Myr

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 file

Take it

1const { 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;17    this.showGlobalOptions = false;18  }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);29    const helpCommand = cmd._getHelpCommand();30    if (helpCommand && !helpCommand._hidden) {31      visibleCommands.push(helpCommand);32    }33    if (this.sortSubcommands) {34      visibleCommands.sort((a, b) => {35        // @ts-ignore: overloaded return type36        return a.name().localeCompare(b.name());37      });38    }39    return visibleCommands;40  }4142  /**43   * 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  /**58   * 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);66    // 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));78      }79    }80    if (this.sortOptions) {81      visibleOptions.sort(this.compareOptions);82    }83    return visibleOptions;84  }8586  /**87   * 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 = [];97    for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {98      const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);99      globalOptions.push(...visibleOptions);100    }101    if (this.sortOptions) {102      globalOptions.sort(this.compareOptions);103    }104    return globalOptions;105  }106107  /**108   * 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) {117      cmd.registeredArguments.forEach(argument => {118        argument.description = argument.description || cmd._argsDescription[argument.name()] || '';119      });120    }121122    // If there are any arguments with a description then return all the arguments.123    if (cmd.registeredArguments.find(argument => argument.description)) {124      return cmd.registeredArguments;125    }126    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.138    const args = cmd.registeredArguments.map(arg => humanReadableArgName(arg)).join(' ');139    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);179  }180181  /**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);193  }194195  /**196   * 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  /**210   * 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);221  }222223  /**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    }236    let ancestorCmdNames = '';237    for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {238      ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;239    }240    return ancestorCmdNames + cmdName + ' ' + cmd.usage();241  }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  /**256   * Get the subcommand summary to show in the list of subcommands.257   * (Fallback to description for backwards compatibility.)258   *259   * @param {Command} cmd260   * @returns {string}261   */262263  subcommandDescription(cmd) {264    // @ts-ignore: overloaded return type265    return cmd.summary() || cmd.description();266  }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 = [];277278    if (option.argChoices) {279      extraInfo.push(280        // use stringify to match the display of the default value281        `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);282    }283    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      }291    }292    // 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    }296    if (option.envVar !== undefined) {297      extraInfo.push(`env: ${option.envVar}`);298    }299    if (extraInfo.length > 0) {300      return `${option.description} (${extraInfo.join(', ')})`;301    }302303    return option.description;304  }305306  /**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 = [];315    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    }320    if (argument.defaultValue !== undefined) {321      extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);322    }323    if (extraInfo.length > 0) {324      const extraDescripton = `(${extraInfo.join(', ')})`;325      if (argument.description) {326        return `${argument.description} ${extraDescripton}`;327      }328      return extraDescripton;329    }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;352    }353    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) {363      output = output.concat([helper.wrap(commandDescription, helpWidth, 0), '']);364    }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    }381382    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    }390391    // 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),413      helper.longestGlobalOptionTermLength(cmd, helper),414      helper.longestSubcommandTermLength(cmd, helper),415      helper.longestArgumentTermLength(cmd, helper)416    );417  }418419  /**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) {432    // 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;437    // 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;440441    const leadingStr = str.slice(0, indent);442    const columnText = str.slice(indent).replace('\r\n', '\n');443    const indentString = ' '.repeat(indent);444    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');449    const lines = columnText.match(regex) || [];450    return leadingStr + lines.map((line, i) => {451      if (line === '\n') return ''; // preserve empty lines452      return ((i > 0) ? indentString : '') + line.trimEnd();453    }).join('\n');454  }455}456457exports.Help = Help;