index.d.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  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. /* eslint-disable @typescript-eslint/no-explicit-any */
  4. // This is a trick to encourage editor to suggest the known literals while still
  5. // allowing any BaseType value.
  6. // References:
  7. // - https://github.com/microsoft/TypeScript/issues/29729
  8. // - https://github.com/sindresorhus/type-fest/blob/main/source/literal-union.d.ts
  9. // - https://github.com/sindresorhus/type-fest/blob/main/source/primitive.d.ts
  10. type LiteralUnion<LiteralType, BaseType extends string | number> =
  11. | LiteralType
  12. | (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. */
  24. constructor(exitCode: number, code: string, message: string);
  25. }
  26. export class InvalidArgumentError extends CommanderError {
  27. /**
  28. * Constructs the InvalidArgumentError class
  29. * @param message - explanation of why argument is invalid
  30. */
  31. constructor(message: string);
  32. }
  33. export { InvalidArgumentError as InvalidOptionArgumentError }; // deprecated old name
  34. export interface ErrorOptions {
  35. // optional parameter for error()
  36. /** an id string representing the error */
  37. code?: string;
  38. /** suggested exit code which could be used with process.exit */
  39. exitCode?: number;
  40. }
  41. export class Argument {
  42. description: string;
  43. required: boolean;
  44. variadic: boolean;
  45. defaultValue?: any;
  46. defaultValueDescription?: string;
  47. parseArg?: <T>(value: string, previous: T) => T;
  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. helpGroupHeading?: string;
  98. constructor(flags: string, description?: string);
  99. /**
  100. * Set the default value, and optionally supply the description to be displayed in the help.
  101. */
  102. default(value: unknown, description?: string): this;
  103. /**
  104. * Preset to use when option used without option-argument, especially optional but also boolean and negated.
  105. * The custom processing (parseArg) is called.
  106. *
  107. * @example
  108. * ```ts
  109. * new Option('--color').default('GREYSCALE').preset('RGB');
  110. * new Option('--donate [amount]').preset('20').argParser(parseFloat);
  111. * ```
  112. */
  113. preset(arg: unknown): this;
  114. /**
  115. * Add option name(s) that conflict with this option.
  116. * An error will be displayed if conflicting options are found during parsing.
  117. *
  118. * @example
  119. * ```ts
  120. * new Option('--rgb').conflicts('cmyk');
  121. * new Option('--js').conflicts(['ts', 'jsx']);
  122. * ```
  123. */
  124. conflicts(names: string | string[]): this;
  125. /**
  126. * Specify implied option values for when this option is set and the implied options are not.
  127. *
  128. * The custom processing (parseArg) is not called on the implied values.
  129. *
  130. * @example
  131. * program
  132. * .addOption(new Option('--log', 'write logging information to file'))
  133. * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
  134. */
  135. implies(optionValues: OptionValues): this;
  136. /**
  137. * Set environment variable to check for option value.
  138. *
  139. * An environment variables is only used if when processed the current option value is
  140. * undefined, or the source of the current value is 'default' or 'config' or 'env'.
  141. */
  142. env(name: string): this;
  143. /**
  144. * Set the custom handler for processing CLI option arguments into option values.
  145. */
  146. argParser<T>(fn: (value: string, previous: T) => T): this;
  147. /**
  148. * Whether the option is mandatory and must have a value after parsing.
  149. */
  150. makeOptionMandatory(mandatory?: boolean): this;
  151. /**
  152. * Hide option in help.
  153. */
  154. hideHelp(hide?: boolean): this;
  155. /**
  156. * Only allow option value to be one of choices.
  157. */
  158. choices(values: readonly string[]): this;
  159. /**
  160. * Return option name.
  161. */
  162. name(): string;
  163. /**
  164. * Return option name, in a camelcase format that can be used
  165. * as an object attribute key.
  166. */
  167. attributeName(): string;
  168. /**
  169. * Set the help group heading.
  170. */
  171. helpGroup(heading: string): this;
  172. /**
  173. * Return whether a boolean option.
  174. *
  175. * Options are one of boolean, negated, required argument, or optional argument.
  176. */
  177. isBoolean(): boolean;
  178. }
  179. export class Help {
  180. /** output helpWidth, long lines are wrapped to fit */
  181. helpWidth?: number;
  182. minWidthToWrap: number;
  183. sortSubcommands: boolean;
  184. sortOptions: boolean;
  185. showGlobalOptions: boolean;
  186. constructor();
  187. /*
  188. * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
  189. * and just before calling `formatHelp()`.
  190. *
  191. * Commander just uses the helpWidth and the others are provided for subclasses.
  192. */
  193. prepareContext(contextOptions: {
  194. error?: boolean;
  195. helpWidth?: number;
  196. outputHasColors?: boolean;
  197. }): void;
  198. /** Get the command term to show in the list of subcommands. */
  199. subcommandTerm(cmd: Command): string;
  200. /** Get the command summary to show in the list of subcommands. */
  201. subcommandDescription(cmd: Command): string;
  202. /** Get the option term to show in the list of options. */
  203. optionTerm(option: Option): string;
  204. /** Get the option description to show in the list of options. */
  205. optionDescription(option: Option): string;
  206. /** Get the argument term to show in the list of arguments. */
  207. argumentTerm(argument: Argument): string;
  208. /** Get the argument description to show in the list of arguments. */
  209. argumentDescription(argument: Argument): string;
  210. /** Get the command usage to be displayed at the top of the built-in help. */
  211. commandUsage(cmd: Command): string;
  212. /** Get the description for the command. */
  213. commandDescription(cmd: Command): string;
  214. /** Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. */
  215. visibleCommands(cmd: Command): Command[];
  216. /** Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. */
  217. visibleOptions(cmd: Command): Option[];
  218. /** Get an array of the visible global options. (Not including help.) */
  219. visibleGlobalOptions(cmd: Command): Option[];
  220. /** Get an array of the arguments which have descriptions. */
  221. visibleArguments(cmd: Command): Argument[];
  222. /** Get the longest command term length. */
  223. longestSubcommandTermLength(cmd: Command, helper: Help): number;
  224. /** Get the longest option term length. */
  225. longestOptionTermLength(cmd: Command, helper: Help): number;
  226. /** Get the longest global option term length. */
  227. longestGlobalOptionTermLength(cmd: Command, helper: Help): number;
  228. /** Get the longest argument term length. */
  229. longestArgumentTermLength(cmd: Command, helper: Help): number;
  230. /** Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations. */
  231. displayWidth(str: string): number;
  232. /** Style the titles. Called with 'Usage:', 'Options:', etc. */
  233. styleTitle(title: string): string;
  234. /** Usage: <str> */
  235. styleUsage(str: string): string;
  236. /** Style for command name in usage string. */
  237. styleCommandText(str: string): string;
  238. styleCommandDescription(str: string): string;
  239. styleOptionDescription(str: string): string;
  240. styleSubcommandDescription(str: string): string;
  241. styleArgumentDescription(str: string): string;
  242. /** Base style used by descriptions. */
  243. styleDescriptionText(str: string): string;
  244. styleOptionTerm(str: string): string;
  245. styleSubcommandTerm(str: string): string;
  246. styleArgumentTerm(str: string): string;
  247. /** Base style used in terms and usage for options. */
  248. styleOptionText(str: string): string;
  249. /** Base style used in terms and usage for subcommands. */
  250. styleSubcommandText(str: string): string;
  251. /** Base style used in terms and usage for arguments. */
  252. styleArgumentText(str: string): string;
  253. /** Calculate the pad width from the maximum term length. */
  254. padWidth(cmd: Command, helper: Help): number;
  255. /**
  256. * Wrap a string at whitespace, preserving existing line breaks.
  257. * Wrapping is skipped if the width is less than `minWidthToWrap`.
  258. */
  259. boxWrap(str: string, width: number): string;
  260. /** Detect manually wrapped and indented strings by checking for line break followed by whitespace. */
  261. preformatted(str: string): boolean;
  262. /**
  263. * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
  264. *
  265. * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
  266. * TTT DDD DDDD
  267. * DD DDD
  268. */
  269. formatItem(
  270. term: string,
  271. termWidth: number,
  272. description: string,
  273. helper: Help,
  274. ): string;
  275. /**
  276. * Format a list of items, given a heading and an array of formatted items.
  277. */
  278. formatItemList(heading: string, items: string[], helper: Help): string[];
  279. /**
  280. * Group items by their help group heading.
  281. */
  282. groupItems<T extends Command | Option>(
  283. unsortedItems: T[],
  284. visibleItems: T[],
  285. getGroup: (item: T) => string,
  286. ): Map<string, T[]>;
  287. /** Generate the built-in help text. */
  288. formatHelp(cmd: Command, helper: Help): string;
  289. }
  290. export type HelpConfiguration = Partial<Help>;
  291. export interface ParseOptions {
  292. from: 'node' | 'electron' | 'user';
  293. }
  294. export interface HelpContext {
  295. // optional parameter for .help() and .outputHelp()
  296. error: boolean;
  297. }
  298. export interface AddHelpTextContext {
  299. // passed to text function used with .addHelpText()
  300. error: boolean;
  301. command: Command;
  302. }
  303. export interface OutputConfiguration {
  304. writeOut?(str: string): void;
  305. writeErr?(str: string): void;
  306. outputError?(str: string, write: (str: string) => void): void;
  307. getOutHelpWidth?(): number;
  308. getErrHelpWidth?(): number;
  309. getOutHasColors?(): boolean;
  310. getErrHasColors?(): boolean;
  311. stripColor?(str: string): string;
  312. }
  313. export type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';
  314. export type HookEvent = 'preSubcommand' | 'preAction' | 'postAction';
  315. // The source is a string so author can define their own too.
  316. export type OptionValueSource =
  317. | LiteralUnion<'default' | 'config' | 'env' | 'cli' | 'implied', string>
  318. | undefined;
  319. export type OptionValues = Record<string, any>;
  320. export class Command {
  321. args: string[];
  322. processedArgs: any[];
  323. readonly commands: readonly Command[];
  324. readonly options: readonly Option[];
  325. readonly registeredArguments: readonly Argument[];
  326. parent: Command | null;
  327. constructor(name?: string);
  328. /**
  329. * Set the program version to `str`.
  330. *
  331. * This method auto-registers the "-V, --version" flag
  332. * which will print the version number when passed.
  333. *
  334. * You can optionally supply the flags and description to override the defaults.
  335. */
  336. version(str: string, flags?: string, description?: string): this;
  337. /**
  338. * Get the program version.
  339. */
  340. version(): string | undefined;
  341. /**
  342. * Define a command, implemented using an action handler.
  343. *
  344. * @remarks
  345. * The command description is supplied using `.description`, not as a parameter to `.command`.
  346. *
  347. * @example
  348. * ```ts
  349. * program
  350. * .command('clone <source> [destination]')
  351. * .description('clone a repository into a newly created directory')
  352. * .action((source, destination) => {
  353. * console.log('clone command called');
  354. * });
  355. * ```
  356. *
  357. * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
  358. * @param opts - configuration options
  359. * @returns new command
  360. */
  361. command(
  362. nameAndArgs: string,
  363. opts?: CommandOptions,
  364. ): ReturnType<this['createCommand']>;
  365. /**
  366. * Define a command, implemented in a separate executable file.
  367. *
  368. * @remarks
  369. * The command description is supplied as the second parameter to `.command`.
  370. *
  371. * @example
  372. * ```ts
  373. * program
  374. * .command('start <service>', 'start named service')
  375. * .command('stop [service]', 'stop named service, or all if no name supplied');
  376. * ```
  377. *
  378. * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
  379. * @param description - description of executable command
  380. * @param opts - configuration options
  381. * @returns `this` command for chaining
  382. */
  383. command(
  384. nameAndArgs: string,
  385. description: string,
  386. opts?: ExecutableCommandOptions,
  387. ): this;
  388. /**
  389. * Factory routine to create a new unattached command.
  390. *
  391. * See .command() for creating an attached subcommand, which uses this routine to
  392. * create the command. You can override createCommand to customise subcommands.
  393. */
  394. createCommand(name?: string): Command;
  395. /**
  396. * Add a prepared subcommand.
  397. *
  398. * See .command() for creating an attached subcommand which inherits settings from its parent.
  399. *
  400. * @returns `this` command for chaining
  401. */
  402. addCommand(cmd: Command, opts?: CommandOptions): this;
  403. /**
  404. * Factory routine to create a new unattached argument.
  405. *
  406. * See .argument() for creating an attached argument, which uses this routine to
  407. * create the argument. You can override createArgument to return a custom argument.
  408. */
  409. createArgument(name: string, description?: string): Argument;
  410. /**
  411. * Define argument syntax for command.
  412. *
  413. * The default is that the argument is required, and you can explicitly
  414. * indicate this with <> around the name. Put [] around the name for an optional argument.
  415. *
  416. * @example
  417. * ```
  418. * program.argument('<input-file>');
  419. * program.argument('[output-file]');
  420. * ```
  421. *
  422. * @returns `this` command for chaining
  423. */
  424. argument<T>(
  425. flags: string,
  426. description: string,
  427. parseArg: (value: string, previous: T) => T,
  428. defaultValue?: T,
  429. ): this;
  430. argument(name: string, description?: string, defaultValue?: unknown): this;
  431. /**
  432. * Define argument syntax for command, adding a prepared argument.
  433. *
  434. * @returns `this` command for chaining
  435. */
  436. addArgument(arg: Argument): this;
  437. /**
  438. * Define argument syntax for command, adding multiple at once (without descriptions).
  439. *
  440. * See also .argument().
  441. *
  442. * @example
  443. * ```
  444. * program.arguments('<cmd> [env]');
  445. * ```
  446. *
  447. * @returns `this` command for chaining
  448. */
  449. arguments(names: string): this;
  450. /**
  451. * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
  452. *
  453. * @example
  454. * ```ts
  455. * program.helpCommand('help [cmd]');
  456. * program.helpCommand('help [cmd]', 'show help');
  457. * program.helpCommand(false); // suppress default help command
  458. * program.helpCommand(true); // add help command even if no subcommands
  459. * ```
  460. */
  461. helpCommand(nameAndArgs: string, description?: string): this;
  462. helpCommand(enable: boolean): this;
  463. /**
  464. * Add prepared custom help command.
  465. */
  466. addHelpCommand(cmd: Command): this;
  467. /** @deprecated since v12, instead use helpCommand */
  468. addHelpCommand(nameAndArgs: string, description?: string): this;
  469. /** @deprecated since v12, instead use helpCommand */
  470. addHelpCommand(enable?: boolean): this;
  471. /**
  472. * Add hook for life cycle event.
  473. */
  474. hook(
  475. event: HookEvent,
  476. listener: (
  477. thisCommand: Command,
  478. actionCommand: Command,
  479. ) => void | Promise<void>,
  480. ): this;
  481. /**
  482. * Register callback to use as replacement for calling process.exit.
  483. */
  484. exitOverride(callback?: (err: CommanderError) => never | void): this;
  485. /**
  486. * Display error message and exit (or call exitOverride).
  487. */
  488. error(message: string, errorOptions?: ErrorOptions): never;
  489. /**
  490. * You can customise the help with a subclass of Help by overriding createHelp,
  491. * or by overriding Help properties using configureHelp().
  492. */
  493. createHelp(): Help;
  494. /**
  495. * You can customise the help by overriding Help properties using configureHelp(),
  496. * or with a subclass of Help by overriding createHelp().
  497. */
  498. configureHelp(configuration: HelpConfiguration): this;
  499. /** Get configuration */
  500. configureHelp(): HelpConfiguration;
  501. /**
  502. * The default output goes to stdout and stderr. You can customise this for special
  503. * applications. You can also customise the display of errors by overriding outputError.
  504. *
  505. * The configuration properties are all functions:
  506. * ```
  507. * // functions to change where being written, stdout and stderr
  508. * writeOut(str)
  509. * writeErr(str)
  510. * // matching functions to specify width for wrapping help
  511. * getOutHelpWidth()
  512. * getErrHelpWidth()
  513. * // functions based on what is being written out
  514. * outputError(str, write) // used for displaying errors, and not used for displaying help
  515. * ```
  516. */
  517. configureOutput(configuration: OutputConfiguration): this;
  518. /** Get configuration */
  519. configureOutput(): OutputConfiguration;
  520. /**
  521. * Copy settings that are useful to have in common across root command and subcommands.
  522. *
  523. * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
  524. */
  525. copyInheritedSettings(sourceCommand: Command): this;
  526. /**
  527. * Display the help or a custom message after an error occurs.
  528. */
  529. showHelpAfterError(displayHelp?: boolean | string): this;
  530. /**
  531. * Display suggestion of similar commands for unknown commands, or options for unknown options.
  532. */
  533. showSuggestionAfterError(displaySuggestion?: boolean): this;
  534. /**
  535. * Register callback `fn` for the command.
  536. *
  537. * @example
  538. * ```
  539. * program
  540. * .command('serve')
  541. * .description('start service')
  542. * .action(function() {
  543. * // do work here
  544. * });
  545. * ```
  546. *
  547. * @returns `this` command for chaining
  548. */
  549. action(fn: (this: this, ...args: any[]) => void | Promise<void>): this;
  550. /**
  551. * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
  552. *
  553. * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
  554. * option-argument is indicated by `<>` and an optional option-argument by `[]`.
  555. *
  556. * See the README for more details, and see also addOption() and requiredOption().
  557. *
  558. * @example
  559. *
  560. * ```js
  561. * program
  562. * .option('-p, --pepper', 'add pepper')
  563. * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
  564. * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
  565. * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
  566. * ```
  567. *
  568. * @returns `this` command for chaining
  569. */
  570. option(
  571. flags: string,
  572. description?: string,
  573. defaultValue?: string | boolean | string[],
  574. ): this;
  575. option<T>(
  576. flags: string,
  577. description: string,
  578. parseArg: (value: string, previous: T) => T,
  579. defaultValue?: T,
  580. ): this;
  581. /** @deprecated since v7, instead use choices or a custom function */
  582. option(
  583. flags: string,
  584. description: string,
  585. regexp: RegExp,
  586. defaultValue?: string | boolean | string[],
  587. ): this;
  588. /**
  589. * Define a required option, which must have a value after parsing. This usually means
  590. * the option must be specified on the command line. (Otherwise the same as .option().)
  591. *
  592. * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
  593. */
  594. requiredOption(
  595. flags: string,
  596. description?: string,
  597. defaultValue?: string | boolean | string[],
  598. ): this;
  599. requiredOption<T>(
  600. flags: string,
  601. description: string,
  602. parseArg: (value: string, previous: T) => T,
  603. defaultValue?: T,
  604. ): this;
  605. /** @deprecated since v7, instead use choices or a custom function */
  606. requiredOption(
  607. flags: string,
  608. description: string,
  609. regexp: RegExp,
  610. defaultValue?: string | boolean | string[],
  611. ): this;
  612. /**
  613. * Factory routine to create a new unattached option.
  614. *
  615. * See .option() for creating an attached option, which uses this routine to
  616. * create the option. You can override createOption to return a custom option.
  617. */
  618. createOption(flags: string, description?: string): Option;
  619. /**
  620. * Add a prepared Option.
  621. *
  622. * See .option() and .requiredOption() for creating and attaching an option in a single call.
  623. */
  624. addOption(option: Option): this;
  625. /**
  626. * Whether to store option values as properties on command object,
  627. * or store separately (specify false). In both cases the option values can be accessed using .opts().
  628. *
  629. * @returns `this` command for chaining
  630. */
  631. storeOptionsAsProperties<T extends OptionValues>(): this & T;
  632. storeOptionsAsProperties<T extends OptionValues>(
  633. storeAsProperties: true,
  634. ): this & T;
  635. storeOptionsAsProperties(storeAsProperties?: boolean): this;
  636. /**
  637. * Retrieve option value.
  638. */
  639. getOptionValue(key: string): any;
  640. /**
  641. * Store option value.
  642. */
  643. setOptionValue(key: string, value: unknown): this;
  644. /**
  645. * Store option value and where the value came from.
  646. */
  647. setOptionValueWithSource(
  648. key: string,
  649. value: unknown,
  650. source: OptionValueSource,
  651. ): this;
  652. /**
  653. * Get source of option value.
  654. */
  655. getOptionValueSource(key: string): OptionValueSource | undefined;
  656. /**
  657. * Get source of option value. See also .optsWithGlobals().
  658. */
  659. getOptionValueSourceWithGlobals(key: string): OptionValueSource | undefined;
  660. /**
  661. * Alter parsing of short flags with optional values.
  662. *
  663. * @example
  664. * ```
  665. * // for `.option('-f,--flag [value]'):
  666. * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour
  667. * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
  668. * ```
  669. *
  670. * @returns `this` command for chaining
  671. */
  672. combineFlagAndOptionalValue(combine?: boolean): this;
  673. /**
  674. * Allow unknown options on the command line.
  675. *
  676. * @returns `this` command for chaining
  677. */
  678. allowUnknownOption(allowUnknown?: boolean): this;
  679. /**
  680. * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
  681. *
  682. * @returns `this` command for chaining
  683. */
  684. allowExcessArguments(allowExcess?: boolean): this;
  685. /**
  686. * Enable positional options. Positional means global options are specified before subcommands which lets
  687. * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
  688. *
  689. * The default behaviour is non-positional and global options may appear anywhere on the command line.
  690. *
  691. * @returns `this` command for chaining
  692. */
  693. enablePositionalOptions(positional?: boolean): this;
  694. /**
  695. * Pass through options that come after command-arguments rather than treat them as command-options,
  696. * so actual command-options come before command-arguments. Turning this on for a subcommand requires
  697. * positional options to have been enabled on the program (parent commands).
  698. *
  699. * The default behaviour is non-positional and options may appear before or after command-arguments.
  700. *
  701. * @returns `this` command for chaining
  702. */
  703. passThroughOptions(passThrough?: boolean): this;
  704. /**
  705. * Parse `argv`, setting options and invoking commands when defined.
  706. *
  707. * Use parseAsync instead of parse if any of your action handlers are async.
  708. *
  709. * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
  710. *
  711. * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
  712. * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
  713. * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
  714. * - `'user'`: just user arguments
  715. *
  716. * @example
  717. * ```
  718. * program.parse(); // parse process.argv and auto-detect electron and special node flags
  719. * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
  720. * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
  721. * ```
  722. *
  723. * @returns `this` command for chaining
  724. */
  725. parse(argv?: readonly string[], parseOptions?: ParseOptions): this;
  726. /**
  727. * Parse `argv`, setting options and invoking commands when defined.
  728. *
  729. * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
  730. *
  731. * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
  732. * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
  733. * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
  734. * - `'user'`: just user arguments
  735. *
  736. * @example
  737. * ```
  738. * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
  739. * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
  740. * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
  741. * ```
  742. *
  743. * @returns Promise
  744. */
  745. parseAsync(
  746. argv?: readonly string[],
  747. parseOptions?: ParseOptions,
  748. ): Promise<this>;
  749. /**
  750. * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
  751. * Not usually called directly, but available for subclasses to save their custom state.
  752. *
  753. * This is called in a lazy way. Only commands used in parsing chain will have state saved.
  754. */
  755. saveStateBeforeParse(): void;
  756. /**
  757. * Restore state before parse for calls after the first.
  758. * Not usually called directly, but available for subclasses to save their custom state.
  759. *
  760. * This is called in a lazy way. Only commands used in parsing chain will have state restored.
  761. */
  762. restoreStateBeforeParse(): void;
  763. /**
  764. * Parse options from `argv` removing known options,
  765. * and return argv split into operands and unknown arguments.
  766. *
  767. * Side effects: modifies command by storing options. Does not reset state if called again.
  768. *
  769. * argv => operands, unknown
  770. * --known kkk op => [op], []
  771. * op --known kkk => [op], []
  772. * sub --unknown uuu op => [sub], [--unknown uuu op]
  773. * sub -- --unknown uuu op => [sub --unknown uuu op], []
  774. */
  775. parseOptions(argv: string[]): ParseOptionsResult;
  776. /**
  777. * Return an object containing local option values as key-value pairs
  778. */
  779. opts<T extends OptionValues>(): T;
  780. /**
  781. * Return an object containing merged local and global option values as key-value pairs.
  782. */
  783. optsWithGlobals<T extends OptionValues>(): T;
  784. /**
  785. * Set the description.
  786. *
  787. * @returns `this` command for chaining
  788. */
  789. description(str: string): this;
  790. /** @deprecated since v8, instead use .argument to add command argument with description */
  791. description(str: string, argsDescription: Record<string, string>): this;
  792. /**
  793. * Get the description.
  794. */
  795. description(): string;
  796. /**
  797. * Set the summary. Used when listed as subcommand of parent.
  798. *
  799. * @returns `this` command for chaining
  800. */
  801. summary(str: string): this;
  802. /**
  803. * Get the summary.
  804. */
  805. summary(): string;
  806. /**
  807. * Set an alias for the command.
  808. *
  809. * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
  810. *
  811. * @returns `this` command for chaining
  812. */
  813. alias(alias: string): this;
  814. /**
  815. * Get alias for the command.
  816. */
  817. alias(): string;
  818. /**
  819. * Set aliases for the command.
  820. *
  821. * Only the first alias is shown in the auto-generated help.
  822. *
  823. * @returns `this` command for chaining
  824. */
  825. aliases(aliases: readonly string[]): this;
  826. /**
  827. * Get aliases for the command.
  828. */
  829. aliases(): string[];
  830. /**
  831. * Set the command usage.
  832. *
  833. * @returns `this` command for chaining
  834. */
  835. usage(str: string): this;
  836. /**
  837. * Get the command usage.
  838. */
  839. usage(): string;
  840. /**
  841. * Set the name of the command.
  842. *
  843. * @returns `this` command for chaining
  844. */
  845. name(str: string): this;
  846. /**
  847. * Get the name of the command.
  848. */
  849. name(): string;
  850. /**
  851. * Set the name of the command from script filename, such as process.argv[1],
  852. * or require.main.filename, or __filename.
  853. *
  854. * (Used internally and public although not documented in README.)
  855. *
  856. * @example
  857. * ```ts
  858. * program.nameFromFilename(require.main.filename);
  859. * ```
  860. *
  861. * @returns `this` command for chaining
  862. */
  863. nameFromFilename(filename: string): this;
  864. /**
  865. * Set the directory for searching for executable subcommands of this command.
  866. *
  867. * @example
  868. * ```ts
  869. * program.executableDir(__dirname);
  870. * // or
  871. * program.executableDir('subcommands');
  872. * ```
  873. *
  874. * @returns `this` command for chaining
  875. */
  876. executableDir(path: string): this;
  877. /**
  878. * Get the executable search directory.
  879. */
  880. executableDir(): string | null;
  881. /**
  882. * Set the help group heading for this subcommand in parent command's help.
  883. *
  884. * @returns `this` command for chaining
  885. */
  886. helpGroup(heading: string): this;
  887. /**
  888. * Get the help group heading for this subcommand in parent command's help.
  889. */
  890. helpGroup(): string;
  891. /**
  892. * Set the default help group heading for subcommands added to this command.
  893. * (This does not override a group set directly on the subcommand using .helpGroup().)
  894. *
  895. * @example
  896. * program.commandsGroup('Development Commands:);
  897. * program.command('watch')...
  898. * program.command('lint')...
  899. * ...
  900. *
  901. * @returns `this` command for chaining
  902. */
  903. commandsGroup(heading: string): this;
  904. /**
  905. * Get the default help group heading for subcommands added to this command.
  906. */
  907. commandsGroup(): string;
  908. /**
  909. * Set the default help group heading for options added to this command.
  910. * (This does not override a group set directly on the option using .helpGroup().)
  911. *
  912. * @example
  913. * program
  914. * .optionsGroup('Development Options:')
  915. * .option('-d, --debug', 'output extra debugging')
  916. * .option('-p, --profile', 'output profiling information')
  917. *
  918. * @returns `this` command for chaining
  919. */
  920. optionsGroup(heading: string): this;
  921. /**
  922. * Get the default help group heading for options added to this command.
  923. */
  924. optionsGroup(): string;
  925. /**
  926. * Output help information for this command.
  927. *
  928. * Outputs built-in help, and custom text added using `.addHelpText()`.
  929. *
  930. */
  931. outputHelp(context?: HelpContext): void;
  932. /** @deprecated since v7 */
  933. outputHelp(cb?: (str: string) => string): void;
  934. /**
  935. * Return command help documentation.
  936. */
  937. helpInformation(context?: HelpContext): string;
  938. /**
  939. * You can pass in flags and a description to override the help
  940. * flags and help description for your command. Pass in false
  941. * to disable the built-in help option.
  942. */
  943. helpOption(flags?: string | boolean, description?: string): this;
  944. /**
  945. * Supply your own option to use for the built-in help option.
  946. * This is an alternative to using helpOption() to customise the flags and description etc.
  947. */
  948. addHelpOption(option: Option): this;
  949. /**
  950. * Output help information and exit.
  951. *
  952. * Outputs built-in help, and custom text added using `.addHelpText()`.
  953. */
  954. help(context?: HelpContext): never;
  955. /** @deprecated since v7 */
  956. help(cb?: (str: string) => string): never;
  957. /**
  958. * Add additional text to be displayed with the built-in help.
  959. *
  960. * Position is 'before' or 'after' to affect just this command,
  961. * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
  962. */
  963. addHelpText(position: AddHelpTextPosition, text: string): this;
  964. addHelpText(
  965. position: AddHelpTextPosition,
  966. text: (context: AddHelpTextContext) => string,
  967. ): this;
  968. /**
  969. * Add a listener (callback) for when events occur. (Implemented using EventEmitter.)
  970. */
  971. on(event: string | symbol, listener: (...args: any[]) => void): this;
  972. }
  973. export interface CommandOptions {
  974. hidden?: boolean;
  975. isDefault?: boolean;
  976. /** @deprecated since v7, replaced by hidden */
  977. noHelp?: boolean;
  978. }
  979. export interface ExecutableCommandOptions extends CommandOptions {
  980. executableFile?: string;
  981. }
  982. export interface ParseOptionsResult {
  983. operands: string[];
  984. unknown: string[];
  985. }
  986. export function createCommand(name?: string): Command;
  987. export function createOption(flags: string, description?: string): Option;
  988. export function createArgument(name: string, description?: string): Argument;
  989. export const program: Command;