index.d.ts 28 KB

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