Class CommandBuilder<Args, Opts>

Wrapper around the

See

Command class, for more intuitive construction.

Type Parameters

  • Args extends Any[] = unknown[]

  • Opts extends OptionValues = OptionValues

Hierarchy

  • CommandBuilder

Constructors

Properties

Accessors

Methods

action addHelpCommand addHelpText addUtilCommands alias aliases allowExcessArguments allowUnknownOption appData argument assertCommandNameNotReserved assertNoDuplicateCommandNames assertNoDuplicateOptionNames assertPresetArgsOptional assertValidArguments assertValidOptions assertValidPreset assignMissingOptionFlags assignSubCommandAliases autoAssignMissingOptionFlags autoAssignSubCommandAliases combineVariadicArgs command config configureHelp debugLogArgsOpts deleteDataFile description enableBuiltinOptions enablePositionalOptions errorHandler executableDir exitOverride getActionHandler getAlias getAliases getAncestors getAncestorsIterator getChildren getChildrenIterator getDescription getExecutableDir getGlobalOptions getHelpInformation getOptionValue getOptionValueSource getOptionValueSourceWithGlobals getOptsWithGlobals getOwnAndGlobalOptions getParsedValidArgsOptsWithPresets getParsedValidArgsWithPresets getParsedValidOptsWithPresets getPrefixArray getPrefixString getPresetArgsAndOpts getSiblings getSiblingsIterator getSummary getVersion globalOption handleOutputOptions hasIdenticalParentOption hideGlobalOptions hideOptionsWithDefaultOrNoValueOrArePresets hook inheritParentHiddenGlobals initializeActionWrapper initializeHelp nativeCommand option outputDebugMessage outputError outputHelp padArgsWithUndefinedUntilExpectedLength parse parseArguments parseAsync parseOptions passThroughOptions preset presetsEnabled setDataFilepath setOptionValue setOptionValueWithSource setRecommended showHelpAfterError showSuggestionAfterError throwCommanderError throwRatherThanExitProcess unhideGlobalOptions usage usageExamples version

Constructors

Properties

$: Command<[], {}>

