Simplify typings (#1520)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Simplify typings by removing default export of program * Switch any to unknown per lint suggestion * Add typings change to deprecated.md * Remove stale test which was commented out
authored by John Gee · committed by GitHub · parent ca514ae · Browse files · 3 files·+622 added−610 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+622 added−610 removed
- other:+622 added−610 removed
Provenance
- Commit
ad3f947- Tree
df256e6- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
ca514ae
3 files changed+622 added−610 removed
modified:docs/deprecated.md+3 added-1 removed
40 unmodified lines41424344454546474849505193 unmodified lines40 unmodified linesconst { Command } = require('commander');comnst program = new Command()```
Removed from README in Commander v5. Deprecated from Commander v7. - Removed from README in Commander v5.- Deprecated from Commander v7. - Removed from TypeScript declarations in Commander v8.
## Callback to .help() and .outputHelp()
These routines allowed a callback parameter to process the built-in help before display.93 unmodified linesmodified:typings/index.d.ts+613 added-605 removed
3 unmodified lines4 // Using method rather than property for method-signature-style, to document method overloads separately. Allow either.5 /* eslint-disable @typescript-eslint/method-signature-style */6 /* eslint-disable @typescript-eslint/no-explicit-any */7 8-declare namespace commander {8+export class CommanderError extends Error {9+ code: string;10+ exitCode: number;11+ message: string;12+ nestedError?: string;13 10- interface CommanderError extends Error {11- code: string;12- exitCode: number;13- message: string;14- nestedError?: string;15- }16- type CommanderErrorConstructor = new (exitCode: number, code: string, message: string) => CommanderError;14+ /**15+ * Constructs the CommanderError class16+ * @param {number} exitCode suggested exit code which could be used with process.exit17+ * @param {string} code an id string representing the error18+ * @param {string} message human-readable description of the error19+ * @constructor20+ */21+ constructor(exitCode: number, code: string, message: string);22+}23 18- // eslint-disable-next-line @typescript-eslint/no-empty-interface19- interface InvalidArgumentError extends CommanderError {20- }21- type InvalidArgumentErrorConstructor = new (message: string) => InvalidArgumentError;24+export class InvalidArgumentError extends CommanderError {25+ /**26+ * Constructs the InvalidArgumentError class27+ * @param {string} [message] explanation of why argument is invalid28+ * @constructor29+ */30+ constructor(message: string);31+}32+export { InvalidArgumentError as InvalidOptionArgumentError }; // deprecated old name33 23- interface Argument {24- description: string;25- required: boolean;26- variadic: boolean;34+export class Argument {35+ description: string;36+ required: boolean;37+ variadic: boolean;38 28- /**29- * Return argument name.30- */31- name(): string;32- }39+ /**40+ * Initialize a new command argument with the given name and description.41+ * The default is that the argument is required, and you can explicitly42+ * indicate this with <> around the name. Put [] around the name for an optional argument.43+ *44+ * @param {string} name45+ * @param {string} [description]46+ */47+ constructor(arg: string, description?: string);48 34- interface Option {35- flags: string;36- description: string;49+ /**50+ * Return argument name.51+ */52+ name(): string;53+ }54 38- required: boolean; // A value must be supplied when the option is specified.39- optional: boolean; // A value is optional when the option is specified.40- variadic: boolean;41- mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line.42- optionFlags: string;43- short?: string;44- long?: string;45- negate: boolean;46- defaultValue?: any;47- defaultValueDescription?: string;48- parseArg?: <T>(value: string, previous: T) => T;49- hidden: boolean;50- argChoices?: string[];55+export class Option {56+ flags: string;57+ description: string;58 52- /**53- * Set the default value, and optionally supply the description to be displayed in the help.54- */55- default(value: any, description?: string): this;59+ required: boolean; // A value must be supplied when the option is specified.60+ optional: boolean; // A value is optional when the option is specified.61+ variadic: boolean;62+ mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line.63+ optionFlags: string;64+ short?: string;65+ long?: string;66+ negate: boolean;67+ defaultValue?: any;68+ defaultValueDescription?: string;69+ parseArg?: <T>(value: string, previous: T) => T;70+ hidden: boolean;71+ argChoices?: string[];72 57- /**58- * Calculate the full description, including defaultValue etc.59- */60- fullDescription(): string;73+ constructor(flags: string, description?: string);74 62- /**63- * Set the custom handler for processing CLI option arguments into option values.64- */65- argParser<T>(fn: (value: string, previous: T) => T): this;75+ /**76+ * Set the default value, and optionally supply the description to be displayed in the help.77+ */78+ default(value: unknown, description?: string): this;79 67- /**68- * Whether the option is mandatory and must have a value after parsing.69- */70- makeOptionMandatory(mandatory?: boolean): this;80+ /**81+ * Calculate the full description, including defaultValue etc.82+ */83+ fullDescription(): string;84 72- /**73- * Hide option in help.74- */75- hideHelp(hide?: boolean): this;85+ /**86+ * Set the custom handler for processing CLI option arguments into option values.87+ */88+ argParser<T>(fn: (value: string, previous: T) => T): this;89 77- /**78- * Validation of option argument failed.79- * Intended for use from custom argument processing functions.80- */81- argumentRejected(messsage: string): never;90+ /**91+ * Whether the option is mandatory and must have a value after parsing.92+ */93+ makeOptionMandatory(mandatory?: boolean): this;94 83- /**84- * Only allow option value to be one of choices.85- */86- choices(values: string[]): this;95+ /**96+ * Hide option in help.97+ */98+ hideHelp(hide?: boolean): this;99 88- /**89- * Return option name.90- */91- name(): string;100+ /**101+ * Validation of option argument failed.102+ * Intended for use from custom argument processing functions.103+ */104+ argumentRejected(messsage: string): never;105 93- /**94- * Return option name, in a camelcase format that can be used95- * as a object attribute key.96- */97- attributeName(): string;98- }99- type OptionConstructor = new (flags: string, description?: string) => Option;100- type ArgumentConstructor = new (arg: string, description?: string) => Argument;106+ /**107+ * Only allow option value to be one of choices.108+ */109+ choices(values: string[]): this;110 102- interface Help {103- /** output helpWidth, long lines are wrapped to fit */104- helpWidth?: number;105- sortSubcommands: boolean;106- sortOptions: boolean;111+ /**112+ * Return option name.113+ */114+ name(): string;115 108- /** Get the command term to show in the list of subcommands. */109- subcommandTerm(cmd: Command): string;110- /** Get the command description to show in the list of subcommands. */111- subcommandDescription(cmd: Command): string;112- /** Get the option term to show in the list of options. */113- optionTerm(option: Option): string;114- /** Get the option description to show in the list of options. */115- optionDescription(option: Option): string;116- /** Get the argument term to show in the list of arguments. */117- argumentTerm(argument: Argument): string;118- /** Get the argument description to show in the list of arguments. */119- argumentDescription(argument: Argument): string;116+ /**117+ * Return option name, in a camelcase format that can be used118+ * as a object attribute key.119+ */120+ attributeName(): string;121+}122 121- /** Get the command usage to be displayed at the top of the built-in help. */122- commandUsage(cmd: Command): string;123- /** Get the description for the command. */124- commandDescription(cmd: Command): string;123+export class Help {124+ /** output helpWidth, long lines are wrapped to fit */125+ helpWidth?: number;126+ sortSubcommands: boolean;127+ sortOptions: boolean;128 126- /** Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. */127- visibleCommands(cmd: Command): Command[];128- /** Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. */129- visibleOptions(cmd: Command): Option[];130- /** Get an array of the arguments which have descriptions. */131- visibleArguments(cmd: Command): Argument[];129+ constructor();130 133- /** Get the longest command term length. */134- longestSubcommandTermLength(cmd: Command, helper: Help): number;135- /** Get the longest option term length. */136- longestOptionTermLength(cmd: Command, helper: Help): number;137- /** Get the longest argument term length. */138- longestArgumentTermLength(cmd: Command, helper: Help): number;139- /** Calculate the pad width from the maximum term length. */140- padWidth(cmd: Command, helper: Help): number;131+ /** Get the command term to show in the list of subcommands. */132+ subcommandTerm(cmd: Command): string;133+ /** Get the command description to show in the list of subcommands. */134+ subcommandDescription(cmd: Command): string;135+ /** Get the option term to show in the list of options. */136+ optionTerm(option: Option): string;137+ /** Get the option description to show in the list of options. */138+ optionDescription(option: Option): string;139+ /** Get the argument term to show in the list of arguments. */140+ argumentTerm(argument: Argument): string;141+ /** Get the argument description to show in the list of arguments. */142+ argumentDescription(argument: Argument): string;143 142- /**143- * Wrap the given string to width characters per line, with lines after the first indented.144- * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.145- */146- wrap(str: string, width: number, indent: number, minColumnWidth?: number): string;144+ /** Get the command usage to be displayed at the top of the built-in help. */145+ commandUsage(cmd: Command): string;146+ /** Get the description for the command. */147+ commandDescription(cmd: Command): string;148 148- /** Generate the built-in help text. */149- formatHelp(cmd: Command, helper: Help): string;150- }151- type HelpConstructor = new () => Help;152- type HelpConfiguration = Partial<Help>;149+ /** Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. */150+ visibleCommands(cmd: Command): Command[];151+ /** Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. */152+ visibleOptions(cmd: Command): Option[];153+ /** Get an array of the arguments which have descriptions. */154+ visibleArguments(cmd: Command): Argument[];155 154- interface ParseOptions {155- from: 'node' | 'electron' | 'user';156- }157- interface HelpContext { // optional parameter for .help() and .outputHelp()158- error: boolean;159- }160- interface AddHelpTextContext { // passed to text function used with .addHelpText()161- error: boolean;162- command: Command;163- }164- interface OutputConfiguration {165- writeOut?(str: string): void;166- writeErr?(str: string): void;167- getOutHelpWidth?(): number;168- getErrHelpWidth?(): number;169- outputError?(str: string, write: (str: string) => void): void;156+ /** Get the longest command term length. */157+ longestSubcommandTermLength(cmd: Command, helper: Help): number;158+ /** Get the longest option term length. */159+ longestOptionTermLength(cmd: Command, helper: Help): number;160+ /** Get the longest argument term length. */161+ longestArgumentTermLength(cmd: Command, helper: Help): number;162+ /** Calculate the pad width from the maximum term length. */163+ padWidth(cmd: Command, helper: Help): number;164 171- }165+ /**166+ * Wrap the given string to width characters per line, with lines after the first indented.167+ * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.168+ */169+ wrap(str: string, width: number, indent: number, minColumnWidth?: number): string;170 173- type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';171+ /** Generate the built-in help text. */172+ formatHelp(cmd: Command, helper: Help): string;173+}174+export type HelpConfiguration = Partial<Help>;175 175- interface OptionValues {176- [key: string]: any;177- }176+export interface ParseOptions {177+ from: 'node' | 'electron' | 'user';178+}179+export interface HelpContext { // optional parameter for .help() and .outputHelp()180+ error: boolean;181+}182+export interface AddHelpTextContext { // passed to text function used with .addHelpText()183+ error: boolean;184+ command: Command;185+}186+export interface OutputConfiguration {187+ writeOut?(str: string): void;188+ writeErr?(str: string): void;189+ getOutHelpWidth?(): number;190+ getErrHelpWidth?(): number;191+ outputError?(str: string, write: (str: string) => void): void;192 179- interface Command {180- args: string[];181- commands: Command[];182- parent: Command | null;193+}194 184- /**185- * Set the program version to `str`.186- *187- * This method auto-registers the "-V, --version" flag188- * which will print the version number when passed.189- *190- * You can optionally supply the flags and description to override the defaults.191- */192- version(str: string, flags?: string, description?: string): this;195+type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';196 194- /**195- * Define a command, implemented using an action handler.196- *197- * @remarks198- * The command description is supplied using `.description`, not as a parameter to `.command`.199- *200- * @example201- * ```ts202- * program203- * .command('clone <source> [destination]')204- * .description('clone a repository into a newly created directory')205- * .action((source, destination) => {206- * console.log('clone command called');207- * });208- * ```209- *210- * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`211- * @param opts - configuration options212- * @returns new command213- */214- command(nameAndArgs: string, opts?: CommandOptions): ReturnType<this['createCommand']>;215- /**216- * Define a command, implemented in a separate executable file.217- *218- * @remarks219- * The command description is supplied as the second parameter to `.command`.220- *221- * @example222- * ```ts223- * program224- * .command('start <service>', 'start named service')225- * .command('stop [service]', 'stop named service, or all if no name supplied');226- * ```227- *228- * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`229- * @param description - description of executable command230- * @param opts - configuration options231- * @returns `this` command for chaining232- */233- command(nameAndArgs: string, description: string, opts?: commander.ExecutableCommandOptions): this;197+export interface OptionValues {198+ [key: string]: any;199+}200 235- /**236- * Factory routine to create a new unattached command.237- *238- * See .command() for creating an attached subcommand, which uses this routine to239- * create the command. You can override createCommand to customise subcommands.240- */241- createCommand(name?: string): Command;201+export class Command {202+ args: string[];203+ commands: Command[];204+ parent: Command | null;205 243- /**244- * Add a prepared subcommand.245- *246- * See .command() for creating an attached subcommand which inherits settings from its parent.247- *248- * @returns `this` command for chaining249- */250- addCommand(cmd: Command, opts?: CommandOptions): this;206+ constructor(name?: string);207 252- /**253- * Factory routine to create a new unattached argument.254- *255- * See .argument() for creating an attached argument, which uses this routine to256- * create the argument. You can override createArgument to return a custom argument.257- */258- createArgument(name: string, description?: string): Argument;208+ /**209+ * Set the program version to `str`.210+ *211+ * This method auto-registers the "-V, --version" flag212+ * which will print the version number when passed.213+ *214+ * You can optionally supply the flags and description to override the defaults.215+ */216+ version(str: string, flags?: string, description?: string): this;217 260- /**261- * Define argument syntax for command.262- *263- * The default is that the argument is required, and you can explicitly264- * indicate this with <> around the name. Put [] around the name for an optional argument.265- *266- * @example267- *268- * program.argument('<input-file>');269- * program.argument('[output-file]');270- *271- * @returns `this` command for chaining272- */273- argument<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;274- argument(name: string, description?: string, defaultValue?: any): this;218+ /**219+ * Define a command, implemented using an action handler.220+ *221+ * @remarks222+ * The command description is supplied using `.description`, not as a parameter to `.command`.223+ *224+ * @example225+ * ```ts226+ * program227+ * .command('clone <source> [destination]')228+ * .description('clone a repository into a newly created directory')229+ * .action((source, destination) => {230+ * console.log('clone command called');231+ * });232+ * ```233+ *234+ * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`235+ * @param opts - configuration options236+ * @returns new command237+ */238+ command(nameAndArgs: string, opts?: CommandOptions): ReturnType<this['createCommand']>;239+ /**240+ * Define a command, implemented in a separate executable file.241+ *242+ * @remarks243+ * The command description is supplied as the second parameter to `.command`.244+ *245+ * @example246+ * ```ts247+ * program248+ * .command('start <service>', 'start named service')249+ * .command('stop [service]', 'stop named service, or all if no name supplied');250+ * ```251+ *252+ * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`253+ * @param description - description of executable command254+ * @param opts - configuration options255+ * @returns `this` command for chaining256+ */257+ command(nameAndArgs: string, description: string, opts?: ExecutableCommandOptions): this;258 276- /**277- * Define argument syntax for command, adding a prepared argument.278- *279- * @returns `this` command for chaining280- */281- addArgument(arg: Argument): this;259+ /**260+ * Factory routine to create a new unattached command.261+ *262+ * See .command() for creating an attached subcommand, which uses this routine to263+ * create the command. You can override createCommand to customise subcommands.264+ */265+ createCommand(name?: string): Command;266 283- /**284- * Define argument syntax for command, adding multiple at once (without descriptions).285- *286- * See also .argument().287- *288- * @example289- *290- * program.arguments('<cmd> [env]');291- *292- * @returns `this` command for chaining293- */294- arguments(names: string): this;267+ /**268+ * Add a prepared subcommand.269+ *270+ * See .command() for creating an attached subcommand which inherits settings from its parent.271+ *272+ * @returns `this` command for chaining273+ */274+ addCommand(cmd: Command, opts?: CommandOptions): this;275 296- /**297- * Override default decision whether to add implicit help command.298- *299- * addHelpCommand() // force on300- * addHelpCommand(false); // force off301- * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details302- *303- * @returns `this` command for chaining304- */305- addHelpCommand(enableOrNameAndArgs?: string | boolean, description?: string): this;276+ /**277+ * Factory routine to create a new unattached argument.278+ *279+ * See .argument() for creating an attached argument, which uses this routine to280+ * create the argument. You can override createArgument to return a custom argument.281+ */282+ createArgument(name: string, description?: string): Argument;283 307- /**308- * Register callback to use as replacement for calling process.exit.309- */310- exitOverride(callback?: (err: CommanderError) => never|void): this;284+ /**285+ * Define argument syntax for command.286+ *287+ * The default is that the argument is required, and you can explicitly288+ * indicate this with <> around the name. Put [] around the name for an optional argument.289+ *290+ * @example291+ *292+ * program.argument('<input-file>');293+ * program.argument('[output-file]');294+ *295+ * @returns `this` command for chaining296+ */297+ argument<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;298+ argument(name: string, description?: string, defaultValue?: unknown): this;299 312- /**313- * You can customise the help with a subclass of Help by overriding createHelp,314- * or by overriding Help properties using configureHelp().315- */316- createHelp(): Help;300+ /**301+ * Define argument syntax for command, adding a prepared argument.302+ *303+ * @returns `this` command for chaining304+ */305+ addArgument(arg: Argument): this;306 318- /**319- * You can customise the help by overriding Help properties using configureHelp(),320- * or with a subclass of Help by overriding createHelp().321- */322- configureHelp(configuration: HelpConfiguration): this;323- /** Get configuration */324- configureHelp(): HelpConfiguration;307+ /**308+ * Define argument syntax for command, adding multiple at once (without descriptions).309+ *310+ * See also .argument().311+ *312+ * @example313+ *314+ * program.arguments('<cmd> [env]');315+ *316+ * @returns `this` command for chaining317+ */318+ arguments(names: string): this;319 326- /**327- * The default output goes to stdout and stderr. You can customise this for special328- * applications. You can also customise the display of errors by overriding outputError.329- *330- * The configuration properties are all functions:331- *332- * // functions to change where being written, stdout and stderr333- * writeOut(str)334- * writeErr(str)335- * // matching functions to specify width for wrapping help336- * getOutHelpWidth()337- * getErrHelpWidth()338- * // functions based on what is being written out339- * outputError(str, write) // used for displaying errors, and not used for displaying help340- */341- configureOutput(configuration: OutputConfiguration): this;342- /** Get configuration */343- configureOutput(): OutputConfiguration;320+ /**321+ * Override default decision whether to add implicit help command.322+ *323+ * addHelpCommand() // force on324+ * addHelpCommand(false); // force off325+ * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details326+ *327+ * @returns `this` command for chaining328+ */329+ addHelpCommand(enableOrNameAndArgs?: string | boolean, description?: string): this;330 345- /**346- * Register callback `fn` for the command.347- *348- * @example349- * program350- * .command('help')351- * .description('display verbose help')352- * .action(function() {353- * // output help here354- * });355- *356- * @returns `this` command for chaining357- */358- action(fn: (...args: any[]) => void | Promise<void>): this;331+ /**332+ * Register callback to use as replacement for calling process.exit.333+ */334+ exitOverride(callback?: (err: CommanderError) => never|void): this;335 360- /**361- * Define option with `flags`, `description` and optional362- * coercion `fn`.363- *364- * The `flags` string contains the short and/or long flags,365- * separated by comma, a pipe or space. The following are all valid366- * all will output this way when `--help` is used.367- *368- * "-p, --pepper"369- * "-p|--pepper"370- * "-p --pepper"371- *372- * @example373- * // simple boolean defaulting to false374- * program.option('-p, --pepper', 'add pepper');375- *376- * --pepper377- * program.pepper378- * // => Boolean379- *380- * // simple boolean defaulting to true381- * program.option('-C, --no-cheese', 'remove cheese');382- *383- * program.cheese384- * // => true385- *386- * --no-cheese387- * program.cheese388- * // => false389- *390- * // required argument391- * program.option('-C, --chdir <path>', 'change the working directory');392- *393- * --chdir /tmp394- * program.chdir395- * // => "/tmp"396- *397- * // optional argument398- * program.option('-c, --cheese [type]', 'add cheese [marble]');399- *400- * @returns `this` command for chaining401- */402- option(flags: string, description?: string, defaultValue?: string | boolean): this;403- option<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;404- /** @deprecated since v7, instead use choices or a custom function */405- option(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean): this;336+ /**337+ * You can customise the help with a subclass of Help by overriding createHelp,338+ * or by overriding Help properties using configureHelp().339+ */340+ createHelp(): Help;341 407- /**408- * Define a required option, which must have a value after parsing. This usually means409- * the option must be specified on the command line. (Otherwise the same as .option().)410- *411- * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.412- */413- requiredOption(flags: string, description?: string, defaultValue?: string | boolean): this;414- requiredOption<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;415- /** @deprecated since v7, instead use choices or a custom function */416- requiredOption(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean): this;342+ /**343+ * You can customise the help by overriding Help properties using configureHelp(),344+ * or with a subclass of Help by overriding createHelp().345+ */346+ configureHelp(configuration: HelpConfiguration): this;347+ /** Get configuration */348+ configureHelp(): HelpConfiguration;349 418- /**419- * Factory routine to create a new unattached option.420- *421- * See .option() for creating an attached option, which uses this routine to422- * create the option. You can override createOption to return a custom option.423- */350+ /**351+ * The default output goes to stdout and stderr. You can customise this for special352+ * applications. You can also customise the display of errors by overriding outputError.353+ *354+ * The configuration properties are all functions:355+ *356+ * // functions to change where being written, stdout and stderr357+ * writeOut(str)358+ * writeErr(str)359+ * // matching functions to specify width for wrapping help360+ * getOutHelpWidth()361+ * getErrHelpWidth()362+ * // functions based on what is being written out363+ * outputError(str, write) // used for displaying errors, and not used for displaying help364+ */365+ configureOutput(configuration: OutputConfiguration): this;366+ /** Get configuration */367+ configureOutput(): OutputConfiguration;368 425- createOption(flags: string, description?: string): Option;369+ /**370+ * Register callback `fn` for the command.371+ *372+ * @example373+ * program374+ * .command('help')375+ * .description('display verbose help')376+ * .action(function() {377+ * // output help here378+ * });379+ *380+ * @returns `this` command for chaining381+ */382+ action(fn: (...args: any[]) => void | Promise<void>): this;383 427- /**428- * Add a prepared Option.429- *430- * See .option() and .requiredOption() for creating and attaching an option in a single call.431- */432- addOption(option: Option): this;384+ /**385+ * Define option with `flags`, `description` and optional386+ * coercion `fn`.387+ *388+ * The `flags` string contains the short and/or long flags,389+ * separated by comma, a pipe or space. The following are all valid390+ * all will output this way when `--help` is used.391+ *392+ * "-p, --pepper"393+ * "-p|--pepper"394+ * "-p --pepper"395+ *396+ * @example397+ * // simple boolean defaulting to false398+ * program.option('-p, --pepper', 'add pepper');399+ *400+ * --pepper401+ * program.pepper402+ * // => Boolean403+ *404+ * // simple boolean defaulting to true405+ * program.option('-C, --no-cheese', 'remove cheese');406+ *407+ * program.cheese408+ * // => true409+ *410+ * --no-cheese411+ * program.cheese412+ * // => false413+ *414+ * // required argument415+ * program.option('-C, --chdir <path>', 'change the working directory');416+ *417+ * --chdir /tmp418+ * program.chdir419+ * // => "/tmp"420+ *421+ * // optional argument422+ * program.option('-c, --cheese [type]', 'add cheese [marble]');423+ *424+ * @returns `this` command for chaining425+ */426+ option(flags: string, description?: string, defaultValue?: string | boolean): this;427+ option<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;428+ /** @deprecated since v7, instead use choices or a custom function */429+ option(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean): this;430 434- /**435- * Whether to store option values as properties on command object,436- * or store separately (specify false). In both cases the option values can be accessed using .opts().437- *438- * @returns `this` command for chaining439- */440- storeOptionsAsProperties(): this & OptionValues;441- storeOptionsAsProperties(storeAsProperties: true): this & OptionValues;442- storeOptionsAsProperties(storeAsProperties?: boolean): this;431+ /**432+ * Define a required option, which must have a value after parsing. This usually means433+ * the option must be specified on the command line. (Otherwise the same as .option().)434+ *435+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.436+ */437+ requiredOption(flags: string, description?: string, defaultValue?: string | boolean): this;438+ requiredOption<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;439+ /** @deprecated since v7, instead use choices or a custom function */440+ requiredOption(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean): this;441 444- /**445- * Alter parsing of short flags with optional values.446- *447- * @example448- * // for `.option('-f,--flag [value]'):449- * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour450- * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`451- *452- * @returns `this` command for chaining453- */454- combineFlagAndOptionalValue(combine?: boolean): this;442+ /**443+ * Factory routine to create a new unattached option.444+ *445+ * See .option() for creating an attached option, which uses this routine to446+ * create the option. You can override createOption to return a custom option.447+ */448 456- /**457- * Allow unknown options on the command line.458- *459- * @returns `this` command for chaining460- */461- allowUnknownOption(allowUnknown?: boolean): this;449+ createOption(flags: string, description?: string): Option;450 463- /**464- * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.465- *466- * @returns `this` command for chaining467- */468- allowExcessArguments(allowExcess?: boolean): this;451+ /**452+ * Add a prepared Option.453+ *454+ * See .option() and .requiredOption() for creating and attaching an option in a single call.455+ */456+ addOption(option: Option): this;457 470- /**471- * Enable positional options. Positional means global options are specified before subcommands which lets472- * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.473- *474- * The default behaviour is non-positional and global options may appear anywhere on the command line.475- *476- * @returns `this` command for chaining477- */478- enablePositionalOptions(positional?: boolean): this;458+ /**459+ * Whether to store option values as properties on command object,460+ * or store separately (specify false). In both cases the option values can be accessed using .opts().461+ *462+ * @returns `this` command for chaining463+ */464+ storeOptionsAsProperties(): this & OptionValues;465+ storeOptionsAsProperties(storeAsProperties: true): this & OptionValues;466+ storeOptionsAsProperties(storeAsProperties?: boolean): this;467 480- /**481- * Pass through options that come after command-arguments rather than treat them as command-options,482- * so actual command-options come before command-arguments. Turning this on for a subcommand requires483- * positional options to have been enabled on the program (parent commands).484- *485- * The default behaviour is non-positional and options may appear before or after command-arguments.486- *487- * @returns `this` command for chaining488- */489- passThroughOptions(passThrough?: boolean): this;468+ /**469+ * Alter parsing of short flags with optional values.470+ *471+ * @example472+ * // for `.option('-f,--flag [value]'):473+ * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour474+ * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`475+ *476+ * @returns `this` command for chaining477+ */478+ combineFlagAndOptionalValue(combine?: boolean): this;479 491- /**492- * Parse `argv`, setting options and invoking commands when defined.493- *494- * The default expectation is that the arguments are from node and have the application as argv[0]495- * and the script being run in argv[1], with user parameters after that.496- *497- * Examples:498- *499- * program.parse(process.argv);500- * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions501- * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]502- *503- * @returns `this` command for chaining504- */505- parse(argv?: string[], options?: ParseOptions): this;480+ /**481+ * Allow unknown options on the command line.482+ *483+ * @returns `this` command for chaining484+ */485+ allowUnknownOption(allowUnknown?: boolean): this;486 507- /**508- * Parse `argv`, setting options and invoking commands when defined.509- *510- * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.511- *512- * The default expectation is that the arguments are from node and have the application as argv[0]513- * and the script being run in argv[1], with user parameters after that.514- *515- * Examples:516- *517- * program.parseAsync(process.argv);518- * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions519- * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]520- *521- * @returns Promise522- */523- parseAsync(argv?: string[], options?: ParseOptions): Promise<this>;487+ /**488+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.489+ *490+ * @returns `this` command for chaining491+ */492+ allowExcessArguments(allowExcess?: boolean): this;493 525- /**526- * Parse options from `argv` removing known options,527- * and return argv split into operands and unknown arguments.528- *529- * @example530- * argv => operands, unknown531- * --known kkk op => [op], []532- * op --known kkk => [op], []533- * sub --unknown uuu op => [sub], [--unknown uuu op]534- * sub -- --unknown uuu op => [sub --unknown uuu op], []535- */536- parseOptions(argv: string[]): commander.ParseOptionsResult;494+ /**495+ * Enable positional options. Positional means global options are specified before subcommands which lets496+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.497+ *498+ * The default behaviour is non-positional and global options may appear anywhere on the command line.499+ *500+ * @returns `this` command for chaining501+ */502+ enablePositionalOptions(positional?: boolean): this;503 538- /**539- * Return an object containing options as key-value pairs540- */541- opts(): OptionValues;504+ /**505+ * Pass through options that come after command-arguments rather than treat them as command-options,506+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires507+ * positional options to have been enabled on the program (parent commands).508+ *509+ * The default behaviour is non-positional and options may appear before or after command-arguments.510+ *511+ * @returns `this` command for chaining512+ */513+ passThroughOptions(passThrough?: boolean): this;514 543- /**544- * Set the description.545- *546- * @returns `this` command for chaining547- */515+ /**516+ * Parse `argv`, setting options and invoking commands when defined.517+ *518+ * The default expectation is that the arguments are from node and have the application as argv[0]519+ * and the script being run in argv[1], with user parameters after that.520+ *521+ * Examples:522+ *523+ * program.parse(process.argv);524+ * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions525+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]526+ *527+ * @returns `this` command for chaining528+ */529+ parse(argv?: string[], options?: ParseOptions): this;530 549- description(str: string): this;550- /** @deprecated since v8, instead use .argument to add command argument with description */551- description(str: string, argsDescription: {[argName: string]: string}): this;552- /**553- * Get the description.554- */555- description(): string;531+ /**532+ * Parse `argv`, setting options and invoking commands when defined.533+ *534+ * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.535+ *536+ * The default expectation is that the arguments are from node and have the application as argv[0]537+ * and the script being run in argv[1], with user parameters after that.538+ *539+ * Examples:540+ *541+ * program.parseAsync(process.argv);542+ * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions543+ * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]544+ *545+ * @returns Promise546+ */547+ parseAsync(argv?: string[], options?: ParseOptions): Promise<this>;548 557- /**558- * Set an alias for the command.559- *560- * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.561- *562- * @returns `this` command for chaining563- */564- alias(alias: string): this;565- /**566- * Get alias for the command.567- */568- alias(): string;549+ /**550+ * Parse options from `argv` removing known options,551+ * and return argv split into operands and unknown arguments.552+ *553+ * @example554+ * argv => operands, unknown555+ * --known kkk op => [op], []556+ * op --known kkk => [op], []557+ * sub --unknown uuu op => [sub], [--unknown uuu op]558+ * sub -- --unknown uuu op => [sub --unknown uuu op], []559+ */560+ parseOptions(argv: string[]): ParseOptionsResult;561 570- /**571- * Set aliases for the command.572- *573- * Only the first alias is shown in the auto-generated help.574- *575- * @returns `this` command for chaining576- */577- aliases(aliases: string[]): this;578- /**579- * Get aliases for the command.580- */581- aliases(): string[];562+ /**563+ * Return an object containing options as key-value pairs564+ */565+ opts(): OptionValues;566 583- /**584- * Set the command usage.585- *586- * @returns `this` command for chaining587- */588- usage(str: string): this;589- /**590- * Get the command usage.591- */592- usage(): string;567+ /**568+ * Set the description.569+ *570+ * @returns `this` command for chaining571+ */572 594- /**595- * Set the name of the command.596- *597- * @returns `this` command for chaining598- */599- name(str: string): this;600- /**601- * Get the name of the command.602- */603- name(): string;573+ description(str: string): this;574+ /** @deprecated since v8, instead use .argument to add command argument with description */575+ description(str: string, argsDescription: {[argName: string]: string}): this;576+ /**577+ * Get the description.578+ */579+ description(): string;580 605- /**606- * Output help information for this command.607- *608- * Outputs built-in help, and custom text added using `.addHelpText()`.609- *610- */611- outputHelp(context?: HelpContext): void;612- /** @deprecated since v7 */613- outputHelp(cb?: (str: string) => string): void;581+ /**582+ * Set an alias for the command.583+ *584+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.585+ *586+ * @returns `this` command for chaining587+ */588+ alias(alias: string): this;589+ /**590+ * Get alias for the command.591+ */592+ alias(): string;593 615- /**616- * Return command help documentation.617- */618- helpInformation(context?: HelpContext): string;594+ /**595+ * Set aliases for the command.596+ *597+ * Only the first alias is shown in the auto-generated help.598+ *599+ * @returns `this` command for chaining600+ */601+ aliases(aliases: string[]): this;602+ /**603+ * Get aliases for the command.604+ */605+ aliases(): string[];606 620- /**621- * You can pass in flags and a description to override the help622- * flags and help description for your command. Pass in false623- * to disable the built-in help option.624- */625- helpOption(flags?: string | boolean, description?: string): this;607+ /**608+ * Set the command usage.609+ *610+ * @returns `this` command for chaining611+ */612+ usage(str: string): this;613+ /**614+ * Get the command usage.615+ */616+ usage(): string;617 627- /**628- * Output help information and exit.629- *630- * Outputs built-in help, and custom text added using `.addHelpText()`.631- */632- help(context?: HelpContext): never;633- /** @deprecated since v7 */634- help(cb?: (str: string) => string): never;618+ /**619+ * Set the name of the command.620+ *621+ * @returns `this` command for chaining622+ */623+ name(str: string): this;624+ /**625+ * Get the name of the command.626+ */627+ name(): string;628 636- /**637- * Add additional text to be displayed with the built-in help.638- *639- * Position is 'before' or 'after' to affect just this command,640- * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.641- */642- addHelpText(position: AddHelpTextPosition, text: string): this;643- addHelpText(position: AddHelpTextPosition, text: (context: AddHelpTextContext) => string): this;629+ /**630+ * Output help information for this command.631+ *632+ * Outputs built-in help, and custom text added using `.addHelpText()`.633+ *634+ */635+ outputHelp(context?: HelpContext): void;636+ /** @deprecated since v7 */637+ outputHelp(cb?: (str: string) => string): void;638 645- /**646- * Add a listener (callback) for when events occur. (Implemented using EventEmitter.)647- */648- on(event: string | symbol, listener: (...args: any[]) => void): this;649- }650- type CommandConstructor = new (name?: string) => Command;639+ /**640+ * Return command help documentation.641+ */642+ helpInformation(context?: HelpContext): string;643 652- interface CommandOptions {653- hidden?: boolean;654- isDefault?: boolean;655- /** @deprecated since v7, replaced by hidden */656- noHelp?: boolean;657- }658- interface ExecutableCommandOptions extends CommandOptions {659- executableFile?: string;660- }644+ /**645+ * You can pass in flags and a description to override the help646+ * flags and help description for your command. Pass in false647+ * to disable the built-in help option.648+ */649+ helpOption(flags?: string | boolean, description?: string): this;650 662- // eslint-disable-next-line @typescript-eslint/no-unused-vars663- interface ParseOptionsResult {664- operands: string[];665- unknown: string[];666- }651+ /**652+ * Output help information and exit.653+ *654+ * Outputs built-in help, and custom text added using `.addHelpText()`.655+ */656+ help(context?: HelpContext): never;657+ /** @deprecated since v7 */658+ help(cb?: (str: string) => string): never;659 668- // eslint-disable-next-line @typescript-eslint/no-unused-vars669- interface CommanderStatic extends Command {670- program: Command;671- Command: CommandConstructor;672- Option: OptionConstructor;673- Argument: ArgumentConstructor;674- CommanderError: CommanderErrorConstructor;675- InvalidArgumentError: InvalidArgumentErrorConstructor;676- /** @deprecated since v8, replaced by InvalidArgumentError */677- InvalidOptionArgumentError: InvalidArgumentErrorConstructor;678- Help: HelpConstructor;679- }660+ /**661+ * Add additional text to be displayed with the built-in help.662+ *663+ * Position is 'before' or 'after' to affect just this command,664+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.665+ */666+ addHelpText(position: AddHelpTextPosition, text: string): this;667+ addHelpText(position: AddHelpTextPosition, text: (context: AddHelpTextContext) => string): this;668 669+ /**670+ * Add a listener (callback) for when events occur. (Implemented using EventEmitter.)671+ */672+ on(event: string | symbol, listener: (...args: any[]) => void): this;673 }674 683-// Declaring namespace AND global684-// eslint-disable-next-line @typescript-eslint/no-redeclare685-declare const commander: commander.CommanderStatic;686-export = commander;675+export interface CommandOptions {676+ hidden?: boolean;677+ isDefault?: boolean;678+ /** @deprecated since v7, replaced by hidden */679+ noHelp?: boolean;680+}681+export interface ExecutableCommandOptions extends CommandOptions {682+ executableFile?: string;683+}684+685+export interface ParseOptionsResult {686+ operands: string[];687+ unknown: string[];688+}689+690+export function createCommand(name?: string): Command;691+export function createOption(flags: string, description?: string): Option;692+export function createArgument(name: string, description?: string): Argument;693+694+export const program: Command;modified:typings/index.test-d.ts+6 added-4 removed
1 import * as commander from './index';2-import {expectType, expectAssignable} from 'tsd';2+import {expectType} from 'tsd';3 4 // We are are not just checking return types here, we are also implicitly checking that the expected syntax is allowed.5 6 const program: commander.Command = new commander.Command();7+// @ts-expect-error Check that Command is strongly typed and does not allow arbitrary properties7-// program.silly; // <-- Error, hurrah!8+program.silly; // <-- Error, hurrah!9 9-// Check for exported global Command object(s)10-expectAssignable<commander.Command>(commander); // legacy default export of program10+// Check for exported global Command object11 expectType<commander.Command>(commander.program);12 13 // Check export classes and functions exist14 expectType<commander.Command>(new commander.Command());2 unmodified lines17 expectType<commander.CommanderError>(new commander.CommanderError(1, 'code', 'message'));18 expectType<commander.InvalidArgumentError>(new commander.InvalidArgumentError('message'));19 expectType<commander.InvalidArgumentError>(new commander.InvalidOptionArgumentError('message'));20 expectType<commander.Command>(commander.createCommand());21+expectType<commander.Option>(commander.createOption('--demo'));22+expectType<commander.Argument>(commander.createArgument('<foo>'));23 24 // Command properties25 expectType<string[]>(program.args);26 expectType<commander.Command[]>(program.commands);330 unmodified lines