UNPKG

23.9 kBTypeScriptView Raw
1// Type definitions for commander
2// Original definitions by: Alan Agius <https://github.com/alan-agius4>, Marcelo Dezem <https://github.com/mdezem>, vvakame <https://github.com/vvakame>, Jules Randolph <https://github.com/sveinburne>
3
4// 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
8export class CommanderError extends Error {
9 code: string;
10 exitCode: number;
11 message: string;
12 nestedError?: string;
13
14 /**
15 * Constructs the CommanderError class
16 * @param exitCode - suggested exit code which could be used with process.exit
17 * @param code - an id string representing the error
18 * @param message - human-readable description of the error
19 * @constructor
20 */
21 constructor(exitCode: number, code: string, message: string);
22}
23
24export class InvalidArgumentError extends CommanderError {
25 /**
26 * Constructs the InvalidArgumentError class
27 * @param message - explanation of why argument is invalid
28 * @constructor
29 */
30 constructor(message: string);
31}
32export { InvalidArgumentError as InvalidOptionArgumentError }; // deprecated old name
33
34export class Argument {
35 description: string;
36 required: boolean;
37 variadic: boolean;
38
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 explicitly
42 * indicate this with <> around the name. Put [] around the name for an optional argument.
43 */
44 constructor(arg: string, description?: string);
45
46 /**
47 * Return argument name.
48 */
49 name(): string;
50
51 /**
52 * Set the default value, and optionally supply the description to be displayed in the help.
53 */
54 default(value: unknown, description?: string): this;
55
56 /**
57 * Set the custom handler for processing CLI command arguments into argument values.
58 */
59 argParser<T>(fn: (value: string, previous: T) => T): this;
60
61 /**
62 * Only allow argument value to be one of choices.
63 */
64 choices(values: string[]): this;
65
66 /**
67 * Make option-argument required.
68 */
69 argRequired(): this;
70
71 /**
72 * Make option-argument optional.
73 */
74 argOptional(): this;
75 }
76
77export class Option {
78 flags: string;
79 description: string;
80
81 required: boolean; // A value must be supplied when the option is specified.
82 optional: boolean; // A value is optional when the option is specified.
83 variadic: boolean;
84 mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line.
85 optionFlags: string;
86 short?: string;
87 long?: string;
88 negate: boolean;
89 defaultValue?: any;
90 defaultValueDescription?: string;
91 parseArg?: <T>(value: string, previous: T) => T;
92 hidden: boolean;
93 argChoices?: string[];
94
95 constructor(flags: string, description?: string);
96
97 /**
98 * Set the default value, and optionally supply the description to be displayed in the help.
99 */
100 default(value: unknown, description?: string): this;
101
102 /**
103 * Calculate the full description, including defaultValue etc.
104 */
105 fullDescription(): string;
106
107 /**
108 * Set the custom handler for processing CLI option arguments into option values.
109 */
110 argParser<T>(fn: (value: string, previous: T) => T): this;
111
112 /**
113 * Whether the option is mandatory and must have a value after parsing.
114 */
115 makeOptionMandatory(mandatory?: boolean): this;
116
117 /**
118 * Hide option in help.
119 */
120 hideHelp(hide?: boolean): this;
121
122 /**
123 * Validation of option argument failed.
124 * Intended for use from custom argument processing functions.
125 */
126 argumentRejected(messsage: string): never;
127
128 /**
129 * Only allow option value to be one of choices.
130 */
131 choices(values: string[]): this;
132
133 /**
134 * Return option name.
135 */
136 name(): string;
137
138 /**
139 * Return option name, in a camelcase format that can be used
140 * as a object attribute key.
141 */
142 attributeName(): string;
143}
144
145export class Help {
146 /** output helpWidth, long lines are wrapped to fit */
147 helpWidth?: number;
148 sortSubcommands: boolean;
149 sortOptions: boolean;
150
151 constructor();
152
153 /** Get the command term to show in the list of subcommands. */
154 subcommandTerm(cmd: Command): string;
155 /** Get the command description to show in the list of subcommands. */
156 subcommandDescription(cmd: Command): string;
157 /** Get the option term to show in the list of options. */
158 optionTerm(option: Option): string;
159 /** Get the option description to show in the list of options. */
160 optionDescription(option: Option): string;
161 /** Get the argument term to show in the list of arguments. */
162 argumentTerm(argument: Argument): string;
163 /** Get the argument description to show in the list of arguments. */
164 argumentDescription(argument: Argument): string;
165
166 /** Get the command usage to be displayed at the top of the built-in help. */
167 commandUsage(cmd: Command): string;
168 /** Get the description for the command. */
169 commandDescription(cmd: Command): string;
170
171 /** Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. */
172 visibleCommands(cmd: Command): Command[];
173 /** Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. */
174 visibleOptions(cmd: Command): Option[];
175 /** Get an array of the arguments which have descriptions. */
176 visibleArguments(cmd: Command): Argument[];
177
178 /** Get the longest command term length. */
179 longestSubcommandTermLength(cmd: Command, helper: Help): number;
180 /** Get the longest option term length. */
181 longestOptionTermLength(cmd: Command, helper: Help): number;
182 /** Get the longest argument term length. */
183 longestArgumentTermLength(cmd: Command, helper: Help): number;
184 /** Calculate the pad width from the maximum term length. */
185 padWidth(cmd: Command, helper: Help): number;
186
187 /**
188 * Wrap the given string to width characters per line, with lines after the first indented.
189 * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
190 */
191 wrap(str: string, width: number, indent: number, minColumnWidth?: number): string;
192
193 /** Generate the built-in help text. */
194 formatHelp(cmd: Command, helper: Help): string;
195}
196export type HelpConfiguration = Partial<Help>;
197
198export interface ParseOptions {
199 from: 'node' | 'electron' | 'user';
200}
201export interface HelpContext { // optional parameter for .help() and .outputHelp()
202 error: boolean;
203}
204export interface AddHelpTextContext { // passed to text function used with .addHelpText()
205 error: boolean;
206 command: Command;
207}
208export interface OutputConfiguration {
209 writeOut?(str: string): void;
210 writeErr?(str: string): void;
211 getOutHelpWidth?(): number;
212 getErrHelpWidth?(): number;
213 outputError?(str: string, write: (str: string) => void): void;
214
215}
216
217type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';
218type HookEvent = 'preAction' | 'postAction';
219
220export interface OptionValues {
221 [key: string]: any;
222}
223
224export class Command {
225 args: string[];
226 processedArgs: any[];
227 commands: Command[];
228 parent: Command | null;
229
230 constructor(name?: string);
231
232 /**
233 * Set the program version to `str`.
234 *
235 * This method auto-registers the "-V, --version" flag
236 * which will print the version number when passed.
237 *
238 * You can optionally supply the flags and description to override the defaults.
239 */
240 version(str: string, flags?: string, description?: string): this;
241
242 /**
243 * Define a command, implemented using an action handler.
244 *
245 * @remarks
246 * The command description is supplied using `.description`, not as a parameter to `.command`.
247 *
248 * @example
249 * ```ts
250 * program
251 * .command('clone <source> [destination]')
252 * .description('clone a repository into a newly created directory')
253 * .action((source, destination) => {
254 * console.log('clone command called');
255 * });
256 * ```
257 *
258 * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
259 * @param opts - configuration options
260 * @returns new command
261 */
262 command(nameAndArgs: string, opts?: CommandOptions): ReturnType<this['createCommand']>;
263 /**
264 * Define a command, implemented in a separate executable file.
265 *
266 * @remarks
267 * The command description is supplied as the second parameter to `.command`.
268 *
269 * @example
270 * ```ts
271 * program
272 * .command('start <service>', 'start named service')
273 * .command('stop [service]', 'stop named service, or all if no name supplied');
274 * ```
275 *
276 * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
277 * @param description - description of executable command
278 * @param opts - configuration options
279 * @returns `this` command for chaining
280 */
281 command(nameAndArgs: string, description: string, opts?: ExecutableCommandOptions): this;
282
283 /**
284 * Factory routine to create a new unattached command.
285 *
286 * See .command() for creating an attached subcommand, which uses this routine to
287 * create the command. You can override createCommand to customise subcommands.
288 */
289 createCommand(name?: string): Command;
290
291 /**
292 * Add a prepared subcommand.
293 *
294 * See .command() for creating an attached subcommand which inherits settings from its parent.
295 *
296 * @returns `this` command for chaining
297 */
298 addCommand(cmd: Command, opts?: CommandOptions): this;
299
300 /**
301 * Factory routine to create a new unattached argument.
302 *
303 * See .argument() for creating an attached argument, which uses this routine to
304 * create the argument. You can override createArgument to return a custom argument.
305 */
306 createArgument(name: string, description?: string): Argument;
307
308 /**
309 * Define argument syntax for command.
310 *
311 * The default is that the argument is required, and you can explicitly
312 * indicate this with <> around the name. Put [] around the name for an optional argument.
313 *
314 * @example
315 * ```
316 * program.argument('<input-file>');
317 * program.argument('[output-file]');
318 * ```
319 *
320 * @returns `this` command for chaining
321 */
322 argument<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;
323 argument(name: string, description?: string, defaultValue?: unknown): this;
324
325 /**
326 * Define argument syntax for command, adding a prepared argument.
327 *
328 * @returns `this` command for chaining
329 */
330 addArgument(arg: Argument): this;
331
332 /**
333 * Define argument syntax for command, adding multiple at once (without descriptions).
334 *
335 * See also .argument().
336 *
337 * @example
338 * ```
339 * program.arguments('<cmd> [env]');
340 * ```
341 *
342 * @returns `this` command for chaining
343 */
344 arguments(names: string): this;
345
346 /**
347 * Override default decision whether to add implicit help command.
348 *
349 * @example
350 * ```
351 * addHelpCommand() // force on
352 * addHelpCommand(false); // force off
353 * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
354 * ```
355 *
356 * @returns `this` command for chaining
357 */
358 addHelpCommand(enableOrNameAndArgs?: string | boolean, description?: string): this;
359
360 /**
361 * Add hook for life cycle event.
362 */
363 hook(event: HookEvent, listener: (thisCommand: Command, actionCommand: Command) => void | Promise<void>): this;
364
365 /**
366 * Register callback to use as replacement for calling process.exit.
367 */
368 exitOverride(callback?: (err: CommanderError) => never|void): this;
369
370 /**
371 * You can customise the help with a subclass of Help by overriding createHelp,
372 * or by overriding Help properties using configureHelp().
373 */
374 createHelp(): Help;
375
376 /**
377 * You can customise the help by overriding Help properties using configureHelp(),
378 * or with a subclass of Help by overriding createHelp().
379 */
380 configureHelp(configuration: HelpConfiguration): this;
381 /** Get configuration */
382 configureHelp(): HelpConfiguration;
383
384 /**
385 * The default output goes to stdout and stderr. You can customise this for special
386 * applications. You can also customise the display of errors by overriding outputError.
387 *
388 * The configuration properties are all functions:
389 * ```
390 * // functions to change where being written, stdout and stderr
391 * writeOut(str)
392 * writeErr(str)
393 * // matching functions to specify width for wrapping help
394 * getOutHelpWidth()
395 * getErrHelpWidth()
396 * // functions based on what is being written out
397 * outputError(str, write) // used for displaying errors, and not used for displaying help
398 * ```
399 */
400 configureOutput(configuration: OutputConfiguration): this;
401 /** Get configuration */
402 configureOutput(): OutputConfiguration;
403
404 /**
405 * Copy settings that are useful to have in common across root command and subcommands.
406 *
407 * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
408 */
409 copyInheritedSettings(sourceCommand: Command): this;
410
411 /**
412 * Display the help or a custom message after an error occurs.
413 */
414 showHelpAfterError(displayHelp?: boolean | string): this;
415
416 /**
417 * Register callback `fn` for the command.
418 *
419 * @example
420 * ```
421 * program
422 * .command('help')
423 * .description('display verbose help')
424 * .action(function() {
425 * // output help here
426 * });
427 * ```
428 *
429 * @returns `this` command for chaining
430 */
431 action(fn: (...args: any[]) => void | Promise<void>): this;
432
433 /**
434 * Define option with `flags`, `description` and optional
435 * coercion `fn`.
436 *
437 * The `flags` string contains the short and/or long flags,
438 * separated by comma, a pipe or space. The following are all valid
439 * all will output this way when `--help` is used.
440 *
441 * "-p, --pepper"
442 * "-p|--pepper"
443 * "-p --pepper"
444 *
445 * @example
446 * ```
447 * // simple boolean defaulting to false
448 * program.option('-p, --pepper', 'add pepper');
449 *
450 * --pepper
451 * program.pepper
452 * // => Boolean
453 *
454 * // simple boolean defaulting to true
455 * program.option('-C, --no-cheese', 'remove cheese');
456 *
457 * program.cheese
458 * // => true
459 *
460 * --no-cheese
461 * program.cheese
462 * // => false
463 *
464 * // required argument
465 * program.option('-C, --chdir <path>', 'change the working directory');
466 *
467 * --chdir /tmp
468 * program.chdir
469 * // => "/tmp"
470 *
471 * // optional argument
472 * program.option('-c, --cheese [type]', 'add cheese [marble]');
473 * ```
474 *
475 * @returns `this` command for chaining
476 */
477 option(flags: string, description?: string, defaultValue?: string | boolean): this;
478 option<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;
479 /** @deprecated since v7, instead use choices or a custom function */
480 option(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean): this;
481
482 /**
483 * Define a required option, which must have a value after parsing. This usually means
484 * the option must be specified on the command line. (Otherwise the same as .option().)
485 *
486 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
487 */
488 requiredOption(flags: string, description?: string, defaultValue?: string | boolean): this;
489 requiredOption<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;
490 /** @deprecated since v7, instead use choices or a custom function */
491 requiredOption(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean): this;
492
493 /**
494 * Factory routine to create a new unattached option.
495 *
496 * See .option() for creating an attached option, which uses this routine to
497 * create the option. You can override createOption to return a custom option.
498 */
499
500 createOption(flags: string, description?: string): Option;
501
502 /**
503 * Add a prepared Option.
504 *
505 * See .option() and .requiredOption() for creating and attaching an option in a single call.
506 */
507 addOption(option: Option): this;
508
509 /**
510 * Whether to store option values as properties on command object,
511 * or store separately (specify false). In both cases the option values can be accessed using .opts().
512 *
513 * @returns `this` command for chaining
514 */
515 storeOptionsAsProperties<T extends OptionValues>(): this & T;
516 storeOptionsAsProperties<T extends OptionValues>(storeAsProperties: true): this & T;
517 storeOptionsAsProperties(storeAsProperties?: boolean): this;
518
519 /**
520 * Retrieve option value.
521 */
522 getOptionValue(key: string): any;
523
524 /**
525 * Store option value.
526 */
527 setOptionValue(key: string, value: unknown): this;
528
529 /**
530 * Alter parsing of short flags with optional values.
531 *
532 * @example
533 * ```
534 * // for `.option('-f,--flag [value]'):
535 * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour
536 * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
537 * ```
538 *
539 * @returns `this` command for chaining
540 */
541 combineFlagAndOptionalValue(combine?: boolean): this;
542
543 /**
544 * Allow unknown options on the command line.
545 *
546 * @returns `this` command for chaining
547 */
548 allowUnknownOption(allowUnknown?: boolean): this;
549
550 /**
551 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
552 *
553 * @returns `this` command for chaining
554 */
555 allowExcessArguments(allowExcess?: boolean): this;
556
557 /**
558 * Enable positional options. Positional means global options are specified before subcommands which lets
559 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
560 *
561 * The default behaviour is non-positional and global options may appear anywhere on the command line.
562 *
563 * @returns `this` command for chaining
564 */
565 enablePositionalOptions(positional?: boolean): this;
566
567 /**
568 * Pass through options that come after command-arguments rather than treat them as command-options,
569 * so actual command-options come before command-arguments. Turning this on for a subcommand requires
570 * positional options to have been enabled on the program (parent commands).
571 *
572 * The default behaviour is non-positional and options may appear before or after command-arguments.
573 *
574 * @returns `this` command for chaining
575 */
576 passThroughOptions(passThrough?: boolean): this;
577
578 /**
579 * Parse `argv`, setting options and invoking commands when defined.
580 *
581 * The default expectation is that the arguments are from node and have the application as argv[0]
582 * and the script being run in argv[1], with user parameters after that.
583 *
584 * @example
585 * ```
586 * program.parse(process.argv);
587 * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
588 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
589 * ```
590 *
591 * @returns `this` command for chaining
592 */
593 parse(argv?: string[], options?: ParseOptions): this;
594
595 /**
596 * Parse `argv`, setting options and invoking commands when defined.
597 *
598 * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
599 *
600 * The default expectation is that the arguments are from node and have the application as argv[0]
601 * and the script being run in argv[1], with user parameters after that.
602 *
603 * @example
604 * ```
605 * program.parseAsync(process.argv);
606 * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
607 * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
608 * ```
609 *
610 * @returns Promise
611 */
612 parseAsync(argv?: string[], options?: ParseOptions): Promise<this>;
613
614 /**
615 * Parse options from `argv` removing known options,
616 * and return argv split into operands and unknown arguments.
617 *
618 * argv => operands, unknown
619 * --known kkk op => [op], []
620 * op --known kkk => [op], []
621 * sub --unknown uuu op => [sub], [--unknown uuu op]
622 * sub -- --unknown uuu op => [sub --unknown uuu op], []
623 */
624 parseOptions(argv: string[]): ParseOptionsResult;
625
626 /**
627 * Return an object containing options as key-value pairs
628 */
629 opts<T extends OptionValues>(): T;
630
631 /**
632 * Set the description.
633 *
634 * @returns `this` command for chaining
635 */
636
637 description(str: string): this;
638 /** @deprecated since v8, instead use .argument to add command argument with description */
639 description(str: string, argsDescription: {[argName: string]: string}): this;
640 /**
641 * Get the description.
642 */
643 description(): string;
644
645 /**
646 * Set an alias for the command.
647 *
648 * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
649 *
650 * @returns `this` command for chaining
651 */
652 alias(alias: string): this;
653 /**
654 * Get alias for the command.
655 */
656 alias(): string;
657
658 /**
659 * Set aliases for the command.
660 *
661 * Only the first alias is shown in the auto-generated help.
662 *
663 * @returns `this` command for chaining
664 */
665 aliases(aliases: string[]): this;
666 /**
667 * Get aliases for the command.
668 */
669 aliases(): string[];
670
671 /**
672 * Set the command usage.
673 *
674 * @returns `this` command for chaining
675 */
676 usage(str: string): this;
677 /**
678 * Get the command usage.
679 */
680 usage(): string;
681
682 /**
683 * Set the name of the command.
684 *
685 * @returns `this` command for chaining
686 */
687 name(str: string): this;
688 /**
689 * Get the name of the command.
690 */
691 name(): string;
692
693 /**
694 * Output help information for this command.
695 *
696 * Outputs built-in help, and custom text added using `.addHelpText()`.
697 *
698 */
699 outputHelp(context?: HelpContext): void;
700 /** @deprecated since v7 */
701 outputHelp(cb?: (str: string) => string): void;
702
703 /**
704 * Return command help documentation.
705 */
706 helpInformation(context?: HelpContext): string;
707
708 /**
709 * You can pass in flags and a description to override the help
710 * flags and help description for your command. Pass in false
711 * to disable the built-in help option.
712 */
713 helpOption(flags?: string | boolean, description?: string): this;
714
715 /**
716 * Output help information and exit.
717 *
718 * Outputs built-in help, and custom text added using `.addHelpText()`.
719 */
720 help(context?: HelpContext): never;
721 /** @deprecated since v7 */
722 help(cb?: (str: string) => string): never;
723
724 /**
725 * Add additional text to be displayed with the built-in help.
726 *
727 * Position is 'before' or 'after' to affect just this command,
728 * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
729 */
730 addHelpText(position: AddHelpTextPosition, text: string): this;
731 addHelpText(position: AddHelpTextPosition, text: (context: AddHelpTextContext) => string): this;
732
733 /**
734 * Add a listener (callback) for when events occur. (Implemented using EventEmitter.)
735 */
736 on(event: string | symbol, listener: (...args: any[]) => void): this;
737}
738
739export interface CommandOptions {
740 hidden?: boolean;
741 isDefault?: boolean;
742 /** @deprecated since v7, replaced by hidden */
743 noHelp?: boolean;
744}
745export interface ExecutableCommandOptions extends CommandOptions {
746 executableFile?: string;
747}
748
749export interface ParseOptionsResult {
750 operands: string[];
751 unknown: string[];
752}
753
754export function createCommand(name?: string): Command;
755export function createOption(flags: string, description?: string): Option;
756export function createArgument(name: string, description?: string): Argument;
757
758export const program: Command;
759
\No newline at end of file