tis-cli前端项目快速搭建命令行工具
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

763 lines
24 KiB

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