code
stringlengths
28
313k
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
74
language
stringclasses
1 value
repo
stringlengths
5
60
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
saveStateBeforeParse() { this._savedState = { // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing _name: this._name, // option values before parse have default values (including false for negated options) // shallow clones _optionValues: { ...this._optionValues }, _optionValueSources: { ...this._optionValueSources }, }; }
Called the first time parse is called to save state and allow a restore before subsequent calls to parse. Not usually called directly, but available for subclasses to save their custom state. This is called in a lazy way. Only commands used in parsing chain will have state saved.
saveStateBeforeParse
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
restoreStateBeforeParse() { if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true. - either make a new Command for each call to parse, or stop storing options as properties`); // clear state from _prepareUserArgs this._name = this._savedState._name; this._scriptPath = null; this.rawArgs = []; // clear state from setOptionValueWithSource this._optionValues = { ...this._savedState._optionValues }; this._optionValueSources = { ...this._savedState._optionValueSources }; // clear state from _parseCommand this.args = []; // clear state from _processArguments this.processedArgs = []; }
Restore state before parse for calls after the first. Not usually called directly, but available for subclasses to save their custom state. This is called in a lazy way. Only commands used in parsing chain will have state restored.
restoreStateBeforeParse
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_checkForMissingExecutable(executableFile, executableDir, subcommandName) { if (fs.existsSync(executableFile)) return; const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory'; const executableMissing = `'${executableFile}' does not exist - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead - if the default executable name is not suitable, use the executableFile option to supply a custom name or path - ${executableDirMessage}`; throw new Error(executableMissing); }
Throw if expected executable is missing. Add lots of help for author. @param {string} executableFile @param {string} executableDir @param {string} subcommandName
_checkForMissingExecutable
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_dispatchHelpCommand(subcommandName) { if (!subcommandName) { this.help(); } const subCommand = this._findCommand(subcommandName); if (subCommand && !subCommand._executableHandler) { subCommand.help(); } // Fallback to parsing the help flag to invoke the help. return this._dispatchSubcommand( subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'], ); }
Invoke help directly if possible, or dispatch if necessary. e.g. help foo @private
_dispatchHelpCommand
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_checkNumberOfArguments() { // too few this.registeredArguments.forEach((arg, i) => { if (arg.required && this.args[i] == null) { this.missingArgument(arg.name()); } }); // too many if ( this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic ) { return; } if (this.args.length > this.registeredArguments.length) { this._excessArguments(this.args); } }
Check this.args against expected this.registeredArguments. @private
_checkNumberOfArguments
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_processArguments() { const myParseArg = (argument, value, previous) => { // Extra processing for nice error message on parsing failure. let parsedValue = value; if (value !== null && argument.parseArg) { const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`; parsedValue = this._callParseArg( argument, value, previous, invalidValueMessage, ); } return parsedValue; }; this._checkNumberOfArguments(); const processedArgs = []; this.registeredArguments.forEach((declaredArg, index) => { let value = declaredArg.defaultValue; if (declaredArg.variadic) { // Collect together remaining arguments for passing together as an array. if (index < this.args.length) { value = this.args.slice(index); if (declaredArg.parseArg) { value = value.reduce((processed, v) => { return myParseArg(declaredArg, v, processed); }, declaredArg.defaultValue); } } else if (value === undefined) { value = []; } } else if (index < this.args.length) { value = this.args[index]; if (declaredArg.parseArg) { value = myParseArg(declaredArg, value, declaredArg.defaultValue); } } processedArgs[index] = value; }); this.processedArgs = processedArgs; }
Process this.args using this.registeredArguments and save as this.processedArgs! @private
_processArguments
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_chainOrCall(promise, fn) { // thenable if (promise && promise.then && typeof promise.then === 'function') { // already have a promise, chain callback return promise.then(() => fn()); } // callback might return a promise return fn(); }
Once we have a promise we chain, but call synchronously until then. @param {(Promise|undefined)} promise @param {Function} fn @return {(Promise|undefined)} @private
_chainOrCall
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_chainOrCallHooks(promise, event) { let result = promise; const hooks = []; this._getCommandAndAncestors() .reverse() .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined) .forEach((hookedCommand) => { hookedCommand._lifeCycleHooks[event].forEach((callback) => { hooks.push({ hookedCommand, callback }); }); }); if (event === 'postAction') { hooks.reverse(); } hooks.forEach((hookDetail) => { result = this._chainOrCall(result, () => { return hookDetail.callback(hookDetail.hookedCommand, this); }); }); return result; }
@param {(Promise|undefined)} promise @param {string} event @return {(Promise|undefined)} @private
_chainOrCallHooks
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_chainOrCallSubCommandHook(promise, subCommand, event) { let result = promise; if (this._lifeCycleHooks[event] !== undefined) { this._lifeCycleHooks[event].forEach((hook) => { result = this._chainOrCall(result, () => { return hook(this, subCommand); }); }); } return result; }
@param {(Promise|undefined)} promise @param {Command} subCommand @param {string} event @return {(Promise|undefined)} @private
_chainOrCallSubCommandHook
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_parseCommand(operands, unknown) { const parsed = this.parseOptions(unknown); this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env this._parseOptionsImplied(); operands = operands.concat(parsed.operands); unknown = parsed.unknown; this.args = operands.concat(unknown); if (operands && this._findCommand(operands[0])) { return this._dispatchSubcommand(operands[0], operands.slice(1), unknown); } if ( this._getHelpCommand() && operands[0] === this._getHelpCommand().name() ) { return this._dispatchHelpCommand(operands[1]); } if (this._defaultCommandName) { this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command return this._dispatchSubcommand( this._defaultCommandName, operands, unknown, ); } if ( this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName ) { // probably missing subcommand and no handler, user needs help (and exit) this.help({ error: true }); } this._outputHelpIfRequested(parsed.unknown); this._checkForMissingMandatoryOptions(); this._checkForConflictingOptions(); // We do not always call this check to avoid masking a "better" error, like unknown command. const checkForUnknownOptions = () => { if (parsed.unknown.length > 0) { this.unknownOption(parsed.unknown[0]); } }; const commandEvent = `command:${this.name()}`; if (this._actionHandler) { checkForUnknownOptions(); this._processArguments(); let promiseChain; promiseChain = this._chainOrCallHooks(promiseChain, 'preAction'); promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs), ); if (this.parent) { promiseChain = this._chainOrCall(promiseChain, () => { this.parent.emit(commandEvent, operands, unknown); // legacy }); } promiseChain = this._chainOrCallHooks(promiseChain, 'postAction'); return promiseChain; } if (this.parent && this.parent.listenerCount(commandEvent)) { checkForUnknownOptions(); this._processArguments(); this.parent.emit(commandEvent, operands, unknown); // legacy } else if (operands.length) { if (this._findCommand('*')) { // legacy default command return this._dispatchSubcommand('*', operands, unknown); } if (this.listenerCount('command:*')) { // skip option check, emit event for possible misspelling suggestion this.emit('command:*', operands, unknown); } else if (this.commands.length) { this.unknownCommand(); } else { checkForUnknownOptions(); this._processArguments(); } } else if (this.commands.length) { checkForUnknownOptions(); // This command has subcommands and nothing hooked up at this level, so display help (and exit). this.help({ error: true }); } else { checkForUnknownOptions(); this._processArguments(); // fall through for caller to handle after calling .parse() } }
Process arguments in context of this command. Returns action result, in case it is a promise. @private
_parseCommand
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_findCommand(name) { if (!name) return undefined; return this.commands.find( (cmd) => cmd._name === name || cmd._aliases.includes(name), ); }
Find matching command. @private @return {Command | undefined}
_findCommand
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_findOption(arg) { return this.options.find((option) => option.is(arg)); }
Return an option matching `arg` if any. @param {string} arg @return {Option} @package
_findOption
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_checkForMissingMandatoryOptions() { // Walk up hierarchy so can call in subcommand after checking for displaying help. this._getCommandAndAncestors().forEach((cmd) => { cmd.options.forEach((anOption) => { if ( anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined ) { cmd.missingMandatoryOptionValue(anOption); } }); }); }
Display an error message if a mandatory option does not have a value. Called after checking for help flags in leaf subcommand. @private
_checkForMissingMandatoryOptions
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_checkForConflictingLocalOptions() { const definedNonDefaultOptions = this.options.filter((option) => { const optionKey = option.attributeName(); if (this.getOptionValue(optionKey) === undefined) { return false; } return this.getOptionValueSource(optionKey) !== 'default'; }); const optionsWithConflicting = definedNonDefaultOptions.filter( (option) => option.conflictsWith.length > 0, ); optionsWithConflicting.forEach((option) => { const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()), ); if (conflictingAndDefined) { this._conflictingOption(option, conflictingAndDefined); } }); }
Display an error message if conflicting options are used together in this. @private
_checkForConflictingLocalOptions
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_checkForConflictingOptions() { // Walk up hierarchy so can call in subcommand after checking for displaying help. this._getCommandAndAncestors().forEach((cmd) => { cmd._checkForConflictingLocalOptions(); }); }
Display an error message if conflicting options are used together. Called after checking for help flags in leaf subcommand. @private
_checkForConflictingOptions
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
parseOptions(argv) { const operands = []; // operands, not options or values const unknown = []; // first unknown option and remaining unknown args let dest = operands; const args = argv.slice(); function maybeOption(arg) { return arg.length > 1 && arg[0] === '-'; } const negativeNumberArg = (arg) => { // return false if not a negative number if (!/^-\d*\.?\d+(e[+-]?\d+)?$/.test(arg)) return false; // negative number is ok unless digit used as an option in command hierarchy return !this._getCommandAndAncestors().some((cmd) => cmd.options .map((opt) => opt.short) .some((short) => /^-\d$/.test(short)), ); }; // parse options let activeVariadicOption = null; while (args.length) { const arg = args.shift(); // literal if (arg === '--') { if (dest === unknown) dest.push(arg); dest.push(...args); break; } if ( activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg)) ) { this.emit(`option:${activeVariadicOption.name()}`, arg); continue; } activeVariadicOption = null; if (maybeOption(arg)) { const option = this._findOption(arg); // recognised option, call listener to assign value with possible custom processing if (option) { if (option.required) { const value = args.shift(); if (value === undefined) this.optionMissingArgument(option); this.emit(`option:${option.name()}`, value); } else if (option.optional) { let value = null; // historical behaviour is optional value is following arg unless an option if ( args.length > 0 && (!maybeOption(args[0]) || negativeNumberArg(args[0])) ) { value = args.shift(); } this.emit(`option:${option.name()}`, value); } else { // boolean flag this.emit(`option:${option.name()}`); } activeVariadicOption = option.variadic ? option : null; continue; } } // Look for combo options following single dash, eat first one if known. if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') { const option = this._findOption(`-${arg[1]}`); if (option) { if ( option.required || (option.optional && this._combineFlagAndOptionalValue) ) { // option with value following in same argument this.emit(`option:${option.name()}`, arg.slice(2)); } else { // boolean option, emit and put back remainder of arg for further processing this.emit(`option:${option.name()}`); args.unshift(`-${arg.slice(2)}`); } continue; } } // Look for known long flag with value, like --foo=bar if (/^--[^=]+=/.test(arg)) { const index = arg.indexOf('='); const option = this._findOption(arg.slice(0, index)); if (option && (option.required || option.optional)) { this.emit(`option:${option.name()}`, arg.slice(index + 1)); continue; } } // Not a recognised option by this command. // Might be a command-argument, or subcommand option, or unknown option, or help command or option. // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands. // A negative number in a leaf command is not an unknown option. if ( dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg)) ) { dest = unknown; } // If using positionalOptions, stop processing our options at subcommand. if ( (this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0 ) { if (this._findCommand(arg)) { operands.push(arg); if (args.length > 0) unknown.push(...args); break; } else if ( this._getHelpCommand() && arg === this._getHelpCommand().name() ) { operands.push(arg); if (args.length > 0) operands.push(...args); break; } else if (this._defaultCommandName) { unknown.push(arg); if (args.length > 0) unknown.push(...args); break; } } // If using passThroughOptions, stop processing options at first command-argument. if (this._passThroughOptions) { dest.push(arg); if (args.length > 0) dest.push(...args); break; } // add arg dest.push(arg); } return { operands, unknown }; }
Parse options from `argv` removing known options, and return argv split into operands and unknown arguments. Side effects: modifies command by storing options. Does not reset state if called again. Examples: argv => operands, unknown --known kkk op => [op], [] op --known kkk => [op], [] sub --unknown uuu op => [sub], [--unknown uuu op] sub -- --unknown uuu op => [sub --unknown uuu op], [] @param {string[]} argv @return {{operands: string[], unknown: string[]}}
parseOptions
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
opts() { if (this._storeOptionsAsProperties) { // Preserve original behaviour so backwards compatible when still using properties const result = {}; const len = this.options.length; for (let i = 0; i < len; i++) { const key = this.options[i].attributeName(); result[key] = key === this._versionOptionName ? this._version : this[key]; } return result; } return this._optionValues; }
Return an object containing local option values as key-value pairs. @return {object}
opts
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
optsWithGlobals() { // globals overwrite locals return this._getCommandAndAncestors().reduce( (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {}, ); }
Return an object containing merged local and global option values as key-value pairs. @return {object}
optsWithGlobals
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
error(message, errorOptions) { // output handling this._outputConfiguration.outputError( `${message}\n`, this._outputConfiguration.writeErr, ); if (typeof this._showHelpAfterError === 'string') { this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`); } else if (this._showHelpAfterError) { this._outputConfiguration.writeErr('\n'); this.outputHelp({ error: true }); } // exit handling const config = errorOptions || {}; const exitCode = config.exitCode || 1; const code = config.code || 'commander.error'; this._exit(exitCode, code, message); }
Display error message and exit (or call exitOverride). @param {string} message @param {object} [errorOptions] @param {string} [errorOptions.code] - an id string representing the error @param {number} [errorOptions.exitCode] - used with process.exit
error
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_parseOptionsEnv() { this.options.forEach((option) => { if (option.envVar && option.envVar in process.env) { const optionKey = option.attributeName(); // Priority check. Do not overwrite cli or options from unknown source (client-code). if ( this.getOptionValue(optionKey) === undefined || ['default', 'config', 'env'].includes( this.getOptionValueSource(optionKey), ) ) { if (option.required || option.optional) { // option can take a value // keep very simple, optional always takes value this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]); } else { // boolean // keep very simple, only care that envVar defined and not the value this.emit(`optionEnv:${option.name()}`); } } } }); }
Apply any option related environment variables, if option does not have a value from cli or client code. @private
_parseOptionsEnv
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_parseOptionsImplied() { const dualHelper = new DualOptions(this.options); const hasCustomOptionValue = (optionKey) => { return ( this.getOptionValue(optionKey) !== undefined && !['default', 'implied'].includes(this.getOptionValueSource(optionKey)) ); }; this.options .filter( (option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption( this.getOptionValue(option.attributeName()), option, ), ) .forEach((option) => { Object.keys(option.implied) .filter((impliedKey) => !hasCustomOptionValue(impliedKey)) .forEach((impliedKey) => { this.setOptionValueWithSource( impliedKey, option.implied[impliedKey], 'implied', ); }); }); }
Apply any implied option values, if option is undefined or default value. @private
_parseOptionsImplied
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
missingArgument(name) { const message = `error: missing required argument '${name}'`; this.error(message, { code: 'commander.missingArgument' }); }
Argument `name` is missing. @param {string} name @private
missingArgument
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
optionMissingArgument(option) { const message = `error: option '${option.flags}' argument missing`; this.error(message, { code: 'commander.optionMissingArgument' }); }
`Option` is missing an argument. @param {Option} option @private
optionMissingArgument
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
missingMandatoryOptionValue(option) { const message = `error: required option '${option.flags}' not specified`; this.error(message, { code: 'commander.missingMandatoryOptionValue' }); }
`Option` does not have a value, and is a mandatory option. @param {Option} option @private
missingMandatoryOptionValue
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_conflictingOption(option, conflictingOption) { // The calling code does not know whether a negated option is the source of the // value, so do some work to take an educated guess. const findBestOptionFromValue = (option) => { const optionKey = option.attributeName(); const optionValue = this.getOptionValue(optionKey); const negativeOption = this.options.find( (target) => target.negate && optionKey === target.attributeName(), ); const positiveOption = this.options.find( (target) => !target.negate && optionKey === target.attributeName(), ); if ( negativeOption && ((negativeOption.presetArg === undefined && optionValue === false) || (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) ) { return negativeOption; } return positiveOption || option; }; const getErrorMessage = (option) => { const bestOption = findBestOptionFromValue(option); const optionKey = bestOption.attributeName(); const source = this.getOptionValueSource(optionKey); if (source === 'env') { return `environment variable '${bestOption.envVar}'`; } return `option '${bestOption.flags}'`; }; const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`; this.error(message, { code: 'commander.conflictingOption' }); }
`Option` conflicts with another option. @param {Option} option @param {Option} conflictingOption @private
_conflictingOption
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
unknownOption(flag) { if (this._allowUnknownOption) return; let suggestion = ''; if (flag.startsWith('--') && this._showSuggestionAfterError) { // Looping to pick up the global options too let candidateFlags = []; // eslint-disable-next-line @typescript-eslint/no-this-alias let command = this; do { const moreFlags = command .createHelp() .visibleOptions(command) .filter((option) => option.long) .map((option) => option.long); candidateFlags = candidateFlags.concat(moreFlags); command = command.parent; } while (command && !command._enablePositionalOptions); suggestion = suggestSimilar(flag, candidateFlags); } const message = `error: unknown option '${flag}'${suggestion}`; this.error(message, { code: 'commander.unknownOption' }); }
Unknown option `flag`. @param {string} flag @private
unknownOption
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_excessArguments(receivedArgs) { if (this._allowExcessArguments) return; const expected = this.registeredArguments.length; const s = expected === 1 ? '' : 's'; const forSubcommand = this.parent ? ` for '${this.name()}'` : ''; const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`; this.error(message, { code: 'commander.excessArguments' }); }
Excess arguments, more than expected. @param {string[]} receivedArgs @private
_excessArguments
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
version(str, flags, description) { if (str === undefined) return this._version; this._version = str; flags = flags || '-V, --version'; description = description || 'output the version number'; const versionOption = this.createOption(flags, description); this._versionOptionName = versionOption.attributeName(); this._registerOption(versionOption); this.on('option:' + versionOption.name(), () => { this._outputConfiguration.writeOut(`${str}\n`); this._exit(0, 'commander.version', str); }); return this; }
Get or set the program version. This method auto-registers the "-V, --version" option which will print the version number. You can optionally supply the flags and description to override the defaults. @param {string} [str] @param {string} [flags] @param {string} [description] @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
version
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
description(str, argsDescription) { if (str === undefined && argsDescription === undefined) return this._description; this._description = str; if (argsDescription) { this._argsDescription = argsDescription; } return this; }
Set the description. @param {string} [str] @param {object} [argsDescription] @return {(string|Command)}
description
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
summary(str) { if (str === undefined) return this._summary; this._summary = str; return this; }
Set the summary. Used when listed as subcommand of parent. @param {string} [str] @return {(string|Command)}
summary
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
alias(alias) { if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility /** @type {Command} */ // eslint-disable-next-line @typescript-eslint/no-this-alias let command = this; if ( this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler ) { // assume adding alias for last added executable subcommand, rather than this command = this.commands[this.commands.length - 1]; } if (alias === command._name) throw new Error("Command alias can't be the same as its name"); const matchingCommand = this.parent?._findCommand(alias); if (matchingCommand) { // c.f. _registerCommand const existingCmd = [matchingCommand.name()] .concat(matchingCommand.aliases()) .join('|'); throw new Error( `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`, ); } command._aliases.push(alias); return this; }
Set an alias for the command. You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help. @param {string} [alias] @return {(string|Command)}
alias
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
aliases(aliases) { // Getter for the array of aliases is the main reason for having aliases() in addition to alias(). if (aliases === undefined) return this._aliases; aliases.forEach((alias) => this.alias(alias)); return this; }
Set aliases for the command. Only the first alias is shown in the auto-generated help. @param {string[]} [aliases] @return {(string[]|Command)}
aliases
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
usage(str) { if (str === undefined) { if (this._usage) return this._usage; const args = this.registeredArguments.map((arg) => { return humanReadableArgName(arg); }); return [] .concat( this.options.length || this._helpOption !== null ? '[options]' : [], this.commands.length ? '[command]' : [], this.registeredArguments.length ? args : [], ) .join(' '); } this._usage = str; return this; }
Set / get the command usage `str`. @param {string} [str] @return {(string|Command)}
usage
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
name(str) { if (str === undefined) return this._name; this._name = str; return this; }
Get or set the name of the command. @param {string} [str] @return {(string|Command)}
name
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
helpGroup(heading) { if (heading === undefined) return this._helpGroupHeading ?? ''; this._helpGroupHeading = heading; return this; }
Set/get the help group heading for this subcommand in parent command's help. @param {string} [heading] @return {Command | string}
helpGroup
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
commandsGroup(heading) { if (heading === undefined) return this._defaultCommandGroup ?? ''; this._defaultCommandGroup = heading; return this; }
Set/get the default help group heading for subcommands added to this command. (This does not override a group set directly on the subcommand using .helpGroup().) @example program.commandsGroup('Development Commands:); program.command('watch')... program.command('lint')... ... @param {string} [heading] @returns {Command | string}
commandsGroup
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
optionsGroup(heading) { if (heading === undefined) return this._defaultOptionGroup ?? ''; this._defaultOptionGroup = heading; return this; }
Set/get the default help group heading for options added to this command. (This does not override a group set directly on the option using .helpGroup().) @example program .optionsGroup('Development Options:') .option('-d, --debug', 'output extra debugging') .option('-p, --profile', 'output profiling information') @param {string} [heading] @returns {Command | string}
optionsGroup
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
nameFromFilename(filename) { this._name = path.basename(filename, path.extname(filename)); return this; }
Set the name of the command from script filename, such as process.argv[1], or require.main.filename, or __filename. (Used internally and public although not documented in README.) @example program.nameFromFilename(require.main.filename); @param {string} filename @return {Command}
nameFromFilename
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
executableDir(path) { if (path === undefined) return this._executableDir; this._executableDir = path; return this; }
Get or set the directory for searching for executable subcommands of this command. @example program.executableDir(__dirname); // or program.executableDir('subcommands'); @param {string} [path] @return {(string|null|Command)}
executableDir
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
helpInformation(contextOptions) { const helper = this.createHelp(); const context = this._getOutputContext(contextOptions); helper.prepareContext({ error: context.error, helpWidth: context.helpWidth, outputHasColors: context.hasColors, }); const text = helper.formatHelp(this, helper); if (context.hasColors) return text; return this._outputConfiguration.stripColor(text); }
Return program help documentation. @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout @return {string}
helpInformation
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_getOutputContext(contextOptions) { contextOptions = contextOptions || {}; const error = !!contextOptions.error; let baseWrite; let hasColors; let helpWidth; if (error) { baseWrite = (str) => this._outputConfiguration.writeErr(str); hasColors = this._outputConfiguration.getErrHasColors(); helpWidth = this._outputConfiguration.getErrHelpWidth(); } else { baseWrite = (str) => this._outputConfiguration.writeOut(str); hasColors = this._outputConfiguration.getOutHasColors(); helpWidth = this._outputConfiguration.getOutHelpWidth(); } const write = (str) => { if (!hasColors) str = this._outputConfiguration.stripColor(str); return baseWrite(str); }; return { error, write, hasColors, helpWidth }; }
@typedef HelpContext @type {object} @property {boolean} error @property {number} helpWidth @property {boolean} hasColors @property {function} write - includes stripColor if needed @returns {HelpContext} @private
_getOutputContext
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
outputHelp(contextOptions) { let deprecatedCallback; if (typeof contextOptions === 'function') { deprecatedCallback = contextOptions; contextOptions = undefined; } const outputContext = this._getOutputContext(contextOptions); /** @type {HelpTextEventContext} */ const eventContext = { error: outputContext.error, write: outputContext.write, command: this, }; this._getCommandAndAncestors() .reverse() .forEach((command) => command.emit('beforeAllHelp', eventContext)); this.emit('beforeHelp', eventContext); let helpInformation = this.helpInformation({ error: outputContext.error }); if (deprecatedCallback) { helpInformation = deprecatedCallback(helpInformation); if ( typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation) ) { throw new Error('outputHelp callback must return a string or a Buffer'); } } outputContext.write(helpInformation); if (this._getHelpOption()?.long) { this.emit(this._getHelpOption().long); // deprecated } this.emit('afterHelp', eventContext); this._getCommandAndAncestors().forEach((command) => command.emit('afterAllHelp', eventContext), ); }
Output help information for this command. Outputs built-in help, and custom text added using `.addHelpText()`. @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
outputHelp
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
helpOption(flags, description) { // Support enabling/disabling built-in help option. if (typeof flags === 'boolean') { if (flags) { if (this._helpOption === null) this._helpOption = undefined; // reenable if (this._defaultOptionGroup) { // make the option to store the group this._initOptionGroup(this._getHelpOption()); } } else { this._helpOption = null; // disable } return this; } // Customise flags and description. this._helpOption = this.createOption( flags ?? '-h, --help', description ?? 'display help for command', ); // init group unless lazy create if (flags || description) this._initOptionGroup(this._helpOption); return this; }
You can pass in flags and a description to customise the built-in help option. Pass in false to disable the built-in help option. @example program.helpOption('-?, --help' 'show help'); // customise program.helpOption(false); // disable @param {(string | boolean)} flags @param {string} [description] @return {Command} `this` command for chaining
helpOption
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_getHelpOption() { // Lazy create help option on demand. if (this._helpOption === undefined) { this.helpOption(undefined, undefined); } return this._helpOption; }
Lazy create help option. Returns null if has been disabled with .helpOption(false). @returns {(Option | null)} the help option @package
_getHelpOption
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
addHelpOption(option) { this._helpOption = option; this._initOptionGroup(option); return this; }
Supply your own option to use for the built-in help option. This is an alternative to using helpOption() to customise the flags and description etc. @param {Option} option @return {Command} `this` command for chaining
addHelpOption
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
help(contextOptions) { this.outputHelp(contextOptions); let exitCode = Number(process.exitCode ?? 0); // process.exitCode does allow a string or an integer, but we prefer just a number if ( exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error ) { exitCode = 1; } // message: do not have all displayed text available so only passing placeholder. this._exit(exitCode, 'commander.help', '(outputHelp)'); }
Output help information and exit. Outputs built-in help, and custom text added using `.addHelpText()`. @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
help
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
addHelpText(position, text) { const allowedValues = ['beforeAll', 'before', 'after', 'afterAll']; if (!allowedValues.includes(position)) { throw new Error(`Unexpected value for position to addHelpText. Expecting one of '${allowedValues.join("', '")}'`); } const helpEvent = `${position}Help`; this.on(helpEvent, (/** @type {HelpTextEventContext} */ context) => { let helpStr; if (typeof text === 'function') { helpStr = text({ error: context.error, command: context.command }); } else { helpStr = text; } // Ignore falsy value when nothing to output. if (helpStr) { context.write(`${helpStr}\n`); } }); return this; }
Add additional text to be displayed with the built-in help. Position is 'before' or 'after' to affect just this command, and 'beforeAll' or 'afterAll' to affect this command and all its subcommands. @param {string} position - before or after built-in help @param {(string | Function)} text - string to add, or a function returning a string @return {Command} `this` command for chaining
addHelpText
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_outputHelpIfRequested(args) { const helpOption = this._getHelpOption(); const helpRequested = helpOption && args.find((arg) => helpOption.is(arg)); if (helpRequested) { this.outputHelp(); // (Do not have all displayed text available so only passing placeholder.) this._exit(0, 'commander.helpDisplayed', '(outputHelp)'); } }
Output help information if help flags specified @param {Array} args - array of options to search for help flags @private
_outputHelpIfRequested
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
function incrementNodeInspectorPort(args) { // Testing for these options: // --inspect[=[host:]port] // --inspect-brk[=[host:]port] // --inspect-port=[host:]port return args.map((arg) => { if (!arg.startsWith('--inspect')) { return arg; } let debugOption; let debugHost = '127.0.0.1'; let debugPort = '9229'; let match; if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) { // e.g. --inspect debugOption = match[1]; } else if ( (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null ) { debugOption = match[1]; if (/^\d+$/.test(match[3])) { // e.g. --inspect=1234 debugPort = match[3]; } else { // e.g. --inspect=localhost debugHost = match[3]; } } else if ( (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null ) { // e.g. --inspect=localhost:1234 debugOption = match[1]; debugHost = match[3]; debugPort = match[4]; } if (debugOption && debugPort !== '0') { return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; } return arg; }); }
Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command). @param {string[]} args - array of arguments from node.execArgv @returns {string[]} @private
incrementNodeInspectorPort
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
constructor(exitCode, code, message) { super(message); // properly capture stack trace in Node.js Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.code = code; this.exitCode = exitCode; this.nestedError = undefined; }
Constructs the CommanderError class @param {number} exitCode suggested exit code which could be used with process.exit @param {string} code an id string representing the error @param {string} message human-readable description of the error
constructor
javascript
tj/commander.js
lib/error.js
https://github.com/tj/commander.js/blob/master/lib/error.js
MIT
constructor(message) { super(1, 'commander.invalidArgument', message); // properly capture stack trace in Node.js Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; }
Constructs the InvalidArgumentError class @param {string} [message] explanation of why argument is invalid
constructor
javascript
tj/commander.js
lib/error.js
https://github.com/tj/commander.js/blob/master/lib/error.js
MIT
constructor() { this.helpWidth = undefined; this.minWidthToWrap = 40; this.sortSubcommands = false; this.sortOptions = false; this.showGlobalOptions = false; }
TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS` https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types @typedef { import("./argument.js").Argument } Argument @typedef { import("./command.js").Command } Command @typedef { import("./option.js").Option } Option
constructor
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
prepareContext(contextOptions) { this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80; }
prepareContext is called by Commander after applying overrides from `Command.configureHelp()` and just before calling `formatHelp()`. Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses. @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
prepareContext
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
visibleCommands(cmd) { const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden); const helpCommand = cmd._getHelpCommand(); if (helpCommand && !helpCommand._hidden) { visibleCommands.push(helpCommand); } if (this.sortSubcommands) { visibleCommands.sort((a, b) => { // @ts-ignore: because overloaded return type return a.name().localeCompare(b.name()); }); } return visibleCommands; }
Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. @param {Command} cmd @returns {Command[]}
visibleCommands
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
compareOptions(a, b) { const getSortKey = (option) => { // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated. return option.short ? option.short.replace(/^-/, '') : option.long.replace(/^--/, ''); }; return getSortKey(a).localeCompare(getSortKey(b)); }
Compare options for sort. @param {Option} a @param {Option} b @returns {number}
compareOptions
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
visibleOptions(cmd) { const visibleOptions = cmd.options.filter((option) => !option.hidden); // Built-in help option. const helpOption = cmd._getHelpOption(); if (helpOption && !helpOption.hidden) { // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs. const removeShort = helpOption.short && cmd._findOption(helpOption.short); const removeLong = helpOption.long && cmd._findOption(helpOption.long); if (!removeShort && !removeLong) { visibleOptions.push(helpOption); // no changes needed } else if (helpOption.long && !removeLong) { visibleOptions.push( cmd.createOption(helpOption.long, helpOption.description), ); } else if (helpOption.short && !removeShort) { visibleOptions.push( cmd.createOption(helpOption.short, helpOption.description), ); } } if (this.sortOptions) { visibleOptions.sort(this.compareOptions); } return visibleOptions; }
Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. @param {Command} cmd @returns {Option[]}
visibleOptions
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
visibleGlobalOptions(cmd) { if (!this.showGlobalOptions) return []; const globalOptions = []; for ( let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent ) { const visibleOptions = ancestorCmd.options.filter( (option) => !option.hidden, ); globalOptions.push(...visibleOptions); } if (this.sortOptions) { globalOptions.sort(this.compareOptions); } return globalOptions; }
Get an array of the visible global options. (Not including help.) @param {Command} cmd @returns {Option[]}
visibleGlobalOptions
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
visibleArguments(cmd) { // Side effect! Apply the legacy descriptions before the arguments are displayed. if (cmd._argsDescription) { cmd.registeredArguments.forEach((argument) => { argument.description = argument.description || cmd._argsDescription[argument.name()] || ''; }); } // If there are any arguments with a description then return all the arguments. if (cmd.registeredArguments.find((argument) => argument.description)) { return cmd.registeredArguments; } return []; }
Get an array of the arguments if any have a description. @param {Command} cmd @returns {Argument[]}
visibleArguments
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
subcommandTerm(cmd) { // Legacy. Ignores custom usage string, and nested commands. const args = cmd.registeredArguments .map((arg) => humanReadableArgName(arg)) .join(' '); return ( cmd._name + (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') + (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option (args ? ' ' + args : '') ); }
Get the command term to show in the list of subcommands. @param {Command} cmd @returns {string}
subcommandTerm
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
optionTerm(option) { return option.flags; }
Get the option term to show in the list of options. @param {Option} option @returns {string}
optionTerm
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
argumentTerm(argument) { return argument.name(); }
Get the argument term to show in the list of arguments. @param {Argument} argument @returns {string}
argumentTerm
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
longestSubcommandTermLength(cmd, helper) { return helper.visibleCommands(cmd).reduce((max, command) => { return Math.max( max, this.displayWidth( helper.styleSubcommandTerm(helper.subcommandTerm(command)), ), ); }, 0); }
Get the longest command term length. @param {Command} cmd @param {Help} helper @returns {number}
longestSubcommandTermLength
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
longestOptionTermLength(cmd, helper) { return helper.visibleOptions(cmd).reduce((max, option) => { return Math.max( max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))), ); }, 0); }
Get the longest option term length. @param {Command} cmd @param {Help} helper @returns {number}
longestOptionTermLength
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
longestGlobalOptionTermLength(cmd, helper) { return helper.visibleGlobalOptions(cmd).reduce((max, option) => { return Math.max( max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))), ); }, 0); }
Get the longest global option term length. @param {Command} cmd @param {Help} helper @returns {number}
longestGlobalOptionTermLength
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
longestArgumentTermLength(cmd, helper) { return helper.visibleArguments(cmd).reduce((max, argument) => { return Math.max( max, this.displayWidth( helper.styleArgumentTerm(helper.argumentTerm(argument)), ), ); }, 0); }
Get the longest argument term length. @param {Command} cmd @param {Help} helper @returns {number}
longestArgumentTermLength
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
commandUsage(cmd) { // Usage let cmdName = cmd._name; if (cmd._aliases[0]) { cmdName = cmdName + '|' + cmd._aliases[0]; } let ancestorCmdNames = ''; for ( let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent ) { ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames; } return ancestorCmdNames + cmdName + ' ' + cmd.usage(); }
Get the command usage to be displayed at the top of the built-in help. @param {Command} cmd @returns {string}
commandUsage
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
commandDescription(cmd) { // @ts-ignore: because overloaded return type return cmd.description(); }
Get the description for the command. @param {Command} cmd @returns {string}
commandDescription
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
subcommandDescription(cmd) { // @ts-ignore: because overloaded return type return cmd.summary() || cmd.description(); }
Get the subcommand summary to show in the list of subcommands. (Fallback to description for backwards compatibility.) @param {Command} cmd @returns {string}
subcommandDescription
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
optionDescription(option) { const extraInfo = []; if (option.argChoices) { extraInfo.push( // use stringify to match the display of the default value `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`, ); } if (option.defaultValue !== undefined) { // default for boolean and negated more for programmer than end user, // but show true/false for boolean option as may be for hand-rolled env or config processing. const showDefault = option.required || option.optional || (option.isBoolean() && typeof option.defaultValue === 'boolean'); if (showDefault) { extraInfo.push( `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`, ); } } // preset for boolean and negated are more for programmer than end user if (option.presetArg !== undefined && option.optional) { extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`); } if (option.envVar !== undefined) { extraInfo.push(`env: ${option.envVar}`); } if (extraInfo.length > 0) { const extraDescription = `(${extraInfo.join(', ')})`; if (option.description) { return `${option.description} ${extraDescription}`; } return extraDescription; } return option.description; }
Get the option description to show in the list of options. @param {Option} option @return {string}
optionDescription
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
argumentDescription(argument) { const extraInfo = []; if (argument.argChoices) { extraInfo.push( // use stringify to match the display of the default value `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`, ); } if (argument.defaultValue !== undefined) { extraInfo.push( `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`, ); } if (extraInfo.length > 0) { const extraDescription = `(${extraInfo.join(', ')})`; if (argument.description) { return `${argument.description} ${extraDescription}`; } return extraDescription; } return argument.description; }
Get the argument description to show in the list of arguments. @param {Argument} argument @return {string}
argumentDescription
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
formatItemList(heading, items, helper) { if (items.length === 0) return []; return [helper.styleTitle(heading), ...items, '']; }
Format a list of items, given a heading and an array of formatted items. @param {string} heading @param {string[]} items @param {Help} helper @returns string[]
formatItemList
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
groupItems(unsortedItems, visibleItems, getGroup) { const result = new Map(); // Add groups in order of appearance in unsortedItems. unsortedItems.forEach((item) => { const group = getGroup(item); if (!result.has(group)) result.set(group, []); }); // Add items in order of appearance in visibleItems. visibleItems.forEach((item) => { const group = getGroup(item); if (!result.has(group)) { result.set(group, []); } result.get(group).push(item); }); return result; }
Group items by their help group heading. @param {Command[] | Option[]} unsortedItems @param {Command[] | Option[]} visibleItems @param {Function} getGroup @returns {Map<string, Command[] | Option[]>}
groupItems
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
formatHelp(cmd, helper) { const termWidth = helper.padWidth(cmd, helper); const helpWidth = helper.helpWidth ?? 80; // in case prepareContext() was not called function callFormatItem(term, description) { return helper.formatItem(term, termWidth, description, helper); } // Usage let output = [ `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`, '', ]; // Description const commandDescription = helper.commandDescription(cmd); if (commandDescription.length > 0) { output = output.concat([ helper.boxWrap( helper.styleCommandDescription(commandDescription), helpWidth, ), '', ]); } // Arguments const argumentList = helper.visibleArguments(cmd).map((argument) => { return callFormatItem( helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)), ); }); output = output.concat( this.formatItemList('Arguments:', argumentList, helper), ); // Options const optionGroups = this.groupItems( cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? 'Options:', ); optionGroups.forEach((options, group) => { const optionList = options.map((option) => { return callFormatItem( helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)), ); }); output = output.concat(this.formatItemList(group, optionList, helper)); }); if (helper.showGlobalOptions) { const globalOptionList = helper .visibleGlobalOptions(cmd) .map((option) => { return callFormatItem( helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)), ); }); output = output.concat( this.formatItemList('Global Options:', globalOptionList, helper), ); } // Commands const commandGroups = this.groupItems( cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || 'Commands:', ); commandGroups.forEach((commands, group) => { const commandList = commands.map((sub) => { return callFormatItem( helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)), ); }); output = output.concat(this.formatItemList(group, commandList, helper)); }); return output.join('\n'); }
Generate the built-in help text. @param {Command} cmd @param {Help} helper @returns {string}
formatHelp
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
displayWidth(str) { return stripColor(str).length; }
Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations. @param {string} str @returns {number}
displayWidth
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
styleTitle(str) { return str; }
Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc. @param {string} str @returns {string}
styleTitle
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
padWidth(cmd, helper) { return Math.max( helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper), ); }
Calculate the pad width from the maximum term length. @param {Command} cmd @param {Help} helper @returns {number}
padWidth
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
preformatted(str) { return /\n[^\S\r\n]/.test(str); }
Detect manually wrapped and indented strings by checking for line break followed by whitespace. @param {string} str @returns {boolean}
preformatted
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
formatItem(term, termWidth, description, helper) { const itemIndent = 2; const itemIndentStr = ' '.repeat(itemIndent); if (!description) return itemIndentStr + term; // Pad the term out to a consistent width, so descriptions are aligned. const paddedTerm = term.padEnd( termWidth + term.length - helper.displayWidth(term), ); // Format the description. const spacerWidth = 2; // between term and description const helpWidth = this.helpWidth ?? 80; // in case prepareContext() was not called const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent; let formattedDescription; if ( remainingWidth < this.minWidthToWrap || helper.preformatted(description) ) { formattedDescription = description; } else { const wrappedDescription = helper.boxWrap(description, remainingWidth); formattedDescription = wrappedDescription.replace( /\n/g, '\n' + ' '.repeat(termWidth + spacerWidth), ); } // Construct and overall indent. return ( itemIndentStr + paddedTerm + ' '.repeat(spacerWidth) + formattedDescription.replace(/\n/g, `\n${itemIndentStr}`) ); }
Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines. So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so: TTT DDD DDDD DD DDD @param {string} term @param {number} termWidth @param {string} description @param {Help} helper @returns {string}
formatItem
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
boxWrap(str, width) { if (width < this.minWidthToWrap) return str; const rawLines = str.split(/\r\n|\n/); // split up text by whitespace const chunkPattern = /[\s]*[^\s]+/g; const wrappedLines = []; rawLines.forEach((line) => { const chunks = line.match(chunkPattern); if (chunks === null) { wrappedLines.push(''); return; } let sumChunks = [chunks.shift()]; let sumWidth = this.displayWidth(sumChunks[0]); chunks.forEach((chunk) => { const visibleWidth = this.displayWidth(chunk); // Accumulate chunks while they fit into width. if (sumWidth + visibleWidth <= width) { sumChunks.push(chunk); sumWidth += visibleWidth; return; } wrappedLines.push(sumChunks.join('')); const nextChunk = chunk.trimStart(); // trim space at line break sumChunks = [nextChunk]; sumWidth = this.displayWidth(nextChunk); }); wrappedLines.push(sumChunks.join('')); }); return wrappedLines.join('\n'); }
Wrap a string at whitespace, preserving existing line breaks. Wrapping is skipped if the width is less than `minWidthToWrap`. @param {string} str @param {number} width @returns {string}
boxWrap
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
function stripColor(str) { // eslint-disable-next-line no-control-regex const sgrPattern = /\x1b\[\d*(;\d*)*m/g; return str.replace(sgrPattern, ''); }
Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes. @param {string} str @returns {string} @package
stripColor
javascript
tj/commander.js
lib/help.js
https://github.com/tj/commander.js/blob/master/lib/help.js
MIT
constructor(flags, description) { this.flags = flags; this.description = description || ''; this.required = flags.includes('<'); // A value must be supplied when the option is specified. this.optional = flags.includes('['); // A value is optional when the option is specified. // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values. this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line. const optionFlags = splitOptionFlags(flags); this.short = optionFlags.shortFlag; // May be a short flag, undefined, or even a long flag (if option has two long flags). this.long = optionFlags.longFlag; this.negate = false; if (this.long) { this.negate = this.long.startsWith('--no-'); } this.defaultValue = undefined; this.defaultValueDescription = undefined; this.presetArg = undefined; this.envVar = undefined; this.parseArg = undefined; this.hidden = false; this.argChoices = undefined; this.conflictsWith = []; this.implied = undefined; this.helpGroupHeading = undefined; // soft initialised when option added to command }
Initialize a new `Option` with the given `flags` and `description`. @param {string} flags @param {string} [description]
constructor
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
preset(arg) { this.presetArg = arg; return this; }
Preset to use when option used without option-argument, especially optional but also boolean and negated. The custom processing (parseArg) is called. @example new Option('--color').default('GREYSCALE').preset('RGB'); new Option('--donate [amount]').preset('20').argParser(parseFloat); @param {*} arg @return {Option}
preset
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
conflicts(names) { this.conflictsWith = this.conflictsWith.concat(names); return this; }
Add option name(s) that conflict with this option. An error will be displayed if conflicting options are found during parsing. @example new Option('--rgb').conflicts('cmyk'); new Option('--js').conflicts(['ts', 'jsx']); @param {(string | string[])} names @return {Option}
conflicts
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
implies(impliedOptionValues) { let newImplied = impliedOptionValues; if (typeof impliedOptionValues === 'string') { // string is not documented, but easy mistake and we can do what user probably intended. newImplied = { [impliedOptionValues]: true }; } this.implied = Object.assign(this.implied || {}, newImplied); return this; }
Specify implied option values for when this option is set and the implied options are not. The custom processing (parseArg) is not called on the implied values. @example program .addOption(new Option('--log', 'write logging information to file')) .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' })); @param {object} impliedOptionValues @return {Option}
implies
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
env(name) { this.envVar = name; return this; }
Set environment variable to check for option value. An environment variable is only used if when processed the current option value is undefined, or the source of the current value is 'default' or 'config' or 'env'. @param {string} name @return {Option}
env
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
makeOptionMandatory(mandatory = true) { this.mandatory = !!mandatory; return this; }
Whether the option is mandatory and must have a value after parsing. @param {boolean} [mandatory=true] @return {Option}
makeOptionMandatory
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
hideHelp(hide = true) { this.hidden = !!hide; return this; }
Hide option in help. @param {boolean} [hide=true] @return {Option}
hideHelp
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
attributeName() { if (this.negate) { return camelcase(this.name().replace(/^no-/, '')); } return camelcase(this.name()); }
Return option name, in a camelcase format that can be used as an object attribute key. @return {string}
attributeName
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
helpGroup(heading) { this.helpGroupHeading = heading; return this; }
Set the help group heading. @param {string} heading @return {Option}
helpGroup
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
is(arg) { return this.short === arg || this.long === arg; }
Check if `arg` matches the short or long flag. @param {string} arg @return {boolean} @package
is
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
isBoolean() { return !this.required && !this.optional && !this.negate; }
Return whether a boolean option. Options are one of boolean, negated, required argument, or optional argument. @return {boolean} @package
isBoolean
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
valueFromOption(value, option) { const optionKey = option.attributeName(); if (!this.dualOptions.has(optionKey)) return true; // Use the value to deduce if (probably) came from the option. const preset = this.negativeOptions.get(optionKey).presetArg; const negativeValue = preset !== undefined ? preset : false; return option.negate === (negativeValue === value); }
Did the value come from the option, and not from possible matching dual option? @param {*} value @param {Option} option @returns {boolean}
valueFromOption
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
function camelcase(str) { return str.split('-').reduce((str, word) => { return str + word[0].toUpperCase() + word.slice(1); }); }
Convert string from kebab-case to camelCase. @param {string} str @return {string} @private
camelcase
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
function splitOptionFlags(flags) { let shortFlag; let longFlag; // short flag, single dash and single character const shortFlagExp = /^-[^-]$/; // long flag, double dash and at least one character const longFlagExp = /^--[^-]/; const flagParts = flags.split(/[ |,]+/).concat('guard'); // Normal is short and/or long. if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift(); if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift(); // Long then short. Rarely used but fine. if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift(); // Allow two long flags, like '--ws, --workspace' // This is the supported way to have a shortish option flag. if (!shortFlag && longFlagExp.test(flagParts[0])) { shortFlag = longFlag; longFlag = flagParts.shift(); } // Check for unprocessed flag. Fail noisily rather than silently ignore. if (flagParts[0].startsWith('-')) { const unsupportedFlag = flagParts[0]; const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`; if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error( `${baseError} - a short flag is a single dash and a single character - either use a single dash and a single character (for a short flag) - or use a double dash for a long option (and can have two, like '--ws, --workspace')`, ); if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError} - too many short flags`); if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError} - too many long flags`); throw new Error(`${baseError} - unrecognised flag format`); } if (shortFlag === undefined && longFlag === undefined) throw new Error( `option creation failed due to no flags found in '${flags}'.`, ); return { shortFlag, longFlag }; }
Split the short and long flag out of something like '-m,--mixed <value>' @private
splitOptionFlags
javascript
tj/commander.js
lib/option.js
https://github.com/tj/commander.js/blob/master/lib/option.js
MIT
function suggestSimilar(word, candidates) { if (!candidates || candidates.length === 0) return ''; // remove possible duplicates candidates = Array.from(new Set(candidates)); const searchingOptions = word.startsWith('--'); if (searchingOptions) { word = word.slice(2); candidates = candidates.map((candidate) => candidate.slice(2)); } let similar = []; let bestDistance = maxDistance; const minSimilarity = 0.4; candidates.forEach((candidate) => { if (candidate.length <= 1) return; // no one character guesses const distance = editDistance(word, candidate); const length = Math.max(word.length, candidate.length); const similarity = (length - distance) / length; if (similarity > minSimilarity) { if (distance < bestDistance) { // better edit distance, throw away previous worse matches bestDistance = distance; similar = [candidate]; } else if (distance === bestDistance) { similar.push(candidate); } } }); similar.sort((a, b) => a.localeCompare(b)); if (searchingOptions) { similar = similar.map((candidate) => `--${candidate}`); } if (similar.length > 1) { return `\n(Did you mean one of ${similar.join(', ')}?)`; } if (similar.length === 1) { return `\n(Did you mean ${similar[0]}?)`; } return ''; }
Find close matches, restricted to same number of edits. @param {string} word @param {string[]} candidates @returns {string}
suggestSimilar
javascript
tj/commander.js
lib/suggestSimilar.js
https://github.com/tj/commander.js/blob/master/lib/suggestSimilar.js
MIT
get_date_offset = function (date) { var offset = -date.getTimezoneOffset(); return (offset !== null ? offset : 0); }
Gets the offset in minutes from UTC for a certain date. @param {Date} date @returns {Number}
get_date_offset
javascript
Serhioromano/bootstrap-calendar
components/jstimezonedetect/jstz.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/components/jstimezonedetect/jstz.js
MIT
date_is_dst = function (date) { var is_southern = date.getMonth() > 7, base_offset = is_southern ? get_june_offset(date.getFullYear()) : get_january_offset(date.getFullYear()), date_offset = get_date_offset(date), is_west = base_offset < 0, dst_offset = base_offset - date_offset; if (!is_west && !is_southern) { return dst_offset < 0; } return dst_offset !== 0; }
Private method. Checks whether a given date is in daylight saving time. If the date supplied is after august, we assume that we're checking for southern hemisphere DST. @param {Date} date @returns {Boolean}
date_is_dst
javascript
Serhioromano/bootstrap-calendar
components/jstimezonedetect/jstz.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/components/jstimezonedetect/jstz.js
MIT
lookup_key = function () { var january_offset = get_january_offset(), june_offset = get_june_offset(), diff = january_offset - june_offset; if (diff < 0) { return january_offset + ",1"; } else if (diff > 0) { return june_offset + ",1," + HEMISPHERE_SOUTH; } return january_offset + ",0"; }
This function does some basic calculations to create information about the user's timezone. It uses REFERENCE_YEAR as a solid year for which the script has been tested rather than depend on the year set by the client device. Returns a key that can be used to do lookups in jstz.olson.timezones. eg: "720,1,2". @returns {String}
lookup_key
javascript
Serhioromano/bootstrap-calendar
components/jstimezonedetect/jstz.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/components/jstimezonedetect/jstz.js
MIT
dst_start_for = function (tz_name) { var ru_pre_dst_change = new Date(2010, 6, 15, 1, 0, 0, 0), // In 2010 Russia had DST, this allows us to detect Russia :) dst_starts = { 'America/Denver': new Date(2011, 2, 13, 3, 0, 0, 0), 'America/Mazatlan': new Date(2011, 3, 3, 3, 0, 0, 0), 'America/Chicago': new Date(2011, 2, 13, 3, 0, 0, 0), 'America/Mexico_City': new Date(2011, 3, 3, 3, 0, 0, 0), 'America/Asuncion': new Date(2012, 9, 7, 3, 0, 0, 0), 'America/Santiago': new Date(2012, 9, 3, 3, 0, 0, 0), 'America/Campo_Grande': new Date(2012, 9, 21, 5, 0, 0, 0), 'America/Montevideo': new Date(2011, 9, 2, 3, 0, 0, 0), 'America/Sao_Paulo': new Date(2011, 9, 16, 5, 0, 0, 0), 'America/Los_Angeles': new Date(2011, 2, 13, 8, 0, 0, 0), 'America/Santa_Isabel': new Date(2011, 3, 5, 8, 0, 0, 0), 'America/Havana': new Date(2012, 2, 10, 2, 0, 0, 0), 'America/New_York': new Date(2012, 2, 10, 7, 0, 0, 0), 'Europe/Helsinki': new Date(2013, 2, 31, 5, 0, 0, 0), 'Pacific/Auckland': new Date(2011, 8, 26, 7, 0, 0, 0), 'America/Halifax': new Date(2011, 2, 13, 6, 0, 0, 0), 'America/Goose_Bay': new Date(2011, 2, 13, 2, 1, 0, 0), 'America/Miquelon': new Date(2011, 2, 13, 5, 0, 0, 0), 'America/Godthab': new Date(2011, 2, 27, 1, 0, 0, 0), 'Europe/Moscow': ru_pre_dst_change, 'Asia/Amman': new Date(2013, 2, 29, 1, 0, 0, 0), 'Asia/Beirut': new Date(2013, 2, 31, 2, 0, 0, 0), 'Asia/Damascus': new Date(2013, 3, 6, 2, 0, 0, 0), 'Asia/Jerusalem': new Date(2013, 2, 29, 5, 0, 0, 0), 'Asia/Yekaterinburg': ru_pre_dst_change, 'Asia/Omsk': ru_pre_dst_change, 'Asia/Krasnoyarsk': ru_pre_dst_change, 'Asia/Irkutsk': ru_pre_dst_change, 'Asia/Yakutsk': ru_pre_dst_change, 'Asia/Vladivostok': ru_pre_dst_change, 'Asia/Baku': new Date(2013, 2, 31, 4, 0, 0), 'Asia/Yerevan': new Date(2013, 2, 31, 3, 0, 0), 'Asia/Kamchatka': ru_pre_dst_change, 'Asia/Gaza': new Date(2010, 2, 27, 4, 0, 0), 'Africa/Cairo': new Date(2010, 4, 1, 3, 0, 0), 'Europe/Minsk': ru_pre_dst_change, 'Pacific/Apia': new Date(2010, 10, 1, 1, 0, 0, 0), 'Pacific/Fiji': new Date(2010, 11, 1, 0, 0, 0), 'Australia/Perth': new Date(2008, 10, 1, 1, 0, 0, 0) }; return dst_starts[tz_name]; }
This object contains information on when daylight savings starts for different timezones. The list is short for a reason. Often we do not have to be very specific to single out the correct timezone. But when we do, this list comes in handy. Each value is a date denoting when daylight savings starts for that timezone.
dst_start_for
javascript
Serhioromano/bootstrap-calendar
components/jstimezonedetect/jstz.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/components/jstimezonedetect/jstz.js
MIT
ambiguity_check = function () { var ambiguity_list = AMBIGUITIES[timezone_name], length = ambiguity_list.length, i = 0, tz = ambiguity_list[0]; for (; i < length; i += 1) { tz = ambiguity_list[i]; if (jstz.date_is_dst(jstz.dst_start_for(tz))) { timezone_name = tz; return; } } }
Checks if a timezone has possible ambiguities. I.e timezones that are similar. For example, if the preliminary scan determines that we're in America/Denver. We double check here that we're really there and not in America/Mazatlan. This is done by checking known dates for when daylight savings start for different timezones during 2010 and 2011.
ambiguity_check
javascript
Serhioromano/bootstrap-calendar
components/jstimezonedetect/jstz.js
https://github.com/Serhioromano/bootstrap-calendar/blob/master/components/jstimezonedetect/jstz.js
MIT