Skip to content
Myr

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

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by John Gee · committed by GitHub · parent 5a79585 · Browse files · 17 files+1404 added−333 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

17 files+1404 added−333 removed

  • tests:+688 added−219 removed
  • other:+716 added−114 removed

17 files+1404 added−333 removed

added:examples/color-help-replacement.mjs+113 added
1import stripAnsi from 'strip-ansi';2import wrapAnsi from 'wrap-ansi';3import {4 default as chalkStdOut,5 chalkStderr as chalkStdErr,6 supportsColor as supportsColorStdout,7 supportsColorStderr,8} from 'chalk';9import { Command, Help } from 'commander';1011// Replace default color and wrapping support with Chalk packages as an example of12// a deep replacement of format and style support.1314// This example requires chalk and wrap-ansi and strip-ansi, and won't run15// from a clone of Commander repo without installing them first.16//17// For example using npm:18// npm install chalk wrap-ansi strip-ansi1920class MyHelp extends Help {21 constructor() {22 super();23 this.chalk = chalkStdOut;24 }2526 prepareContext(contextOptions) {27 super.prepareContext(contextOptions);28 if (contextOptions?.error) {29 this.chalk = chalkStdErr;30 }31 }3233 displayWidth(str) {34 return stripAnsi(str).length; // use imported package35 }3637 boxWrap(str, width) {38 return wrapAnsi(str, width, { hard: true }); // use imported package39 }4041 styleTitle(str) {42 return this.chalk.bold(str);43 }44 styleCommandText(str) {45 return this.chalk.cyan(str);46 }47 styleCommandDescription(str) {48 return this.chalk.magenta(str);49 }50 styleItemDescription(str) {51 return this.chalk.italic(str);52 }53 styleOptionText(str) {54 return this.chalk.green(str);55 }56 styleArgumentText(str) {57 return this.chalk.yellow(str);58 }59 styleSubcommandText(str) {60 return this.chalk.blue(str);61 }62}6364class MyCommand extends Command {65 createCommand(name) {66 return new MyCommand(name);67 }68 createHelp() {69 return Object.assign(new MyHelp(), this.configureHelp());70 }71}7273const program = new MyCommand();7475// Override the color detection to use Chalk's detection.76// Chalk overrides color support based on the `FORCE_COLOR` environment variable,77// and looks for --color and --no-color command-line options.78// See https://github.com/chalk/chalk?tab=readme-ov-file#supportscolor79//80// In general we want stripColor() to be consistent with displayWidth().81program.configureOutput({82 getOutHasColors: () => supportsColorStdout,83 getErrHasColors: () => supportsColorStderr,84 stripColor: (str) => stripAnsi(str),85});8687program.description('program description '.repeat(10));88program89 .option('-s', 'short description')90 .option('--long <number>', 'long description '.repeat(10))91 .option('--color', 'force color output') // implemented by chalk92 .option('--no-color', 'disable color output'); // implemented by chalk9394program.addHelpText('after', (context) => {95 const chalk = context.error ? chalkStdErr : chalkStdOut;96 return chalk.italic('\nThis is additional help text.');97});9899program.command('esses').description('sssss '.repeat(33));100101program102 .command('print')103 .description('print files')104 .argument('<files...>', 'files to queue for printing')105 .option('--double-sided', 'print on both sides');106107program.parse();108109// Try the following (after installing the required packages):110// node color-help-replacement.mjs --help111// node color-help-replacement.mjs --no-color help112// FORCE_COLOR=0 node color-help-replacement.mjs help113// node color-help-replacement.mjs help print
added:examples/color-help.mjs+41 added
added:examples/help-centered.mjs+42 added
added:examples/man-style-help.mjs+41 added
modified:lib/command.js+108 added-32 removed
4 unmodified lines
5const process = require('node:process');67const { Argument, humanReadableArgName } = require('./argument.js');8const { CommanderError } = require('./error.js');9const { Help } = require('./help.js');9const { Help, stripColor } = require('./help.js');10const { Option, DualOptions } = require('./option.js');11const { suggestSimilar } = require('./suggestSimilar');1213class Command extends EventEmitter {
41 unmodified lines
55 /** @type {(boolean | string)} */56 this._showHelpAfterError = false;57 this._showSuggestionAfterError = true;5859 // see .configureOutput() for docs59 // see configureOutput() for docs60 this._outputConfiguration = {61 writeOut: (str) => process.stdout.write(str),62 writeErr: (str) => process.stderr.write(str),63 outputError: (str, write) => write(str),64 getOutHelpWidth: () =>65 process.stdout.isTTY ? process.stdout.columns : undefined,66 getErrHelpWidth: () =>67 process.stderr.isTTY ? process.stderr.columns : undefined,67 outputError: (str, write) => write(str),68 getOutHasColors: () =>69 useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),70 getErrHasColors: () =>71 useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),72 stripColor: (str) => stripColor(str),73 };7475 this._hidden = false;76 /** @type {(Option | null | undefined)} */
140 unmodified lines
217 * applications. You can also customise the display of errors by overriding outputError.218 *219 * The configuration properties are all functions:220 *216 * // functions to change where being written, stdout and stderr221 * // change how output being written, defaults to stdout and stderr222 * writeOut(str)223 * writeErr(str)224 * // change how output being written for errors, defaults to writeErr225 * outputError(str, write) // used for displaying errors and not used for displaying help219 * // matching functions to specify width for wrapping help226 * // specify width for wrapping help227 * getOutHelpWidth()228 * getErrHelpWidth()222 * // functions based on what is being written out223 * outputError(str, write) // used for displaying errors, and not used for displaying help229 * // color support, currently only used with Help230 * getOutHasColors()231 * getErrHasColors()232 * stripColor() // used to remove ANSI escape codes if output does not have colours233 *234 * @param {object} [configuration] - configuration options235 * @return {(Command | object)} `this` command for chaining, or stored configuration236 */
2025 unmodified lines
2262 */22632264 helpInformation(contextOptions) {2265 const helper = this.createHelp();2257 if (helper.helpWidth === undefined) {2258 helper.helpWidth =2259 contextOptions && contextOptions.error2260 ? this._outputConfiguration.getErrHelpWidth()2261 : this._outputConfiguration.getOutHelpWidth();2262 }2263 return helper.formatHelp(this, helper);2266 const context = this._getOutputContext(contextOptions);2267 helper.prepareContext({2268 error: context.error,2269 helpWidth: context.helpWidth,2270 outputHasColors: context.hasColors,2271 });2272 const text = helper.formatHelp(this, helper);2273 if (context.hasColors) return text;2274 return this._outputConfiguration.stripColor(text);2275 }22762277 /**2278 * @typedef HelpContext2279 * @type {object}2280 * @property {boolean} error2281 * @property {number} helpWidth2282 * @property {boolean} hasColors2283 * @property {function} write - includes stripColor if needed2284 *2285 * @returns {HelpContext}2286 * @private2287 */22882270 _getHelpContext(contextOptions) {2289 _getOutputContext(contextOptions) {2290 contextOptions = contextOptions || {};2272 const context = { error: !!contextOptions.error };2273 let write;2274 if (context.error) {2275 write = (arg) => this._outputConfiguration.writeErr(arg);2291 const error = !!contextOptions.error;2292 let baseWrite;2293 let hasColors;2294 let helpWidth;2295 if (error) {2296 baseWrite = (str) => this._outputConfiguration.writeErr(str);2297 hasColors = this._outputConfiguration.getErrHasColors();2298 helpWidth = this._outputConfiguration.getErrHelpWidth();2299 } else {2277 write = (arg) => this._outputConfiguration.writeOut(arg);2300 baseWrite = (str) => this._outputConfiguration.writeOut(str);2301 hasColors = this._outputConfiguration.getOutHasColors();2302 helpWidth = this._outputConfiguration.getOutHelpWidth();2303 }2279 context.write = contextOptions.write || write;2280 context.command = this;2281 return context;2304 const write = (str) => {2305 if (!hasColors) str = this._outputConfiguration.stripColor(str);2306 return baseWrite(str);2307 };2308 return { error, write, hasColors, helpWidth };2309 }23102311 /**2312 * Output help information for this command.
8 unmodified lines
2321 if (typeof contextOptions === 'function') {2322 deprecatedCallback = contextOptions;2323 contextOptions = undefined;2324 }2298 const context = this._getHelpContext(contextOptions);23252326 const outputContext = this._getOutputContext(contextOptions);2327 /** @type {HelpTextEventContext} */2328 const eventContext = {2329 error: outputContext.error,2330 write: outputContext.write,2331 command: this,2332 };23332334 this._getCommandAndAncestors()2335 .reverse()2302 .forEach((command) => command.emit('beforeAllHelp', context));2303 this.emit('beforeHelp', context);2336 .forEach((command) => command.emit('beforeAllHelp', eventContext));2337 this.emit('beforeHelp', eventContext);23382305 let helpInformation = this.helpInformation(context);2339 let helpInformation = this.helpInformation({ error: outputContext.error });2340 if (deprecatedCallback) {2341 helpInformation = deprecatedCallback(helpInformation);2342 if (2343 typeof helpInformation !== 'string' &&
1 unmodified line
2345 ) {2346 throw new Error('outputHelp callback must return a string or a Buffer');2347 }2348 }2315 context.write(helpInformation);2349 outputContext.write(helpInformation);23502351 if (this._getHelpOption()?.long) {2352 this.emit(this._getHelpOption().long); // deprecated2353 }2320 this.emit('afterHelp', context);2354 this.emit('afterHelp', eventContext);2355 this._getCommandAndAncestors().forEach((command) =>2322 command.emit('afterAllHelp', context),2356 command.emit('afterAllHelp', eventContext),2357 );2358 }23592360 /**
11 unmodified lines
23722373 helpOption(flags, description) {2374 // Support disabling built-in help option.2375 if (typeof flags === 'boolean') {2376 // true is not an expected value. Do something sensible but no unit-test.2377 // istanbul ignore if2378 if (flags) {2379 this._helpOption = this._helpOption ?? undefined; // preserve existing option2380 } else {2381 this._helpOption = null; // disable
45 unmodified lines
2427 */24282429 help(contextOptions) {2430 this.outputHelp(contextOptions);2395 let exitCode = Number(process.exitCode ?? 0); // process.exitCode does allow a string of an integer, but we prefer just a number2431 let exitCode = Number(process.exitCode ?? 0); // process.exitCode does allow a string or an integer, but we prefer just a number2432 if (2433 exitCode === 0 &&2434 contextOptions &&2435 typeof contextOptions !== 'function' &&
5 unmodified lines
2441 this._exit(exitCode, 'commander.help', '(outputHelp)');2442 }24432444 /**2445 * // Do a little typing to coordinate emit and listener for the help text events.2446 * @typedef HelpTextEventContext2447 * @type {object}2448 * @property {boolean} error2449 * @property {Command} command2450 * @property {function} write2451 */24522453 /**2454 * Add additional text to be displayed with the built-in help.2455 *2456 * Position is 'before' or 'after' to affect just this command,2457 * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
1 unmodified line
2459 * @param {string} position - before or after built-in help2460 * @param {(string | Function)} text - string to add, or a function returning a string2461 * @return {Command} `this` command for chaining2462 */24632464 addHelpText(position, text) {2465 const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];2466 if (!allowedValues.includes(position)) {2467 throw new Error(`Unexpected value for position to addHelpText.2468Expecting one of '${allowedValues.join("', '")}'`);2469 }24702471 const helpEvent = `${position}Help`;2425 this.on(helpEvent, (context) => {2472 this.on(helpEvent, (/** @type {HelpTextEventContext} */ context) => {2473 let helpStr;2474 if (typeof text === 'function') {2475 helpStr = text({ error: context.error, command: context.command });2476 } else {
75 unmodified lines
2552 return arg;2553 });2554}25552556/**2557 * @returns {boolean | undefined}2558 * @package2559 */2560function useColor() {2561 // Test for common conventions.2562 // NB: the observed behaviour is in combination with how author adds color! For example:2563 // - we do not test NODE_DISABLE_COLORS, but util:styletext does2564 // - we do test NO_COLOR, but Chalk does not2565 //2566 // References:2567 // https://no-color.org2568 // https://bixense.com/clicolors/2569 // https://github.com/nodejs/node/blob/0a00217a5f67ef4a22384cfc80eb6dd9a917fdc1/lib/internal/tty.js#L1092570 // https://github.com/chalk/supports-color/blob/c214314a14bcb174b12b3014b2b0a8de375029ae/index.js#L332571 // (https://force-color.org recent web page from 2023, does not match major javascript implementations)25722573 if (2574 process.env.NO_COLOR ||2575 process.env.FORCE_COLOR === '0' ||2576 process.env.FORCE_COLOR === 'false'2577 )2578 return false;2579 if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== undefined)2580 return true;2581 return undefined;2582}25832584exports.Command = Command;2585exports.useColor = useColor; // exporting for tests
modified:lib/help.js+259 added-71 removed
10 unmodified lines
11// 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.minWidthToWrap = 40;16 this.sortSubcommands = false;17 this.sortOptions = false;18 this.showGlobalOptions = false;19 }2021 /**22 * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`23 * and just before calling `formatHelp()`.24 *25 * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.26 *27 * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions28 */29 prepareContext(contextOptions) {30 this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;31 }3233 /**34 * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.35 *36 * @param {Command} cmd37 * @returns {Command[]}
165 unmodified lines
203 */204205 longestSubcommandTermLength(cmd, helper) {206 return helper.visibleCommands(cmd).reduce((max, command) => {194 return Math.max(max, helper.subcommandTerm(command).length);207 return Math.max(208 max,209 this.displayWidth(210 helper.styleSubcommandTerm(helper.subcommandTerm(command)),211 ),212 );213 }, 0);214 }215216 /**
5 unmodified lines
222 */223224 longestOptionTermLength(cmd, helper) {225 return helper.visibleOptions(cmd).reduce((max, option) => {208 return Math.max(max, helper.optionTerm(option).length);226 return Math.max(227 max,228 this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),229 );230 }, 0);231 }232233 /**
5 unmodified lines
239 */240241 longestGlobalOptionTermLength(cmd, helper) {242 return helper.visibleGlobalOptions(cmd).reduce((max, option) => {222 return Math.max(max, helper.optionTerm(option).length);243 return Math.max(244 max,245 this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),246 );247 }, 0);248 }249250 /**
5 unmodified lines
256 */257258 longestArgumentTermLength(cmd, helper) {259 return helper.visibleArguments(cmd).reduce((max, argument) => {236 return Math.max(max, helper.argumentTerm(argument).length);260 return Math.max(261 max,262 this.displayWidth(263 helper.styleArgumentTerm(helper.argumentTerm(argument)),264 ),265 );266 }, 0);267 }268269 /**
127 unmodified lines
397 */398399 formatHelp(cmd, helper) {400 const termWidth = helper.padWidth(cmd, helper);372 const helpWidth = helper.helpWidth || 80;373 const itemIndentWidth = 2;374 const itemSeparatorWidth = 2; // between term and description375 function formatItem(term, description) {376 if (description) {377 const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;378 return helper.wrap(379 fullText,380 helpWidth - itemIndentWidth,381 termWidth + itemSeparatorWidth,382 );383 }384 return term;401 const helpWidth = helper.helpWidth ?? 80; // in case prepareContext() was not called402403 function callFormatItem(term, description) {404 return helper.formatItem(405 term,406 termWidth,407 helper.styleItemDescription(description),408 helper,409 );410 }386 function formatList(textArray) {387 return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth));388 }411412 // Usage391 let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];413 let output = [414 `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,415 '',416 ];417418 // Description419 const commandDescription = helper.commandDescription(cmd);420 if (commandDescription.length > 0) {421 output = output.concat([397 helper.wrap(commandDescription, helpWidth, 0),422 helper.boxWrap(423 helper.styleCommandDescription(commandDescription),424 helpWidth,425 ),426 '',427 ]);428 }429430 // Arguments431 const argumentList = helper.visibleArguments(cmd).map((argument) => {404 return formatItem(405 helper.argumentTerm(argument),432 return callFormatItem(433 helper.styleArgumentTerm(helper.argumentTerm(argument)),434 helper.argumentDescription(argument),435 );436 });437 if (argumentList.length > 0) {410 output = output.concat(['Arguments:', formatList(argumentList), '']);438 output = output.concat([439 helper.styleTitle('Arguments:'),440 ...argumentList,441 '',442 ]);443 }444445 // Options446 const optionList = helper.visibleOptions(cmd).map((option) => {415 return formatItem(416 helper.optionTerm(option),447 return callFormatItem(448 helper.styleOptionTerm(helper.optionTerm(option)),449 helper.optionDescription(option),450 );451 });452 if (optionList.length > 0) {421 output = output.concat(['Options:', formatList(optionList), '']);453 output = output.concat([454 helper.styleTitle('Options:'),455 ...optionList,456 '',457 ]);458 }459424 if (this.showGlobalOptions) {460 if (helper.showGlobalOptions) {461 const globalOptionList = helper462 .visibleGlobalOptions(cmd)463 .map((option) => {428 return formatItem(429 helper.optionTerm(option),464 return callFormatItem(465 helper.styleOptionTerm(helper.optionTerm(option)),466 helper.optionDescription(option),467 );468 });469 if (globalOptionList.length > 0) {470 output = output.concat([435 'Global Options:',436 formatList(globalOptionList),471 helper.styleTitle('Global Options:'),472 ...globalOptionList,473 '',474 ]);475 }476 }477478 // Commands479 const commandList = helper.visibleCommands(cmd).map((cmd) => {444 return formatItem(445 helper.subcommandTerm(cmd),480 return callFormatItem(481 helper.styleSubcommandTerm(helper.subcommandTerm(cmd)),482 helper.subcommandDescription(cmd),483 );484 });485 if (commandList.length > 0) {450 output = output.concat(['Commands:', formatList(commandList), '']);486 output = output.concat([487 helper.styleTitle('Commands:'),488 ...commandList,489 '',490 ]);491 }492493 return output.join('\n');494 }495496 /**497 * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.498 *499 * @param {string} str500 * @returns {number}501 */502 displayWidth(str) {503 return stripColor(str).length;504 }505506 /**507 * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.508 *509 * @param {string} str510 * @returns {string}511 */512 styleTitle(str) {513 return str;514 }515516 styleUsage(str) {517 // Usage has lots of parts the user might like to color separately! Assume default usage string which is formed like:518 // command subcommand [options] [command] <foo> [bar]519 return str520 .split(' ')521 .map((word) => {522 if (word === '[options]') return this.styleOptionText(word);523 if (word === '[command]') return this.styleSubcommandText(word);524 if (word[0] === '[' || word[0] === '<')525 return this.styleArgumentText(word);526 return this.styleCommandText(word); // Restrict to initial words?527 })528 .join(' ');529 }530 styleItemDescription(str) {531 return this.styleDescriptionText(str);532 }533 styleCommandDescription(str) {534 return this.styleDescriptionText(str);535 }536 styleDescriptionText(str) {537 return str;538 }539 styleOptionTerm(str) {540 return this.styleOptionText(str);541 }542 styleSubcommandTerm(str) {543 // This is very like usage with lots of parts! Assume default string which is formed like:544 // subcommand [options] <foo> [bar]545 return str546 .split(' ')547 .map((word) => {548 if (word === '[options]') return this.styleOptionText(word);549 if (word[0] === '[' || word[0] === '<')550 return this.styleArgumentText(word);551 return this.styleSubcommandText(word); // Restrict to initial words?552 })553 .join(' ');554 }555 styleArgumentTerm(str) {556 return this.styleArgumentText(str);557 }558 styleOptionText(str) {559 return str;560 }561 styleArgumentText(str) {562 return str;563 }564 styleSubcommandText(str) {565 return str;566 }567 styleCommandText(str) {568 return str;569 }570571 /**572 * Calculate the pad width from the maximum term length.573 *574 * @param {Command} cmd575 * @param {Help} helper
9 unmodified lines
585 );586 }587588 /**474 * Wrap the given string to width characters per line, with lines after the first indented.475 * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.589 * Detect manually wrapped and indented strings by checking for line break followed by whitespace.590 *591 * @param {string} str478 * @param {number} width479 * @param {number} indent480 * @param {number} [minColumnWidth=40]481 * @return {string}592 * @returns {boolean}593 */594 preformatted(str) {595 return /\n[^\S\r\n]/.test(str);596 }597598 /**599 * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.600 *601 * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:602 * TTT DDD DDDD603 * DD DDD604 *605 * @param {string} term606 * @param {number} termWidth607 * @param {string} description608 * @param {Help} helper609 * @returns {string}610 */611 formatItem(term, termWidth, description, helper) {612 const itemIndent = 2;613 const itemIndentStr = ' '.repeat(itemIndent);614 if (!description) return itemIndentStr + term;615485 wrap(str, width, indent, minColumnWidth = 40) {486 // Full \s characters, minus the linefeeds.487 const indents =488 ' \\f\\t\\v\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff';489 // Detect manually wrapped and indented strings by searching for line break followed by spaces.490 const manualIndent = new RegExp(`[\\n][${indents}]+`);491 if (str.match(manualIndent)) return str;492 // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).493 const columnWidth = width - indent;494 if (columnWidth < minColumnWidth) return str;495496 const leadingStr = str.slice(0, indent);497 const columnText = str.slice(indent).replace('\r\n', '\n');498 const indentString = ' '.repeat(indent);499 const zeroWidthSpace = '\u200B';500 const breaks = `\\s${zeroWidthSpace}`;501 // Match line end (so empty lines don't collapse),502 // or as much text as will fit in column, or excess text up to first break.503 const regex = new RegExp(504 `\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,505 'g',616 // Pad the term out to a consistent width, so descriptions are aligned.617 const paddedTerm = term.padEnd(618 termWidth + term.length - helper.displayWidth(term),619 );507 const lines = columnText.match(regex) || [];620621 // Format the description.622 const spacerWidth = 2; // between term and description623 const helpWidth = this.helpWidth ?? 80; // in case prepareContext() was not called624 const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;625 let formattedDescription;626 if (627 remainingWidth < this.minWidthToWrap ||628 helper.preformatted(description)629 ) {630 formattedDescription = description;631 } else {632 const wrappedDescription = helper.boxWrap(description, remainingWidth);633 formattedDescription = wrappedDescription.replace(634 /\n/g,635 '\n' + ' '.repeat(termWidth + spacerWidth),636 );637 }638639 // Construct and overall indent.640 return (509 leadingStr +510 lines511 .map((line, i) => {512 if (line === '\n') return ''; // preserve empty lines513 return (i > 0 ? indentString : '') + line.trimEnd();514 })515 .join('\n')641 itemIndentStr +642 paddedTerm +643 ' '.repeat(spacerWidth) +644 formattedDescription.replace(/\n/g, `\n${itemIndentStr}`)645 );646 }647648 /**649 * Wrap a string at whitespace, preserving existing line breaks.650 * Wrapping is skipped if the width is less than `minWidthToWrap`.651 *652 * @param {string} str653 * @param {number} width654 * @returns {string}655 */656 boxWrap(str, width) {657 if (width < this.minWidthToWrap) return str;658659 const rawLines = str.split(/\r\n|\n/);660 // split up text by whitespace661 const chunkPattern = /[\s]*[^\s]+/g;662 const wrappedLines = [];663 rawLines.forEach((line) => {664 const chunks = line.match(chunkPattern);665 if (chunks === null) {666 wrappedLines.push('');667 return;668 }669670 let sumChunks = [chunks.shift()];671 let sumWidth = this.displayWidth(sumChunks[0]);672 chunks.forEach((chunk) => {673 const visibleWidth = this.displayWidth(chunk);674 // Accumulate chunks while they fit into width.675 if (sumWidth + visibleWidth <= width) {676 sumChunks.push(chunk);677 sumWidth += visibleWidth;678 return;679 }680 wrappedLines.push(sumChunks.join(''));681682 const nextChunk = chunk.trimStart(); // trim space at line break683 sumChunks = [nextChunk];684 sumWidth = this.displayWidth(nextChunk);685 });686 wrappedLines.push(sumChunks.join(''));687 });688689 return wrappedLines.join('\n');690 }691}692693/**694 * Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.695 *696 * @param {string} str697 * @returns {string}698 * @package699 */700701function stripColor(str) {702 // eslint-disable-next-line no-control-regex703 const sgrPattern = /\x1b\[\d*(;\d*)*m/g;704 return str.replace(sgrPattern, '');705}706707exports.Help = Help;708exports.stripColor = stripColor;
modified:tests/command.configureOutput.test.js+61 added
1const commander = require('../');2const process = require('node:process');34test('when default writeErr() then error on stderr', () => {5 const writeSpy = jest6 .spyOn(process.stderr, 'write')
241 unmodified lines
248249 expect(helpWidth).toBe(expectedColumns);250});251252test('when no custom setup and call formatHelp direct then effective helpWidth is fallback 80', () => {253 // Not an important case, but filling out testing coverage.254 const helper = new commander.Help();255 let wrapWidth;256 helper.boxWrap = (str, width) => {257 wrapWidth = wrapWidth ?? width;258 return '';259 };260 const program = new commander.Command()261 .description('description')262 .helpOption(false);263 helper.formatHelp(program, helper);264 expect(wrapWidth).toBe(80);265});266267test('when no custom setup and call formatItem direct then effective helpWidth is fallback 80', () => {268 // Not an important case, but filling out testing coverage.269 const helper = new commander.Help();270 let wrapWidth;271 helper.boxWrap = (str, width) => {272 wrapWidth = wrapWidth ?? width;273 return '';274 };275276 const termWidth = 8;277 helper.formatItem('term', termWidth, 'description', helper);278 const itemIndent = 2;279 const spacerWidth = 2; // between term and description280 const remainingWidth = 80 - termWidth - spacerWidth - itemIndent;281282 expect(wrapWidth).toBe(remainingWidth);283});284285test('when set configureOutput then get configureOutput', () => {286 const outputOptions = {287 writeOut: jest.fn(),288 writeErr: jest.fn(),289 getOutHelpWidth: jest.fn(),290 getErrHelpWidth: jest.fn(),291 getOutHasColors: jest.fn(),292 getErrHasColors: jest.fn(),293 outputError: jest.fn(),294 stripColor: jest.fn(),295 };296 const program = new commander.Command();297 program.configureOutput(outputOptions);298 expect(program.configureOutput()).toEqual(outputOptions);
28 unmodified lines
327 "error: unknown option '--unknownOption'\n",328 writeErr,329 );330});331332describe.each([['getOutHasColors'], ['getErrHasColors']])(333 '%s',334 (configProperty) => {335 // Tried and failed to mock/modify process.stdout.isTTY to test that part of implementation.336 // Just test overrides work as expected!337338 const getHasColors = new commander.Command().configureOutput()[339 configProperty340 ];341342 test.each([343 [true, 'NO_COLOR', false],344 [false, 'FORCE_COLOR', true],345 [false, 'CLICOLOR_FORCE', true],346 ])('when isTTY=%o but %s then returns %o', (isTTY, envvar, result) => {347 const holdEnv = process.env[envvar];348 process.env[envvar] = '1';349 expect(getHasColors()).toBe(result);350 if (holdEnv === undefined) delete process.env[envvar];351 else process.env[envvar] = holdEnv;352 });353 },354);
added:tests/help.boxWrap.test.js+114 added
1const commander = require('../');23test('when empty string then return empty string', () => {4 const helper = new commander.Help();5 const text = '';6 const wrapped = helper.boxWrap(text, 50);7 expect(wrapped).toEqual(text);8});910test('when string contains unix line breaks then return (unix) empty lines', () => {11 const helper = new commander.Help();12 const text = '\n\n\n';13 const wrapped = helper.boxWrap(text, 50);14 expect(wrapped).toEqual(text);15});1617test('when string contains Windows line breaks then return (unix)) empty lines', () => {18 const helper = new commander.Help();19 const text = '\r\n\r\n\r\n';20 const wrapped = helper.boxWrap(text, 50);21 expect(wrapped).toEqual('\n\n\n');22});2324test('when string contains only whitespace then returns empty string (trim right)', () => {25 const helper = new commander.Help();26 const text = ' \t ';27 const wrapped = helper.boxWrap(text, 50);28 expect(wrapped).toEqual('');29});3031test('when string contains leading whitespace then returns string with leading whitespace', () => {32 const helper = new commander.Help();33 const text = ' abc';34 const wrapped = helper.boxWrap(text, 50);35 expect(wrapped).toEqual(' abc');36});3738test('when string contains intermediate whitespace then returns string with intermediate whitespace', () => {39 const helper = new commander.Help();40 const text = '123 456';41 const wrapped = helper.boxWrap(text, 50);42 expect(wrapped).toEqual('123 456');43});4445test('when string contains trailing whitespace then returns string without trailing whitespace (trim right)', () => {46 const helper = new commander.Help();47 const text = '123 456 ';48 const wrapped = helper.boxWrap(text, 50);49 expect(wrapped).toEqual('123 456');50});5152test('when string contains escape sequences then returns string with escape sequences', () => {53 const helper = new commander.Help();54 const text = '123 456 ';55 const wrapped = helper.boxWrap(text, 50);56 expect(wrapped).toEqual('123 456');57});5859test('when string has enough words to wrap then returns two wrapped lines', () => {60 const helper = new commander.Help();61 const text = '123 567 901 345 789 123 567 901 345 789 123 567 901';62 const wrapped = helper.boxWrap(text, 45);63 expect(wrapped).toEqual(64 '123 567 901 345 789 123 567 901 345 789 123\n567 901',65 );66});6768test('when string has enough words and escape sequences to wrap then returns wrapped line with break ignoring escape sequences', () => {69 const helper = new commander.Help();70 const CSI = '\u001b[';71 const underlinedText = `${CSI}4mXYZ${CSI}24m`;72 const text = `${underlinedText}${' ABC'.repeat(19)}`;73 const wrapped = helper.boxWrap(text, 44);74 expect(wrapped).toEqual(`${underlinedText} ${'ABC '.repeat(9)}ABC75${'ABC '.repeat(8)}ABC`);76});7778test('when first word longer than width then soft wrap', () => {79 const helper = new commander.Help();80 const text = 'abc'.repeat(20);81 const wrapped = helper.boxWrap(text, 40);82 expect(wrapped).toEqual(text);83});8485test('when second word longer than width then wrap and soft wrap', () => {86 const helper = new commander.Help();87 const text = 'xyz ' + 'abc'.repeat(20);88 const wrapped = helper.boxWrap(text, 40);89 expect(wrapped).toEqual(`xyz\n${'abc'.repeat(20)}`);90});9192test('when set width 41 then wrap at 41', () => {93 const helper = new commander.Help();94 const text = 'X'.repeat(39) + ' 1 2 3';95 let wrapped = helper.boxWrap(text, 40);96 expect(wrapped).toEqual('X'.repeat(39) + '\n1 2 3');97 wrapped = helper.boxWrap(text, 41);98 expect(wrapped).toEqual('X'.repeat(39) + ' 1\n2 3');99});100101test('when set width 12 (too small) then skip wrap', () => {102 const helper = new commander.Help();103 const text = ' x'.repeat(8) + ' yy'.repeat(6);104 let wrapped = helper.boxWrap(text, 14);105 expect(wrapped).toEqual(text);106});107108test('when set width 12 (and set minWrapWidth) then skip wrap', () => {109 const helper = new commander.Help();110 helper.minWidthToWrap = 1;111 const text = ' x'.repeat(8) + ' yy'.repeat(6);112 let wrapped = helper.boxWrap(text, 14);113 expect(wrapped).toEqual(' x x x x x x x\nx yy yy yy yy\nyy yy');114});
added:tests/help.minWidthToWrap.test.js+47 added
added:tests/help.preformatted.test.js+70 added
added:tests/help.stripAnsi.test.js+65 added
1const { stripColor } = require('../lib/help');23// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters45// Test the lowest level routine being used for SGR support.67const ESC = '\u001b';8const CSI = ESC + '[';910test('SGR only', () => {11 const str = `${CSI}4m`;12 expect(stripColor(str)).toEqual('');13});1415test('SGR at start', () => {16 const str = `${CSI}4mX`;17 expect(stripColor(str)).toEqual('X');18});1920test('SGR in middle', () => {21 const str = `X${CSI}4mY`;22 expect(stripColor(str)).toEqual('XY');23});2425test('SGR at end', () => {26 const str = `${CSI}4mY`;27 expect(stripColor(str)).toEqual('Y');28});2930test('SGR pair', () => {31 // underline and not underlined32 const str = `${CSI}4mABC${CSI}24m`;33 expect(stripColor(str)).toEqual('ABC');34});3536test('explicit reset with zero', () => {37 const str = `${CSI}0m`;38 expect(stripColor(str)).toEqual('');39});4041test('implicit reset without zero', () => {42 const str = `${CSI}m`;43 expect(stripColor(str)).toEqual('');44});4546test('multiple params: select foreground colour', () => {47 const str = `${CSI}38;5;4m`;48 expect(stripColor(str)).toEqual('');49});5051test('multiple params: general', () => {52 const str = `${CSI}2;3;4m`;53 expect(stripColor(str)).toEqual('');54});5556test('multiple params: missing param', () => {57 // CSI sequences can omit number (which is then treated as 0)58 const str = `${CSI};;m`;59 expect(stripColor(str)).toEqual('');60});6162test('incomplete SGR sequence', () => {63 const str = `${CSI}14X`;64 expect(stripColor(str)).toEqual(`${CSI}14X`);65});
added:tests/help.style.test.js+248 added
1const { Command } = require('../');23function red(str) {4 // Use plain characters so not stripped in Jest failure messages. (Means displayWidth is bogus though.)5 return `RED ${str} DER`;6}7function stripRed(str) {8 return str.replace(/RED /g, '').replace(/ DER/g, '');9}10function displayWidth(str) {11 // Not really zero width for the "color", but pretend so spacing matches no-color output.12 return stripRed(str).length;13}1415describe('override style methods and check help information', () => {16 function makeProgram() {17 const program = new Command('program')18 .description('program description')19 .argument('<file>', 'arg description')20 .configureOutput({21 getOutHasColors: () => true, // avoid interactions with testing environment22 });23 program24 .command('subcommand')25 .description('sub description')26 .option('--suboption')27 .argument('[subarg]');2829 return program;30 }3132 const plainHelpInformation = makeProgram().helpInformation();3334 test('styleTitle', () => {35 const program = makeProgram();36 program.configureHelp({ styleTitle: (str) => red(str) }, displayWidth);37 const helpText = program.helpInformation();38 expect(helpText).toEqual(39 plainHelpInformation40 .replace('Usage:', red('Usage:'))41 .replace('Arguments:', red('Arguments:'))42 .replace('Options:', red('Options:'))43 .replace('Commands:', red('Commands:')),44 );45 });4647 test('styleUsage', () => {48 const program = makeProgram();49 program.configureHelp({ styleUsage: (str) => red(str), displayWidth });50 const helpText = program.helpInformation();51 const usageString = program.createHelp().commandUsage(program);52 expect(helpText).toEqual(53 plainHelpInformation.replace(usageString, red(usageString)),54 );55 });5657 test('styleItemDescription', () => {58 const program = makeProgram();59 program.configureHelp({60 styleItemDescription: (str) => red(str),61 displayWidth,62 });63 const helpText = program.helpInformation();64 expect(helpText).toEqual(65 plainHelpInformation66 .replace('arg description', red('arg description'))67 .replace('sub description', red('sub description'))68 .replace(/display help for command/g, red('display help for command')),69 );70 });7172 test('styleCommandDescription', () => {73 const program = makeProgram();74 program.configureHelp({75 styleCommandDescription: (str) => red(str),76 displayWidth,77 });78 const helpText = program.helpInformation();79 expect(helpText).toEqual(80 plainHelpInformation.replace(81 'program description',82 red('program description'),83 ),84 );85 });8687 test('styleDescriptionText', () => {88 const program = makeProgram();89 program.configureHelp({90 styleDescriptionText: (str) => red(str),91 displayWidth,92 });93 const helpText = program.helpInformation();94 expect(helpText).toEqual(95 plainHelpInformation96 .replace('program description', red('program description'))97 .replace('arg description', red('arg description'))98 .replace('sub description', red('sub description'))99 .replace(/display help for command/g, red('display help for command')),100 );101 });102103 test('styleOptionTerm', () => {104 const program = makeProgram();105 program.configureHelp({ styleOptionTerm: (str) => red(str), displayWidth });106 const helpText = program.helpInformation();107 expect(helpText).toEqual(108 plainHelpInformation.replace('-h, --help', red('-h, --help')),109 );110 });111112 test('styleSubcommandTerm', () => {113 const program = makeProgram();114 program.configureHelp({115 styleSubcommandTerm: (str) => red(str),116 displayWidth,117 });118 const helpText = program.helpInformation();119 expect(helpText).toEqual(120 plainHelpInformation121 .replace('help [command]', red('help [command]'))122 .replace(123 'subcommand [options] [subarg]',124 red('subcommand [options] [subarg]'),125 ),126 );127 });128129 test('styleArgumentTerm', () => {130 const program = makeProgram();131 program.configureHelp({132 styleArgumentTerm: (str) => red(str),133 displayWidth,134 });135 const helpText = program.helpInformation();136 expect(helpText).toEqual(137 plainHelpInformation.replace(' file ', ` ${red('file')} `),138 );139 });140141 test('styleOptionText', () => {142 const program = makeProgram();143 program.configureHelp({144 styleOptionText: (str) => red(str),145 displayWidth,146 });147 const helpText = program.helpInformation();148 expect(helpText).toEqual(149 plainHelpInformation150 .replace(/\[options\]/g, red('[options]'))151 .replace('-h, --help', red('-h, --help')),152 );153 });154155 test('styleArgumentText', () => {156 const program = makeProgram();157 program.configureHelp({158 styleArgumentText: (str) => red(str),159 displayWidth,160 });161 const helpText = program.helpInformation();162 expect(helpText).toEqual(163 plainHelpInformation164 .replace('<file>', red('<file>'))165 .replace(' file ', ` ${red('file')} `)166 .replace('[subarg]', red('[subarg]'))167 .replace('help [command]', `help ${red('[command]')}`),168 );169 });170171 test('styleSubcommandText', () => {172 const program = makeProgram();173 program.configureHelp({174 styleSubcommandText: (str) => red(str),175 displayWidth,176 });177 const helpText = program.helpInformation();178 expect(helpText).toEqual(179 plainHelpInformation180 .replace('[command] <file>', `${red('[command]')} <file>`)181 .replace('help [command]', `${red('help')} [command]`)182 .replace('subcommand', red('subcommand')),183 );184 });185186 test('styleCommandText', () => {187 const program = makeProgram();188 program.configureHelp({189 styleCommandText: (str) => red(str),190 displayWidth,191 });192 const helpText = program.helpInformation();193 expect(helpText).toEqual(194 plainHelpInformation.replace('program', red('program')),195 );196 });197});198199describe('check styles with configureOutput overrides for color', () => {200 function makeProgram(hasColors) {201 const program = new Command('program');202 program.myHelpText = [];203 program204 .description('program description')205 .argument('<file>', 'arg description')206 .configureOutput({207 getOutHasColors: () => hasColors,208 stripColor: (str) => stripRed(str),209 writeOut: (str) => {210 program.myHelpText.push(str);211 },212 });213 program.configureHelp({214 styleCommandText: (str) => red(str),215 displayWidth,216 });217218 return program;219 }220221 test('when getOutHasColors returns true then help has color', () => {222 const program = makeProgram(true);223 program.outputHelp();224 const helpText = program.myHelpText.join('');225 expect(helpText).toMatch(red('program'));226 });227228 test('when getOutHasColors returns false then help does not have color', () => {229 const program = makeProgram(false);230 program.outputHelp();231 const helpText = program.myHelpText.join('');232 expect(helpText).not.toMatch(red('program'));233 });234235 test('when getOutHasColors returns false then style still called', () => {236 const program = makeProgram(true);237 // Overwrite styleCommandText so we can track whether called.238 let styleCalled = false;239 const config = program.configureHelp();240 config.styleCommandText = (str) => {241 styleCalled = true;242 return red(str);243 };244 program.configureHelp(config);245 program.outputHelp();246 expect(styleCalled).toBe(true);247 });248});
deleted:tests/help.wrap.test.js-219 removed
1const commander = require('../');23// These are tests of the Help class, not of the Command help.4// There is some overlap with the higher level Command tests (which predate Help).56describe('wrap', () => {7 test('when string fits into width then returns input', () => {8 const text = 'a '.repeat(24) + 'a';9 const helper = new commander.Help();10 const wrapped = helper.wrap(text, 50, 3);11 expect(wrapped).toEqual(text);12 });1314 test('when string shorter than indent then returns input', () => {15 const text = 'a';16 const helper = new commander.Help();17 const wrapped = helper.wrap(text, 50, 3);18 expect(wrapped).toEqual(text);19 });2021 test('when string exceeds width then wrap', () => {22 const text = 'a '.repeat(30) + 'a';23 const helper = new commander.Help();24 const wrapped = helper.wrap(text, 50, 0);25 expect(wrapped).toEqual(`${'a '.repeat(24)}a26${'a '.repeat(5)}a`);27 });2829 test('when string exceeds width then wrap and indent', () => {30 const text = 'a '.repeat(30) + 'a';31 const helper = new commander.Help();32 const wrapped = helper.wrap(text, 50, 10);33 expect(wrapped).toEqual(`${'a '.repeat(24)}a34${' '.repeat(10)}${'a '.repeat(5)}a`);35 });3637 test('when width < 40 then do not wrap', () => {38 const text = 'a '.repeat(30) + 'a';39 const helper = new commander.Help();40 const wrapped = helper.wrap(text, 39, 0);41 expect(wrapped).toEqual(text);42 });4344 test('when text has line break then respect and indent', () => {45 const text = 'term description\nanother line';46 const helper = new commander.Help();47 const wrapped = helper.wrap(text, 78, 5);48 expect(wrapped).toEqual('term description\n another line');49 });5051 test('when text has consecutive line breaks then respect and indent', () => {52 const text = 'term description\n\nanother line';53 const helper = new commander.Help();54 const wrapped = helper.wrap(text, 78, 5);55 expect(wrapped).toEqual('term description\n\n another line');56 });5758 test('when text has Windows line break then respect and indent', () => {59 const text = 'term description\r\nanother line';60 const helper = new commander.Help();61 const wrapped = helper.wrap(text, 78, 5);62 expect(wrapped).toEqual('term description\n another line');63 });6465 test('when text has Windows consecutive line breaks then respect and indent', () => {66 const text = 'term description\r\n\r\nanother line';67 const helper = new commander.Help();68 const wrapped = helper.wrap(text, 78, 5);69 expect(wrapped).toEqual('term description\n\n another line');70 });7172 test('when text already formatted with line breaks and indent then do not touch', () => {73 const text = 'term a '.repeat(25) + '\n ' + 'a '.repeat(25) + 'a';74 const helper = new commander.Help();75 const wrapped = helper.wrap(text, 78, 5);76 expect(wrapped).toEqual(text);77 });78});7980describe('wrapping by formatHelp', () => {81 // Test auto wrap and indent with some manual strings.82 // Fragile tests with complete help output.8384 test('when long option description then wrap and indent', () => {85 const program = new commander.Command();86 program87 .configureHelp({ helpWidth: 80 })88 .option(89 '-x --extra-long-option-switch',90 'kjsahdkajshkahd kajhsd akhds kashd kajhs dkha dkh aksd ka dkha kdh kasd ka kahs dkh sdkh askdh aksd kashdk ahsd kahs dkha skdh',91 );9293 const expectedOutput = `Usage: [options]9495Options:96 -x --extra-long-option-switch kjsahdkajshkahd kajhsd akhds kashd kajhs dkha97 dkh aksd ka dkha kdh kasd ka kahs dkh sdkh98 askdh aksd kashdk ahsd kahs dkha skdh99 -h, --help display help for command100`;101102 expect(program.helpInformation()).toBe(expectedOutput);103 });104105 test('when long option description and default then wrap and indent', () => {106 const program = new commander.Command();107 program108 .configureHelp({ helpWidth: 80 })109 .option(110 '-x --extra-long-option <value>',111 'kjsahdkajshkahd kajhsd akhds',112 'aaa bbb ccc ddd eee fff ggg',113 );114115 const expectedOutput = `Usage: [options]116117Options:118 -x --extra-long-option <value> kjsahdkajshkahd kajhsd akhds (default: "aaa119 bbb ccc ddd eee fff ggg")120 -h, --help display help for command121`;122123 expect(program.helpInformation()).toBe(expectedOutput);124 });125126 test('when long subcommand description then wrap and indent', () => {127 const program = new commander.Command();128 program129 .configureHelp({ helpWidth: 80 })130 .option('-x --extra-long-option-switch', 'x')131 .command(132 'alpha',133 'Lorem mollit quis dolor ex do eu quis ad insa a commodo esse.',134 );135136 const expectedOutput = `Usage: [options] [command]137138Options:139 -x --extra-long-option-switch x140 -h, --help display help for command141142Commands:143 alpha Lorem mollit quis dolor ex do eu quis ad insa144 a commodo esse.145 help [command] display help for command146`;147148 expect(program.helpInformation()).toBe(expectedOutput);149 });150151 test('when not enough room then help not wrapped', () => {152 // Not wrapping if less than 40 columns available for wrapping.153 const program = new commander.Command();154 const commandDescription =155 'description text of very long command which should not be automatically be wrapped. Do fugiat eiusmod ipsum laboris excepteur pariatur sint ullamco tempor labore eu.';156 program157 .configureHelp({ helpWidth: 60 })158 .command('1234567801234567890x', commandDescription);159160 const expectedOutput = `Usage: [options] [command]161162Options:163 -h, --help display help for command164165Commands:166 1234567801234567890x ${commandDescription}167 help [command] display help for command168`;169170 expect(program.helpInformation()).toBe(expectedOutput);171 });172173 test('when option description pre-formatted then only add small indent', () => {174 // #396: leave custom format alone, apart from space-space indent175 const optionSpec = '-t, --time <HH:MM>';176 const program = new commander.Command();177 program.configureHelp({ helpWidth: 80 }).option(178 optionSpec,179 `select time180181Time can also be specified using special values:182 "dawn" - From night to sunrise.183`,184 );185186 const expectedOutput = `Usage: [options]187188Options:189 ${optionSpec} select time190 191 Time can also be specified using special values:192 "dawn" - From night to sunrise.193 194 -h, --help display help for command195`;196197 expect(program.helpInformation()).toBe(expectedOutput);198 });199200 test('when command description long then wrapped', () => {201 const program = new commander.Command();202 program.configureHelp({ helpWidth: 80 })203 .description(`Do fugiat eiusmod ipsum laboris excepteur pariatur sint ullamco tempor labore eu Do fugiat eiusmod ipsum laboris excepteur pariatur sint ullamco tempor labore eu204After line break Do fugiat eiusmod ipsum laboris excepteur pariatur sint ullamco tempor labore eu Do fugiat eiusmod ipsum laboris excepteur pariatur sint ullamco tempor labore eu`);205 const expectedOutput = `Usage: [options]206207Do fugiat eiusmod ipsum laboris excepteur pariatur sint ullamco tempor labore208eu Do fugiat eiusmod ipsum laboris excepteur pariatur sint ullamco tempor209labore eu210After line break Do fugiat eiusmod ipsum laboris excepteur pariatur sint211ullamco tempor labore eu Do fugiat eiusmod ipsum laboris excepteur pariatur212sint ullamco tempor labore eu213214Options:215 -h, --help display help for command216`;217 expect(program.helpInformation()).toBe(expectedOutput);218 });219});
added:tests/useColor.test.js+83 added
1const { useColor } = require('../lib/command.js');23describe('internal useColor environment variable support', () => {4 let holdNoColor = process.env.NO_COLOR;5 let holdForceColor = process.env.FORCE_COLOR;6 let holdCliColorForce = process.env.CLICOLOR_FORCE;78 beforeEach(() => {9 delete process.env.NO_COLOR;10 delete process.env.FORCE_COLOR;11 delete process.env.CLICOLOR_FORCE;12 });1314 afterAll(() => {15 if (holdNoColor === undefined) delete process.env.NO_COLOR;16 else process.env.NO_COLOR = holdNoColor;1718 if (holdForceColor === undefined) delete process.env.FORCE_COLOR;19 else process.env.FORCE_COLOR = holdForceColor;2021 if (holdCliColorForce === undefined) delete process.env.CLICOLOR_FORCE;22 else process.env.CLICOLOR_FORCE = holdCliColorForce;23 });2425 test('when no ENV defined then returns undefined', () => {26 expect(useColor()).toBeUndefined();27 });2829 // https://no-color.org30 //31 // Command-line software which adds ANSI color to its output by default should check for a NO_COLOR environment variable that,32 // when present and not an empty string (regardless of its value), prevents the addition of ANSI color.3334 test('when NO_COLOR defined then returns false', () => {35 process.env.NO_COLOR = 'non-empty';36 expect(useColor()).toBe(false);37 });3839 test('when NO_COLOR empty then returns undefined', () => {40 process.env.NO_COLOR = '';41 expect(useColor()).toBe(undefined);42 });4344 // https://bixense.com/clicolors/4546 test('when CLICOLOR_FORCE defined then returns true', () => {47 process.env.CLICOLOR_FORCE = '1';48 expect(useColor()).toBe(true);49 });5051 test('when CLICOLOR_FORCE empty then returns true', () => {52 // Follow original Apple usage and test for existence, don't ignore empty value.53 process.env.CLICOLOR_FORCE = '';54 expect(useColor()).toBe(true);55 });5657 test('when CLICOLOR_FORCE and NO_COLOR defined then returns false', () => {58 // NO_COLOR trumps CLICOLOR_FORCE59 process.env.NO_COLOR = '1';60 process.env.CLICOLOR_FORCE = '1';61 expect(useColor()).toBe(false);62 });6364 // chalk: https://github.com/chalk/supports-color/blob/c214314a14bcb174b12b3014b2b0a8de375029ae/index.js#L3365 // node: https://github.com/nodejs/node/blob/0a00217a5f67ef4a22384cfc80eb6dd9a917fdc1/lib/internal/tty.js#L10966 // (https://force-color.org recent web page from 2023, does not match major javascript implementations)67 //68 // Chalk ignores anything except for 0,1,2,3,4,true,false values.69 // Node somewhat follows Chalk with 0,1,2,3,true, but treats empty as true and unexpected values as false.70 // Test the expected Chalk values (which do produce same result in node).7172 test.each([73 ['true', true],74 ['false', false],75 ['0', false],76 ['1', true],77 ['2', true],78 ['3', true],79 ])('when FORCE_COLOR=%s then returns %s', (value, result) => {80 process.env.FORCE_COLOR = value;81 expect(useColor()).toBe(result);82 });83});
modified:typings/index.d.ts+66 added-8 removed
203 unmodified lines
204205export class Help {206 /** output helpWidth, long lines are wrapped to fit */207 helpWidth?: number;208 minWidthToWrap: number;209 sortSubcommands: boolean;210 sortOptions: boolean;211 showGlobalOptions: boolean;212213 constructor();214215 /*216 * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`217 * and just before calling `formatHelp()`.218 *219 * Commander just uses the helpWidth and the others are provided for subclasses.220 */221 prepareContext(contextOptions: {222 error?: boolean;223 helpWidth?: number;224 outputHasColors?: boolean;225 }): void;226227 /** Get the command term to show in the list of subcommands. */228 subcommandTerm(cmd: Command): string;229 /** Get the command summary to show in the list of subcommands. */230 subcommandDescription(cmd: Command): string;
27 unmodified lines
258 /** Get the longest global option term length. */259 longestGlobalOptionTermLength(cmd: Command, helper: Help): number;260 /** Get the longest argument term length. */261 longestArgumentTermLength(cmd: Command, helper: Help): number;262263 /** Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations. */264 displayWidth(str: string): number;265266 /** Style the titles. Called with 'Usage:', 'Options:', etc. */267 styleTitle(title: string): string;268269 /** Usage: <str> */270 styleUsage(str: string): string;271 /** Style for command name in usage string. */272 styleCommandText(str: string): string;273274 styleItemDescription(str: string): string;275 styleCommandDescription(str: string): string;276 /** Base style used by descriptions. */277 styleDescriptionText(str: string): string;278279 styleOptionTerm(str: string): string;280 styleSubcommandTerm(str: string): string;281 styleArgumentTerm(str: string): string;282283 /** Base style used in terms and usage for options. */284 styleOptionText(str: string): string;285 /** Base style used in terms and usage for subcommands. */286 styleSubcommandText(str: string): string;287 /** Base style used in terms and usage for arguments. */288 styleArgumentText(str: string): string;289290 /** Calculate the pad width from the maximum term length. */291 padWidth(cmd: Command, helper: Help): number;292293 /**253 * Wrap the given string to width characters per line, with lines after the first indented.254 * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.294 * Wrap a string at whitespace, preserving existing line breaks.295 * Wrapping is skipped if the width is less than `minWidthToWrap`.296 */256 wrap(257 str: string,258 width: number,259 indent: number,260 minColumnWidth?: number,297 boxWrap(str: string, width: number): string;298299 /** Detect manually wrapped and indented strings by checking for line break followed by whitespace. */300 preformatted(str: string): boolean;301302 /**303 * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.304 *305 * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:306 * TTT DDD DDDD307 * DD DDD308 */309 formatItem(310 term: string,311 termWidth: number,312 description: string,313 helper: Help,314 ): string;315316 /** Generate the built-in help text. */317 formatHelp(cmd: Command, helper: Help): string;
14 unmodified lines
332}333export interface OutputConfiguration {334 writeOut?(str: string): void;335 writeErr?(str: string): void;336 outputError?(str: string, write: (str: string) => void): void;337338 getOutHelpWidth?(): number;339 getErrHelpWidth?(): number;285 outputError?(str: string, write: (str: string) => void): void;340341 getOutHasColors?(): boolean;342 getErrHasColors?(): boolean;343 stripColor?(str: string): string;344}345346export type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';347export type HookEvent = 'preSubcommand' | 'preAction' | 'postAction';
680 unmodified lines
modified:typings/index.test-d.ts+34 added-3 removed
543 unmodified lines
544 },545 writeErr: (str: string) => {546 console.error(str);547 },548 getOutHelpWidth: () => 80,549 getErrHelpWidth: () => 80,548 outputError: (str: string, write: (str: string) => void) => {549 write(str);550 },551552 getOutHelpWidth: () => 80,553 getErrHelpWidth: () => 80,554555 getOutHasColors: () => true,556 getErrHasColors: () => true,557 stripColor: (str) => str,558 }),559);560561// Help
1 unmodified line
563const helperCommand = new commander.Command();564const helperOption = new commander.Option('-a, --all');565const helperArgument = new commander.Argument('<file>');566567helper.prepareContext({});568helper.prepareContext({ helpWidth: 120, error: true, outputHasColors: false });569570expectType<number | undefined>(helper.helpWidth);571expectType<number>(helper.minWidthToWrap);572expectType<boolean>(helper.sortSubcommands);573expectType<boolean>(helper.sortOptions);574expectType<boolean>(helper.showGlobalOptions);575
16 unmodified lines
592expectType<number>(helper.longestGlobalOptionTermLength(helperCommand, helper));593expectType<number>(helper.longestArgumentTermLength(helperCommand, helper));594expectType<number>(helper.padWidth(helperCommand, helper));595587expectType<string>(helper.wrap('a b c', 50, 3));596expectType<number>(helper.displayWidth('some string'));597expectType<string>(helper.boxWrap('a b c', 50));598expectType<string>(599 helper.formatItem('--example', 12, 'example description', helper),600);601expectType<boolean>(helper.preformatted('a\nb c'));602603expectType<string>(helper.styleTitle('Usage:'));604605expectType<string>(helper.styleUsage('foo [options] <file>'));606expectType<string>(helper.styleCommandText('foo'));607608expectType<string>(helper.styleItemDescription('description'));609expectType<string>(helper.styleCommandDescription('description'));610expectType<string>(helper.styleDescriptionText('description'));611612expectType<string>(helper.styleOptionTerm('-a, --all'));613expectType<string>(helper.styleSubcommandTerm('bar [options]'));614expectType<string>(helper.styleArgumentTerm('<file>'));615616expectType<string>(helper.styleOptionText('-a, --all'));617expectType<string>(helper.styleSubcommandText('bar'));618expectType<string>(helper.styleArgumentText('<file>'));619620expectType<string>(helper.formatHelp(helperCommand, helper));621622// Option properties623const baseOption = new commander.Option('-f,--foo', 'foo description');
113 unmodified lines
modified:Readme.md+12 added
924 unmodified lines
925926The data properties are:927928- `helpWidth`: specify the wrap width, useful for unit tests929- `minWidthToWrap`: specify required width to allow wrapping (default 40)930- `sortSubcommands`: sort the subcommands alphabetically931- `sortOptions`: sort the options alphabetically932- `showGlobalOptions`: show a section with the global options from the parent command(s)933
7 unmodified lines
941 subcommandTerm: (cmd) => cmd.name() // Just show the name, instead of short usage.942});943```944945There are _style_ methods to add color to the help, like `styleTitle` and `styleOptionText`. There is built-in support for respecting946environment variables for `NO_COLOR`, `FORCE_COLOR`, and `CLIFORCE_COLOR`.947948Example file: [color-help.mjs](./examples/color-help.mjs)949950Other help configuration examples:951- [color-help-replacement.mjs](./examples/color-help-replacement.mjs)952- [help-centered.mjs](./examples/help-centered.mjs)953- [help-subcommands-usage.js](./examples/help-subcommands-usage.js)954- [man-style-help.mjs](./examples/man-style-help.mjs)955956## Custom event listeners957958You can execute custom actions by listening to command and option events.959
210 unmodified lines