UNPKG

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