index.d.ts 29 KB

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