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
_option... | 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._savedSt... | 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 .executab... | 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._dispa... | 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.registeredAr... | 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 ... | 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) => {
hook... | @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... | @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)... | 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()) ... | 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';
});
... | 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 negativeNum... | 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... | 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] =
... | 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._... | 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) ===... | 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
.f... | 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.ge... | `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 comm... | 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 ${ex... | 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.at... | 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)} `t... | 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.lengt... | 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]' : [],
t... | 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 {Comma... | 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'... | 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, helpe... | 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.getErrHasColo... | @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 = ... | 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
... | 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} ... | 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.err... | 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`;
... | 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 functi... | 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.h... | 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';
... | 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(".... | 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 }} cont... | 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) => {
// @t... | 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).lo... | 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 ... | 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,
);
... | 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()] || '';
});
... | 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]' ... | 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 = ancestor... | 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 !== undefine... | 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 !==... | 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 v... | 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 outpu... | 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... | 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
@... | 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 ===... | 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 ignor... | 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.impli... | 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... | 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 ? pre... | 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... | 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((can... | 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),
... | 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) {
... | 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".
@return... | 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 D... | 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 ... | 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
time... | ambiguity_check | javascript | Serhioromano/bootstrap-calendar | components/jstimezonedetect/jstz.js | https://github.com/Serhioromano/bootstrap-calendar/blob/master/components/jstimezonedetect/jstz.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.