Skip to content
Myr

help.js

This file

Path

lib/help.js

731 lines · 20.3 KiB · JavaScript

Last changed by

Use node:util stripVTControlCharacters instead of own code (#2486)John Geebefore adoption373f660

History of this file

Take it

The walk stopped after 200 commits: lines older than 471ec40 point at it.

Switching to esm-only (#2464)John Geebefore adoptionf4bd470

line 1why, one step back
1import { humanReadableArgName } from './argument.js';

Use node:util stripVTControlCharacters instead of own code (#2486)John Geebefore adoption373f660

line 2why, one step back
2import { stripVTControlCharacters } from 'node:util';

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 3–12why, one step back
3
4/**5 * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`6 * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types7 * @typedef { import("./argument.js").Argument } Argument8 * @typedef { import("./command.js").Command } Command9 * @typedef { import("./option.js").Option } Option10 */1112// Although this is a class, methods are static in style to allow override using subclass or just functions.

Switching to esm-only (#2464)John Geebefore adoptionf4bd470

line 13why, one step back
13export class Help {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 14–15why, one step back
14 constructor() {
15 this.helpWidth = undefined;

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

line 16why, one step back
16 this.minWidthToWrap = 40;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 17–18why, one step back
17 this.sortSubcommands = false;
18 this.sortOptions = false;

Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631

line 19why, one step back
19 this.showGlobalOptions = false;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 20–22why, one step back
20 }
2122 /**

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 23–34why, one step back
23 * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
24 * and just before calling `formatHelp()`.25 *26 * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.27 *28 * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions29 */30 prepareContext(contextOptions) {31 this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;32 }3334 /**

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 35–41why, one step back
35 * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
36 *37 * @param {Command} cmd38 * @returns {Command[]}39 */4041 visibleCommands(cmd) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 42why, one step back
42 const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 43–44why, one step back
43 const helpCommand = cmd._getHelpCommand();
44 if (helpCommand && !helpCommand._hidden) {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 45–48why, one step back
45 visibleCommands.push(helpCommand);
46 }47 if (this.sortSubcommands) {48 visibleCommands.sort((a, b) => {

ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e

line 49why, one step back
49 // @ts-ignore: because overloaded return type

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 50–56why, one step back
50 return a.name().localeCompare(b.name());
51 });52 }53 return visibleCommands;54 }5556 /**

Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631

lines 57–60why, one step back
57 * Compare options for sort.
58 *59 * @param {Option} a60 * @param {Option} b

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 61why, one step back
61 * @returns {number}

Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631

lines 62–65why, one step back
62 */
63 compareOptions(a, b) {64 const getSortKey = (option) => {65 // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 66–68why, one step back
66 return option.short
67 ? option.short.replace(/^-/, '')68 : option.long.replace(/^--/, '');

Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631

lines 69–73why, one step back
69 };
70 return getSortKey(a).localeCompare(getSortKey(b));71 }7273 /**

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 74–81why, one step back
74 * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
75 *76 * @param {Command} cmd77 * @returns {Option[]}78 */7980 visibleOptions(cmd) {81 const visibleOptions = cmd.options.filter((option) => !option.hidden);

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 82–90why, one step back
82 // Built-in help option.
83 const helpOption = cmd._getHelpOption();84 if (helpOption && !helpOption.hidden) {85 // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.86 const removeShort = helpOption.short && cmd._findOption(helpOption.short);87 const removeLong = helpOption.long && cmd._findOption(helpOption.long);88 if (!removeShort && !removeLong) {89 visibleOptions.push(helpOption); // no changes needed90 } else if (helpOption.long && !removeLong) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 91–93why, one step back
91 visibleOptions.push(
92 cmd.createOption(helpOption.long, helpOption.description),93 );

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 94why, one step back
94 } else if (helpOption.short && !removeShort) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 95–97why, one step back
95 visibleOptions.push(
96 cmd.createOption(helpOption.short, helpOption.description),97 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 98–100why, one step back
98 }
99 }100 if (this.sortOptions) {

Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631

line 101why, one step back
101 visibleOptions.sort(this.compareOptions);

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 102–106why, one step back
102 }
103 return visibleOptions;104 }105106 /**

Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631

lines 107–116why, one step back
107 * Get an array of the visible global options. (Not including help.)
108 *109 * @param {Command} cmd110 * @returns {Option[]}111 */112113 visibleGlobalOptions(cmd) {114 if (!this.showGlobalOptions) return [];115116 const globalOptions = [];

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 117–124why, one step back
117 for (
118 let ancestorCmd = cmd.parent;119 ancestorCmd;120 ancestorCmd = ancestorCmd.parent121 ) {122 const visibleOptions = ancestorCmd.options.filter(123 (option) => !option.hidden,124 );

Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631

line 125why, one step back
125 globalOptions.push(...visibleOptions);

Use _getCommandAndAncestors() less aggressivelyWee Bitbefore adoptionf76a734

line 126why, one step back
126 }

Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631

lines 127–133why, one step back
127 if (this.sortOptions) {
128 globalOptions.sort(this.compareOptions);129 }130 return globalOptions;131 }132133 /**

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 134–142why, one step back
134 * Get an array of the arguments if any have a description.
135 *136 * @param {Command} cmd137 * @returns {Argument[]}138 */139140 visibleArguments(cmd) {141 // Side effect! Apply the legacy descriptions before the arguments are displayed.142 if (cmd._argsDescription) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 143–145why, one step back
143 cmd.registeredArguments.forEach((argument) => {
144 argument.description =145 argument.description || cmd._argsDescription[argument.name()] || '';

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 146–149why, one step back
146 });
147 }148149 // If there are any arguments with a description then return all the arguments.

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 150why, one step back
150 if (cmd.registeredArguments.find((argument) => argument.description)) {

Add public Arguments property (#2010)John Geebefore adoption7d23437

line 151why, one step back
151 return cmd.registeredArguments;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 152–164why, one step back
152 }
153 return [];154 }155156 /**157 * Get the command term to show in the list of subcommands.158 *159 * @param {Command} cmd160 * @returns {string}161 */162163 subcommandTerm(cmd) {164 // Legacy. Ignores custom usage string, and nested commands.

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 165–169why, one step back
165 const args = cmd.registeredArguments
166 .map((arg) => humanReadableArgName(arg))167 .join(' ');168 return (169 cmd._name +

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 170–171why, one step back
170 (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +
171 (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 172–173why, one step back
172 (args ? ' ' + args : '')
173 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 174–207why, one step back
174 }
175176 /**177 * Get the option term to show in the list of options.178 *179 * @param {Option} option180 * @returns {string}181 */182183 optionTerm(option) {184 return option.flags;185 }186187 /**188 * Get the argument term to show in the list of arguments.189 *190 * @param {Argument} argument191 * @returns {string}192 */193194 argumentTerm(argument) {195 return argument.name();196 }197198 /**199 * Get the longest command term length.200 *201 * @param {Command} cmd202 * @param {Help} helper203 * @returns {number}204 */205206 longestSubcommandTermLength(cmd, helper) {207 return helper.visibleCommands(cmd).reduce((max, command) => {

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 208–213why, one step back
208 return Math.max(
209 max,210 this.displayWidth(211 helper.styleSubcommandTerm(helper.subcommandTerm(command)),212 ),213 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 214–226why, one step back
214 }, 0);
215 }216217 /**218 * Get the longest option term length.219 *220 * @param {Command} cmd221 * @param {Help} helper222 * @returns {number}223 */224225 longestOptionTermLength(cmd, helper) {226 return helper.visibleOptions(cmd).reduce((max, option) => {

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 227–230why, one step back
227 return Math.max(
228 max,229 this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),230 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 231–234why, one step back
231 }, 0);
232 }233234 /**

Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631

lines 235–243why, one step back
235 * Get the longest global option term length.
236 *237 * @param {Command} cmd238 * @param {Help} helper239 * @returns {number}240 */241242 longestGlobalOptionTermLength(cmd, helper) {243 return helper.visibleGlobalOptions(cmd).reduce((max, option) => {

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 244–247why, one step back
244 return Math.max(
245 max,246 this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),247 );

Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631

lines 248–251why, one step back
248 }, 0);
249 }250251 /**

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 252–260why, one step back
252 * Get the longest argument term length.
253 *254 * @param {Command} cmd255 * @param {Help} helper256 * @returns {number}257 */258259 longestArgumentTermLength(cmd, helper) {260 return helper.visibleArguments(cmd).reduce((max, argument) => {

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 261–266why, one step back
261 return Math.max(
262 max,263 this.displayWidth(264 helper.styleArgumentTerm(helper.argumentTerm(argument)),265 ),266 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 267–282why, one step back
267 }, 0);
268 }269270 /**271 * Get the command usage to be displayed at the top of the built-in help.272 *273 * @param {Command} cmd274 * @returns {string}275 */276277 commandUsage(cmd) {278 // Usage279 let cmdName = cmd._name;280 if (cmd._aliases[0]) {281 cmdName = cmdName + '|' + cmd._aliases[0];282 }

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

line 283why, one step back
283 let ancestorCmdNames = '';

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 284–288why, one step back
284 for (
285 let ancestorCmd = cmd.parent;286 ancestorCmd;287 ancestorCmd = ancestorCmd.parent288 ) {

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

line 289why, one step back
289 ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;

Use _getCommandAndAncestors() less aggressivelyWee Bitbefore adoptionf76a734

line 290why, one step back
290 }

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

line 291why, one step back
291 return ancestorCmdNames + cmdName + ' ' + cmd.usage();

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 292–301why, one step back
292 }
293294 /**295 * Get the description for the command.296 *297 * @param {Command} cmd298 * @returns {string}299 */300301 commandDescription(cmd) {

ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e

line 302why, one step back
302 // @ts-ignore: because overloaded return type

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 303–307why, one step back
303 return cmd.description();
304 }305306 /**307 * Get the subcommand summary to show in the list of subcommands.

Merge remote-tracking branch 'origin/develop' into release/10.xJohn Geebefore adoptione0f6173

line 308why, one step back
308 * (Fallback to description for backwards compatibility.)

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 309–314why, one step back
309 *
310 * @param {Command} cmd311 * @returns {string}312 */313314 subcommandDescription(cmd) {

ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e

line 315why, one step back
315 // @ts-ignore: because overloaded return type

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 316–331why, one step back
316 return cmd.summary() || cmd.description();
317 }318319 /**320 * Get the option description to show in the list of options.321 *322 * @param {Option} option323 * @return {string}324 */325326 optionDescription(option) {327 const extraInfo = [];328329 if (option.argChoices) {330 extraInfo.push(331 // use stringify to match the display of the default value

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 332–333why, one step back
332 `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
333 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 334–337why, one step back
334 }
335 if (option.defaultValue !== undefined) {336 // default for boolean and negated more for programmer than end user,337 // but show true/false for boolean option as may be for hand-rolled env or config processing.

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 338–340why, one step back
338 const showDefault =
339 option.required ||340 option.optional ||

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 341–342why, one step back
341 (option.isBoolean() && typeof option.defaultValue === 'boolean');
342 if (showDefault) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 343–345why, one step back
343 extraInfo.push(
344 `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,345 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 346–355why, one step back
346 }
347 }348 // preset for boolean and negated are more for programmer than end user349 if (option.presetArg !== undefined && option.optional) {350 extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);351 }352 if (option.envVar !== undefined) {353 extraInfo.push(`env: ${option.envVar}`);354 }355 if (extraInfo.length > 0) {

Trim description when there's only extra info (#2348)Misha Kaletskybefore adoption672e380

lines 356–360why, one step back
356 const extraDescription = `(${extraInfo.join(', ')})`;
357 if (option.description) {358 return `${option.description} ${extraDescription}`;359 }360 return extraDescription;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 361–377why, one step back
361 }
362363 return option.description;364 }365366 /**367 * Get the argument description to show in the list of arguments.368 *369 * @param {Argument} argument370 * @return {string}371 */372373 argumentDescription(argument) {374 const extraInfo = [];375 if (argument.argChoices) {376 extraInfo.push(377 // use stringify to match the display of the default value

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 378–379why, one step back
378 `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
379 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 380–381why, one step back
380 }
381 if (argument.defaultValue !== undefined) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 382–384why, one step back
382 extraInfo.push(
383 `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,384 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 385–386why, one step back
385 }
386 if (extraInfo.length > 0) {

Merge branch 'develop' into release/13.xJohn Geebefore adoption5a79585

line 387why, one step back
387 const extraDescription = `(${extraInfo.join(', ')})`;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 388why, one step back
388 if (argument.description) {

Merge branch 'develop' into release/13.xJohn Geebefore adoption5a79585

line 389why, one step back
389 return `${argument.description} ${extraDescription}`;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 390why, one step back
390 }

Merge branch 'develop' into release/13.xJohn Geebefore adoption5a79585

line 391why, one step back
391 return extraDescription;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 392–396why, one step back
392 }
393 return argument.description;394 }395396 /**

Add typings for helpGroup support (#2367)John Geebefore adoptiondd7edf4

lines 397–398why, one step back
397 * Format a list of items, given a heading and an array of formatted items.
398 *

Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3

lines 399–410why, one step back
399 * @param {string} heading
400 * @param {string[]} items401 * @param {Help} helper402 * @returns string[]403 */404 formatItemList(heading, items, helper) {405 if (items.length === 0) return [];406407 return [helper.styleTitle(heading), ...items, ''];408 }409410 /**

Add typings for helpGroup support (#2367)John Geebefore adoptiondd7edf4

line 411why, one step back
411 * Group items by their help group heading.

Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3

lines 412–436why, one step back
412 *
413 * @param {Command[] | Option[]} unsortedItems414 * @param {Command[] | Option[]} visibleItems415 * @param {Function} getGroup416 * @returns {Map<string, Command[] | Option[]>}417 */418 groupItems(unsortedItems, visibleItems, getGroup) {419 const result = new Map();420 // Add groups in order of appearance in unsortedItems.421 unsortedItems.forEach((item) => {422 const group = getGroup(item);423 if (!result.has(group)) result.set(group, []);424 });425 // Add items in order of appearance in visibleItems.426 visibleItems.forEach((item) => {427 const group = getGroup(item);428 if (!result.has(group)) {429 result.set(group, []);430 }431 result.get(group).push(item);432 });433 return result;434 }435436 /**

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 437–445why, one step back
437 * Generate the built-in help text.
438 *439 * @param {Command} cmd440 * @param {Help} helper441 * @returns {string}442 */443444 formatHelp(cmd, helper) {445 const termWidth = helper.padWidth(cmd, helper);

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 446–448why, one step back
446 const helpWidth = helper.helpWidth ?? 80; // in case prepareContext() was not called
447448 function callFormatItem(term, description) {

Split styleItemDescription into option/subcommand/argument (#2283)John Geebefore adoption437e4e3

line 449why, one step back
449 return helper.formatItem(term, termWidth, description, helper);

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 450–452why, one step back
450 }
451452 // Usage

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 453–456why, one step back
453 let output = [
454 `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,455 '',456 ];

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 457–460why, one step back
457
458 // Description459 const commandDescription = helper.commandDescription(cmd);460 if (commandDescription.length > 0) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 461why, one step back
461 output = output.concat([

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 462–465why, one step back
462 helper.boxWrap(
463 helper.styleCommandDescription(commandDescription),464 helpWidth,465 ),

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 466–467why, one step back
466 '',
467 ]);

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 468–471why, one step back
468 }
469470 // Arguments471 const argumentList = helper.visibleArguments(cmd).map((argument) => {

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 472–473why, one step back
472 return callFormatItem(
473 helper.styleArgumentTerm(helper.argumentTerm(argument)),

Split styleItemDescription into option/subcommand/argument (#2283)John Geebefore adoption437e4e3

line 474why, one step back
474 helper.styleArgumentDescription(helper.argumentDescription(argument)),

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 475why, one step back
475 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 476why, one step back
476 });

Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3

lines 477–479why, one step back
477 output = output.concat(
478 this.formatItemList('Arguments:', argumentList, helper),479 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 480–481why, one step back
480
481 // Options

Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3

lines 482–494why, one step back
482 const optionGroups = this.groupItems(
483 cmd.options,484 helper.visibleOptions(cmd),485 (option) => option.helpGroupHeading ?? 'Options:',486 );487 optionGroups.forEach((options, group) => {488 const optionList = options.map((option) => {489 return callFormatItem(490 helper.styleOptionTerm(helper.optionTerm(option)),491 helper.styleOptionDescription(helper.optionDescription(option)),492 );493 });494 output = output.concat(this.formatItemList(group, optionList, helper));

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 495–496why, one step back
495 });
496

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

line 497why, one step back
497 if (helper.showGlobalOptions) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 498–500why, one step back
498 const globalOptionList = helper
499 .visibleGlobalOptions(cmd)500 .map((option) => {

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 501–502why, one step back
501 return callFormatItem(
502 helper.styleOptionTerm(helper.optionTerm(option)),

Split styleItemDescription into option/subcommand/argument (#2283)John Geebefore adoption437e4e3

line 503why, one step back
503 helper.styleOptionDescription(helper.optionDescription(option)),

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 504–505why, one step back
504 );
505 });

Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3

lines 506–508why, one step back
506 output = output.concat(
507 this.formatItemList('Global Options:', globalOptionList, helper),508 );

Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631

lines 509–510why, one step back
509 }
510

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 511why, one step back
511 // Commands

Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3

lines 512–524why, one step back
512 const commandGroups = this.groupItems(
513 cmd.commands,514 helper.visibleCommands(cmd),515 (sub) => sub.helpGroup() || 'Commands:',516 );517 commandGroups.forEach((commands, group) => {518 const commandList = commands.map((sub) => {519 return callFormatItem(520 helper.styleSubcommandTerm(helper.subcommandTerm(sub)),521 helper.styleSubcommandDescription(helper.subcommandDescription(sub)),522 );523 });524 output = output.concat(this.formatItemList(group, commandList, helper));

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 525–530why, one step back
525 });
526527 return output.join('\n');528 }529530 /**

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 531–536why, one step back
531 * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
532 *533 * @param {string} str534 * @returns {number}535 */536 displayWidth(str) {

Use node:util stripVTControlCharacters instead of own code (#2486)John Geebefore adoption373f660

line 537why, one step back
537 return stripVTControlCharacters(str).length;

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 538–563why, one step back
538 }
539540 /**541 * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.542 *543 * @param {string} str544 * @returns {string}545 */546 styleTitle(str) {547 return str;548 }549550 styleUsage(str) {551 // Usage has lots of parts the user might like to color separately! Assume default usage string which is formed like:552 // command subcommand [options] [command] <foo> [bar]553 return str554 .split(' ')555 .map((word) => {556 if (word === '[options]') return this.styleOptionText(word);557 if (word === '[command]') return this.styleSubcommandText(word);558 if (word[0] === '[' || word[0] === '<')559 return this.styleArgumentText(word);560 return this.styleCommandText(word); // Restrict to initial words?561 })562 .join(' ');563 }

Split styleItemDescription into option/subcommand/argument (#2283)John Geebefore adoption437e4e3

line 564why, one step back
564 styleCommandDescription(str) {

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 565–566why, one step back
565 return this.styleDescriptionText(str);
566 }

Split styleItemDescription into option/subcommand/argument (#2283)John Geebefore adoption437e4e3

lines 567–573why, one step back
567 styleOptionDescription(str) {
568 return this.styleDescriptionText(str);569 }570 styleSubcommandDescription(str) {571 return this.styleDescriptionText(str);572 }573 styleArgumentDescription(str) {

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 574–611why, one step back
574 return this.styleDescriptionText(str);
575 }576 styleDescriptionText(str) {577 return str;578 }579 styleOptionTerm(str) {580 return this.styleOptionText(str);581 }582 styleSubcommandTerm(str) {583 // This is very like usage with lots of parts! Assume default string which is formed like:584 // subcommand [options] <foo> [bar]585 return str586 .split(' ')587 .map((word) => {588 if (word === '[options]') return this.styleOptionText(word);589 if (word[0] === '[' || word[0] === '<')590 return this.styleArgumentText(word);591 return this.styleSubcommandText(word); // Restrict to initial words?592 })593 .join(' ');594 }595 styleArgumentTerm(str) {596 return this.styleArgumentText(str);597 }598 styleOptionText(str) {599 return str;600 }601 styleArgumentText(str) {602 return str;603 }604 styleSubcommandText(str) {605 return str;606 }607 styleCommandText(str) {608 return str;609 }610611 /**

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 612–621why, one step back
612 * Calculate the pad width from the maximum term length.
613 *614 * @param {Command} cmd615 * @param {Help} helper616 * @returns {number}617 */618619 padWidth(cmd, helper) {620 return Math.max(621 helper.longestOptionTermLength(cmd, helper),

Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631

line 622why, one step back
622 helper.longestGlobalOptionTermLength(cmd, helper),

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 623why, one step back
623 helper.longestSubcommandTermLength(cmd, helper),

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 624why, one step back
624 helper.longestArgumentTermLength(cmd, helper),

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 625–628why, one step back
625 );
626 }627628 /**

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

line 629why, one step back
629 * Detect manually wrapped and indented strings by checking for line break followed by whitespace.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 630–631why, one step back
630 *
631 * @param {string} str

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 632–639why, one step back
632 * @returns {boolean}
633 */634 preformatted(str) {635 return /\n[^\S\r\n]/.test(str);636 }637638 /**639 * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 640why, one step back
640 *

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 641–649why, one step back
641 * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
642 * TTT DDD DDDD643 * DD DDD644 *645 * @param {string} term646 * @param {number} termWidth647 * @param {string} description648 * @param {Help} helper649 * @returns {string}

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 650why, one step back
650 */

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 651–654why, one step back
651 formatItem(term, termWidth, description, helper) {
652 const itemIndent = 2;653 const itemIndentStr = ' '.repeat(itemIndent);654 if (!description) return itemIndentStr + term;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 655why, one step back
655

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 656–658why, one step back
656 // Pad the term out to a consistent width, so descriptions are aligned.
657 const paddedTerm = term.padEnd(658 termWidth + term.length - helper.displayWidth(term),

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 659why, one step back
659 );

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 660–679why, one step back
660
661 // Format the description.662 const spacerWidth = 2; // between term and description663 const helpWidth = this.helpWidth ?? 80; // in case prepareContext() was not called664 const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;665 let formattedDescription;666 if (667 remainingWidth < this.minWidthToWrap ||668 helper.preformatted(description)669 ) {670 formattedDescription = description;671 } else {672 const wrappedDescription = helper.boxWrap(description, remainingWidth);673 formattedDescription = wrappedDescription.replace(674 /\n/g,675 '\n' + ' '.repeat(termWidth + spacerWidth),676 );677 }678679 // Construct and overall indent.

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 680why, one step back
680 return (

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 681–684why, one step back
681 itemIndentStr +
682 paddedTerm +683 ' '.repeat(spacerWidth) +684 formattedDescription.replace(/\n/g, `\n${itemIndentStr}`)

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 685why, one step back
685 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 686why, one step back
686 }

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 687–731why, one step back
687
688 /**689 * Wrap a string at whitespace, preserving existing line breaks.690 * Wrapping is skipped if the width is less than `minWidthToWrap`.691 *692 * @param {string} str693 * @param {number} width694 * @returns {string}695 */696 boxWrap(str, width) {697 if (width < this.minWidthToWrap) return str;698699 const rawLines = str.split(/\r\n|\n/);700 // split up text by whitespace701 const chunkPattern = /[\s]*[^\s]+/g;702 const wrappedLines = [];703 rawLines.forEach((line) => {704 const chunks = line.match(chunkPattern);705 if (chunks === null) {706 wrappedLines.push('');707 return;708 }709710 let sumChunks = [chunks.shift()];711 let sumWidth = this.displayWidth(sumChunks[0]);712 chunks.forEach((chunk) => {713 const visibleWidth = this.displayWidth(chunk);714 // Accumulate chunks while they fit into width.715 if (sumWidth + visibleWidth <= width) {716 sumChunks.push(chunk);717 sumWidth += visibleWidth;718 return;719 }720 wrappedLines.push(sumChunks.join(''));721722 const nextChunk = chunk.trimStart(); // trim space at line break723 sumChunks = [nextChunk];724 sumWidth = this.displayWidth(nextChunk);725 });726 wrappedLines.push(sumChunks.join(''));727 });728729 return wrappedLines.join('\n');730 }731}