Type declaration

    features: CommandFeatureSelector = ...
    meta: CommandBuilderMetaData<Args> = ...
    parent: null | CommandBuilder<unknown[], OptionValues> = null
    dataDirectory: string = ...

    Accessors

    • get arguments(): readonly Argument<"", undefined, undefined, undefined, undefined>[]
    • Returns readonly Argument<"", undefined, undefined, undefined, undefined>[]

    • get options(): readonly Option<"", undefined, undefined, undefined, false, undefined>[]
    • Returns readonly Option<"", undefined, undefined, undefined, false, undefined>[]

    Methods

    • Override default decision whether to add implicit help command.

      Parameters

      • Optional enableOrNameAndArgs: string | boolean
      • Optional description: string

      Returns CommandBuilder<Args, Opts>

      this command for chaining

      Example

      addHelpCommand() // force on
      addHelpCommand(false); // force off
      addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
    • Add additional text to be displayed with the built-in help.

      Position is 'before' or 'after' to affect just this command, and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.

      Parameters

      • position: AddHelpTextPosition
      • text: string

      Returns CommandBuilder<Args, Opts>

    • Validate ALREADY PARSED args using the validators defined in the command builder.

      Parameters

      • parsedArgs: any[]

      Returns any[]

    • Validate ALREADY PARSED options using the validators defined in the command builder.

      Parameters

      • parsedOptions: OptionValues

      Returns OptionValues

    • Automatically set 'short' and 'long' names to options that don't have one assigned yet.

      First, it tries to assign a short name based on the first letter of the option's attribute name Both lower and upper case are tried. If these is not available, the next letter of the option name is tried.

      If none of the letters of the option name are available, the option is skipped until all other options have had letters from their names attempted assigned. Those that remain are assigned the first available letter of the alphabet + 0-9. If there are 64 options for the command and no more alphanumeric characters are available, the option is not assigned a short name.

      Returns void

    • Makes aliases for the command. The idea is to be able to navigate the command tree by only typing the first letter(s) of the command names.

      Example: A command 'cola' would get these aliases: ['c', 'co', 'col']. However, if there are package clashes with sibling subcommands that start with the same letter, eg. like 'cola' and 'coal' where the first two letters clash, cola's aliases are reduced to only ['col'] and similarly for 'coal'.

      This method creates the aliases, ensuring there are no clashes with sublings, why it is important that the entire command tree is built before invoking this method.

      Returns CommandBuilder<Args, Opts>

    • Parameters

      • args: any[]
      • opts: OptionValues
      • presetArgs: string[][]
      • presetOpts: OptionValues[]
      • presetOrder: string[]

      Returns void

    • Parameters

      • Optional options: {
            debug?: boolean;
            disableColor?: boolean;
            disableStderr?: boolean;
            disableStdout?: boolean;
        }
        • Optional debug?: boolean
        • Optional disableColor?: boolean
        • Optional disableStderr?: boolean
        • Optional disableStdout?: boolean

      Returns CommandBuilder<Args, Opts>

    • Enable positional options. Positional means global options are specified before subcommands which lets subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.

      The default behaviour is non-positional and global options may appear anywhere on the command line.

      Parameters

      • Optional positional: boolean

      Returns CommandBuilder<Args, Opts>

      this command for chaining

    • Returns ((this, ...args) => void | Promise<void>)

        • (this, ...args): void | Promise<void>
        • Parameters

          Returns void | Promise<void>

    • Returns Option<"", undefined, undefined, undefined, false, undefined>[]

    • Get source of option value. See also .optsWithGlobals().

      Parameters

      • key: string

      Returns OptionValueSource

    • Returns Option<"", undefined, undefined, undefined, false, undefined>[]

    • Returns [presetArgs: string[][], presetOpts: OptionValues[], presetOrder: string[]]

    • Add hook for life cycle event.

      Parameters

      • event: HookEvent
      • listener: ((thisCommand, actionCommand) => void | Promise<void>)
          • (thisCommand, actionCommand): void | Promise<void>
          • Parameters

            • thisCommand: CommandUnknownOpts
            • actionCommand: CommandUnknownOpts

            Returns void | Promise<void>

      Returns CommandBuilder<Args, Opts>

    • Define option with flags, description, and optional argument parsing function or defaultValue or both. The flags string contains the short and/or long flags, separated by comma, a pipe or space. A required option-argument is indicated by <> and an optional option-argument by [].

      Parameters

      • flags: string
      • Optional description: string

      Returns CommandBuilder<Args, Opts>

      Example

      program
      .option('-p, --pepper', 'add pepper')
      .option('-p, --pizza-type <TYPE>', 'type of pizza') // required argument
      .option('-c, --cheese [CHEESE]', 'add extra cheese') // optional
    • Parameters

      • flags: string
      • Optional cb: ((opt, cmd) => void)

      Returns CommandBuilder<Args, Opts>

    • Display error message and exit (or call exitOverride).

      Parameters

      • event: string
      • getProps: (() => Record<string, unknown>) = ...
          • (): Record<string, unknown>
          • Returns Record<string, unknown>

      Returns void

    • Display error message and exit (or call exitOverride).

      Parameters

      • message: string
      • Optional options: ErrorOptions

      Returns void

    • Parse argv, setting options and invoking commands when defined.

      The default expectation is that the arguments are from node and have the application as argv[0] and the script being run in argv[1], with user parameters after that.

      Parameters

      • Optional argv: readonly string[]
      • Optional options: ParseOptions

      Returns CommandBuilder<Args, Opts>

      this command for chaining

      Example

      program.parse(process.argv);
      program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
      program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
    • Parse argv, setting options and invoking commands when defined.

      Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.

      The default expectation is that the arguments are from node and have the application as argv[0] and the script being run in argv[1], with user parameters after that.

      Parameters

      • Optional argv: readonly string[]
      • Optional options: ParseOptions

      Returns Promise<CommandBuilder<Args, Opts>>

      Promise

      Example

      program.parseAsync(process.argv);
      program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
      program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
    • Parses (and validates) options using the parsers defined in the command builder.

      Parameters

      • opts: OptionValues

      Returns OptionValues

    • Pass through options that come after command-arguments rather than treat them as command-options, so actual command-options come before command-arguments. Turning this on for a subcommand requires positional options to have been enabled on the program (parent commands).

      The default behaviour is non-positional and options may appear before or after command-arguments.

      Parameters

      • Optional passThrough: boolean

      Returns CommandBuilder<Args, Opts>

      this command for chaining

    • Set the program version to str.

      This method auto-registers the "-V, --version" flag which will print the version number when passed.

      You can optionally supply the flags and description to override the defaults.

      Parameters

      • string: string

      Returns CommandBuilder<Args, Opts>

    Generated using TypeDoc