index.d.ts 32 KB

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