UNPKG

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