Command is just that, a command for your application. E.g. 'go run ...' - 'run' is the command. Cobra requires you to define the usage and description as part of your command definition to ensure usability.

Hierarchy

Implemented by

Methods

addCommand addGroup allChildCommandsHaveGroup argsLenAtDash calledAs commandPath commandPathPadding commands containsGroup context debugFlags errOrStderr errPrefix execute executeC executeContext executeContextC find flag flagErrorFunc flags genBashCompletion genBashCompletionFile genBashCompletionFileV2 genBashCompletionV2 genFishCompletion genFishCompletionFile genPowerShellCompletion genPowerShellCompletionFile genPowerShellCompletionFileWithDesc genPowerShellCompletionWithDesc genZshCompletion genZshCompletionFile genZshCompletionFileNoDesc genZshCompletionNoDesc getFlagCompletionFunc globalNormalizationFunc groups hasAlias hasAvailableFlags hasAvailableInheritedFlags hasAvailableLocalFlags hasAvailablePersistentFlags hasAvailableSubCommands hasExample hasFlags hasHelpSubCommands hasInheritedFlags hasLocalFlags hasParent hasPersistentFlags hasSubCommands help helpFunc helpTemplate inOrStdin inheritedFlags initDefaultCompletionCmd initDefaultHelpCmd initDefaultHelpFlag initDefaultVersionFlag isAdditionalHelpTopicCommand isAvailableCommand localFlags localNonPersistentFlags markFlagCustom markFlagDirname markFlagFilename markFlagRequired markFlagsMutuallyExclusive markFlagsOneRequired markFlagsRequiredTogether markPersistentFlagDirname markPersistentFlagFilename markPersistentFlagRequired markZshCompPositionalArgumentFile markZshCompPositionalArgumentWords name nameAndAliases namePadding nonInheritedFlags outOrStderr outOrStdout parent parseFlags persistentFlags print printErr printErrf printErrln printf println registerFlagCompletionFunc removeCommand resetCommands resetFlags root runnable setArgs setCompletionCommandGroupID setContext setErr setErrPrefix setFlagErrorFunc setGlobalNormalizationFunc setHelpCommand setHelpCommandGroupID setHelpFunc setHelpTemplate setIn setOut setOutput setUsageFunc setUsageTemplate setVersionTemplate suggestionsFor traverse usage usageFunc usagePadding usageString usageTemplate useLine validateArgs validateFlagGroups validateRequiredFlags versionTemplate visitParents

Properties

Methods

  • AddCommand adds one or more commands to this parent command.

    Parameters

    Returns void

  • AddGroup adds one or more command groups to this parent command.

    Parameters

    Returns void

  • AllChildCommandsHaveGroup returns if all subcommands are assigned to a group

    Returns boolean

  • ArgsLenAtDash will return the length of c.Flags().Args at the moment when a -- was found during args parsing.

    Returns number

  • CalledAs returns the command name or alias that was used to invoke this command or an empty string if the command has not been called.

    Returns string

  • CommandPath returns the full path to this command.

    Returns string

  • CommandPathPadding return padding for the command path.

    Returns number

  • ContainsGroup return if groupID exists in the list of command groups.

    Parameters

    • groupID: string

    Returns boolean

  • Context returns underlying command context. If command was executed with ExecuteContext or the context was set with SetContext, the previously set context will be returned. Otherwise, nil is returned.

    Notice that a call to Execute and ExecuteC will replace a nil context of a command with a context.Background, so a background context will be returned by Context after one of these functions has been called.

    Returns context.Context

  • DebugFlags used to determine which flags have been assigned to which commands and which persist.

    Returns void

  • ErrPrefix return error message prefix for the command

    Returns string

  • Execute uses the args (os.Args[1:] by default) and run through the command tree finding appropriate matches for commands and then corresponding flags.

    Returns void

  • ExecuteContext is the same as Execute(), but sets the ctx on the command. Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs functions.

    Parameters

    Returns void

  • ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command. Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs functions.

    Parameters

    Returns cobra.Command

  • Find the target command given the args and command tree Meant to be run on the highest node. Only searches down.

    Parameters

    • args: string[]

    Returns [cobra.Command, string[]]

  • Flag climbs up the command tree looking for matching flag.

    Parameters

    • name: string

    Returns any

  • FlagErrorFunc returns either the function set by SetFlagErrorFunc for this command or a parent, or it returns a function which returns the original error.

    Returns ((_arg0, _arg1) => void)

      • (_arg0, _arg1): void
      • FlagErrorFunc returns either the function set by SetFlagErrorFunc for this command or a parent, or it returns a function which returns the original error.

        Parameters

        Returns void

  • Flags returns the complete FlagSet that applies to this command (local and persistent declared here and by all parents).

    Returns any

  • GenBashCompletion generates bash completion file and writes to the passed writer.

    Parameters

    Returns void

  • GenBashCompletionFile generates bash completion file.

    Parameters

    • filename: string

    Returns void

  • GenBashCompletionFileV2 generates Bash completion version 2.

    Parameters

    • filename: string
    • includeDesc: boolean

    Returns void

  • GenBashCompletionV2 generates Bash completion file version 2 and writes it to the passed writer.

    Parameters

    Returns void

  • GenFishCompletion generates fish completion file and writes to the passed writer.

    Parameters

    Returns void

  • GenFishCompletionFile generates fish completion file.

    Parameters

    • filename: string
    • includeDesc: boolean

    Returns void

  • GenPowerShellCompletion generates powershell completion file without descriptions and writes it to the passed writer.

    Parameters

    Returns void

  • GenPowerShellCompletionFile generates powershell completion file without descriptions.

    Parameters

    • filename: string

    Returns void

  • GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions.

    Parameters

    • filename: string

    Returns void

  • GenPowerShellCompletionWithDesc generates powershell completion file with descriptions and writes it to the passed writer.

    Parameters

    Returns void

  • GenZshCompletion generates zsh completion file including descriptions and writes it to the passed writer.

    Parameters

    Returns void

  • GenZshCompletionFile generates zsh completion file including descriptions.

    Parameters

    • filename: string

    Returns void

  • GenZshCompletionFileNoDesc generates zsh completion file without descriptions.

    Parameters

    • filename: string

    Returns void

  • GenZshCompletionNoDesc generates zsh completion file without descriptions and writes it to the passed writer.

    Parameters

    Returns void

  • GetFlagCompletionFunc returns the completion function for the given flag of the command, if available.

    Parameters

    • flagName: string

    Returns [((_arg0, _arg1, _arg2) => [string[], ShellCompDirective]), boolean]

  • GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist.

    Returns ((f, name) => any)

      • (f, name): any
      • GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist.

        Parameters

        • f: any
        • name: string

        Returns any

  • HasAlias determines if a given string is an alias of the command.

    Parameters

    • s: string

    Returns boolean

  • HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire structure) which are not hidden or deprecated.

    Returns boolean

  • HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are not hidden or deprecated.

    Returns boolean

  • HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden or deprecated.

    Returns boolean

  • HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.

    Returns boolean

  • HasAvailableSubCommands determines if a command has available sub commands that need to be shown in the usage/help default template under 'available commands'.

    Returns boolean

  • HasExample determines if the command has example.

    Returns boolean

  • HasFlags checks if the command contains any flags (local plus persistent from the entire structure).

    Returns boolean

  • HasHelpSubCommands determines if a command has any available 'help' sub commands that need to be shown in the usage/help default template under 'additional help topics'.

    Returns boolean

  • HasInheritedFlags checks if the command has flags inherited from its parent command.

    Returns boolean

  • HasLocalFlags checks if the command has flags specifically declared locally.

    Returns boolean

  • HasParent determines if the command is a child command.

    Returns boolean

  • HasPersistentFlags checks if the command contains persistent flags.

    Returns boolean

  • HasSubCommands determines if the command has children commands.

    Returns boolean

  • Help puts out the help for the command. Used when a user calls help [command]. Can be defined by user by overriding HelpFunc.

    Returns void

  • HelpFunc returns either the function set by SetHelpFunc for this command or a parent, or it returns a function with default help behavior.

    Returns ((_arg0, _arg1) => void)

      • (_arg0, _arg1): void
      • HelpFunc returns either the function set by SetHelpFunc for this command or a parent, or it returns a function with default help behavior.

        Parameters

        Returns void

  • HelpTemplate return help template for the command.

    Returns string

  • InheritedFlags returns all flags which were inherited from parent commands. This function does not modify the flags of the current command, it's purpose is to return the current state.

    Returns any

  • InitDefaultCompletionCmd adds a default 'completion' command to c. This function will do nothing if any of the following is true: 1- the feature has been explicitly disabled by the program, 2- c has no subcommands (to avoid creating one), 3- c already has a 'completion' command provided by the program.

    Returns void

  • InitDefaultHelpCmd adds default help command to c. It is called automatically by executing the c or by calling help and usage. If c already has help command or c has no subcommands, it will do nothing.

    Returns void

  • InitDefaultHelpFlag adds default help flag to c. It is called automatically by executing the c or by calling help and usage. If c already has help flag, it will do nothing.

    Returns void

  • InitDefaultVersionFlag adds default version flag to c. It is called automatically by executing the c. If c already has a version flag, it will do nothing. If c.Version is empty, it will do nothing.

    Returns void

  • IsAdditionalHelpTopicCommand determines if a command is an additional help topic command; additional help topic command is determined by the fact that it is NOT runnable/hidden/deprecated, and has no sub commands that are runnable/hidden/deprecated. Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.

    Returns boolean

  • IsAvailableCommand determines if a command is available as a non-help command (this includes all non deprecated/hidden commands).

    Returns boolean

  • LocalFlags returns the local FlagSet specifically set in the current command. This function does not modify the flags of the current command, it's purpose is to return the current state.

    Returns any

  • LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands. This function does not modify the flags of the current command, it's purpose is to return the current state.

    Returns any

  • MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. The bash completion script will call the bash function f for the flag.

    This will only work for bash completion. It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows to register a Go function which will work across all shells.

    Parameters

    • name: string
    • f: string

    Returns void

  • MarkFlagDirname instructs the various shell completion implementations to limit completions for the named flag to directory names.

    Parameters

    • name: string

    Returns void

  • MarkFlagFilename instructs the various shell completion implementations to limit completions for the named flag to the specified file extensions.

    Parameters

    • name: string
    • Rest ...extensions: string[]

    Returns void

  • MarkFlagRequired instructs the various shell completion implementations to prioritize the named flag when performing completion, and causes your command to report an error if invoked without the flag.

    Parameters

    • name: string

    Returns void

  • MarkFlagsMutuallyExclusive marks the given flags with annotations so that Cobra errors if the command is invoked with more than one flag from the given set of flags.

    Parameters

    • Rest ...flagNames: string[]

    Returns void

  • MarkFlagsOneRequired marks the given flags with annotations so that Cobra errors if the command is invoked without at least one flag from the given set of flags.

    Parameters

    • Rest ...flagNames: string[]

    Returns void

  • MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors if the command is invoked with a subset (but not all) of the given flags.

    Parameters

    • Rest ...flagNames: string[]

    Returns void

  • MarkPersistentFlagDirname instructs the various shell completion implementations to limit completions for the named persistent flag to directory names.

    Parameters

    • name: string

    Returns void

  • MarkPersistentFlagFilename instructs the various shell completion implementations to limit completions for the named persistent flag to the specified file extensions.

    Parameters

    • name: string
    • Rest ...extensions: string[]

    Returns void

  • MarkPersistentFlagRequired instructs the various shell completion implementations to prioritize the named persistent flag when performing completion, and causes your command to report an error if invoked without the flag.

    Parameters

    • name: string

    Returns void

  • MarkZshCompPositionalArgumentFile only worked for zsh and its behavior was not consistent with Bash completion. It has therefore been disabled. Instead, when no other completion is specified, file completion is done by default for every argument. One can disable file completion on a per-argument basis by using ValidArgsFunction and ShellCompDirectiveNoFileComp. To achieve file extension filtering, one can use ValidArgsFunction and ShellCompDirectiveFilterFileExt.

    Deprecated

    Parameters

    • argPosition: number
    • Rest ...patterns: string[]

    Returns void

  • MarkZshCompPositionalArgumentWords only worked for zsh. It has therefore been disabled. To achieve the same behavior across all shells, one can use ValidArgs (for the first argument only) or ValidArgsFunction for any argument (can include the first one also).

    Deprecated

    Parameters

    • argPosition: number
    • Rest ...words: string[]

    Returns void

  • Name returns the command's name: the first word in the use line.

    Returns string

  • NameAndAliases returns a list of the command name and all aliases

    Returns string

  • NamePadding returns padding for the name.

    Returns number

  • NonInheritedFlags returns all flags which were not inherited from parent commands. This function does not modify the flags of the current command, it's purpose is to return the current state.

    Returns any

  • ParseFlags parses persistent flag tree and local flags.

    Parameters

    • args: string[]

    Returns void

  • PersistentFlags returns the persistent FlagSet specifically set in the current command.

    Returns any

  • Print is a convenience method to Print to the defined output, fallback to Stderr if not set.

    Parameters

    • Rest ...i: {}[]

    Returns void

  • PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set.

    Parameters

    • Rest ...i: {}[]

    Returns void

  • PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set.

    Parameters

    • format: string
    • Rest ...i: {}[]

    Returns void

  • PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set.

    Parameters

    • Rest ...i: {}[]

    Returns void

  • Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.

    Parameters

    • format: string
    • Rest ...i: {}[]

    Returns void

  • Println is a convenience method to Println to the defined output, fallback to Stderr if not set.

    Parameters

    • Rest ...i: {}[]

    Returns void

  • RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.

    Parameters

    Returns void

  • RemoveCommand removes one or more commands from a parent command.

    Parameters

    Returns void

  • ResetCommands delete parent, subcommand and help command from c.

    Returns void

  • ResetFlags deletes all flags from command.

    Returns void

  • Runnable determines if the command is itself runnable.

    Returns boolean

  • SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden particularly useful when testing.

    Parameters

    • a: string[]

    Returns void

  • SetCompletionCommandGroupID sets the group id of the completion command.

    Parameters

    • groupID: string

    Returns void

  • SetContext sets context for the command. This context will be overwritten by Command.ExecuteContext or Command.ExecuteContextC.

    Parameters

    Returns void

  • SetErr sets the destination for error messages. If newErr is nil, os.Stderr is used.

    Parameters

    Returns void

  • SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix.

    Parameters

    • s: string

    Returns void

  • SetFlagErrorFunc sets a function to generate an error when flag parsing fails.

    Parameters

    • f: ((_arg0, _arg1) => void)
        • (_arg0, _arg1): void
        • Parameters

          Returns void

    Returns void

  • SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands. The user should not have a cyclic dependency on commands.

    Parameters

    • n: ((f, name) => any)
        • (f, name): any
        • Parameters

          • f: any
          • name: string

          Returns any

    Returns void

  • SetHelpCommandGroupID sets the group id of the help command.

    Parameters

    • groupID: string

    Returns void

  • SetHelpFunc sets help function. Can be defined by Application.

    Parameters

    • f: ((_arg0, _arg1) => void)
        • (_arg0, _arg1): void
        • Parameters

          Returns void

    Returns void

  • SetHelpTemplate sets help template to be used. Application can use it to set custom template.

    Parameters

    • s: string

    Returns void

  • SetIn sets the source for input data If newIn is nil, os.Stdin is used.

    Parameters

    Returns void

  • SetOut sets the destination for usage messages. If newOut is nil, os.Stdout is used.

    Parameters

    Returns void

  • SetOutput sets the destination for usage and error messages. If output is nil, os.Stderr is used. Deprecated: Use SetOut and/or SetErr instead

    Parameters

    Returns void

  • SetUsageFunc sets usage function. Usage can be defined by application.

    Parameters

    • f: ((_arg0) => void)

    Returns void

  • SetUsageTemplate sets usage template. Can be defined by Application.

    Parameters

    • s: string

    Returns void

  • SetVersionTemplate sets version template to be used. Application can use it to set custom template.

    Parameters

    • s: string

    Returns void

  • SuggestionsFor provides suggestions for the typedName.

    Parameters

    • typedName: string

    Returns string[]

  • Traverse the command tree to find the command, and parse args for each parent.

    Parameters

    • args: string[]

    Returns [cobra.Command, string[]]

  • Usage puts out the usage for the command. Used when a user provides invalid input. Can be defined by user by overriding UsageFunc.

    Returns void

  • UsageFunc returns either the function set by SetUsageFunc for this command or a parent, or it returns a default usage function.

    Returns ((_arg0) => void)

      • (_arg0): void
      • UsageFunc returns either the function set by SetUsageFunc for this command or a parent, or it returns a default usage function.

        Parameters

        Returns void

  • UsagePadding return padding for the usage.

    Returns number

  • UsageString returns usage string.

    Returns string

  • UsageTemplate returns usage template for the command.

    Returns string

  • UseLine puts out the full usage for a given command (including parents).

    Returns string

  • Parameters

    • args: string[]

    Returns void

  • ValidateFlagGroups validates the mutuallyExclusive/oneRequired/requiredAsGroup logic and returns the first error encountered.

    Returns void

  • ValidateRequiredFlags validates all required flags are present and returns an error otherwise

    Returns void

  • VersionTemplate return version template for the command.

    Returns string

  • VisitParents visits all parents of the command and invokes fn on each parent.

    Parameters

    • fn: ((_arg0) => void)

    Returns void

Properties

aliases: string[]

Aliases is an array of aliases that can be used instead of the first word in Use.

annotations: _TygojaDict

Annotations are key/value pairs that can be used by applications to identify or group commands or set special options.

argAliases: string[]

ArgAliases is List of aliases for ValidArgs. These are not suggested to the user in the shell completion, but accepted if entered manually.

Expected arguments

bashCompletionFunction: string

BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator. For portability with other shells, it is recommended to instead use ValidArgsFunction

completionOptions: CompletionOptions

CompletionOptions is a set of options to control the handling of shell completion

deprecated: string

Deprecated defines, if this command is deprecated and should print this string when used.

disableAutoGenTag: boolean

DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...") will be printed by generating docs for this command.

disableFlagParsing: boolean

DisableFlagParsing disables the flag parsing. If this is true all flags will be passed to the command as arguments.

disableFlagsInUseLine: boolean

DisableFlagsInUseLine will disable the addition of [flags] to the usage line of a command when printing help or generating docs

disableSuggestions: boolean

DisableSuggestions disables the suggestions based on Levenshtein distance that go along with 'unknown command' messages.

example: string

Example is examples of how to use the command.

fParseErrWhitelist: FParseErrWhitelist

FParseErrWhitelist flag parse errors to be ignored

groupID: string

The group id under which this subcommand is grouped in the 'help' output of its parent.

hidden: boolean

Hidden defines, if this command is hidden and should NOT show up in the list of available commands.

long: string

Long is the long message shown in the 'help ' output.

persistentPostRun: ((cmd, args) => void)

Type declaration

    • (cmd, args): void
    • PersistentPostRun: children of this command will inherit and execute after PostRun.

      Parameters

      Returns void

persistentPostRunE: ((cmd, args) => void)

Type declaration

    • (cmd, args): void
    • PersistentPostRunE: PersistentPostRun but returns an error.

      Parameters

      Returns void

persistentPreRun: ((cmd, args) => void)

Type declaration

    • (cmd, args): void
    • The *Run functions are executed in the following order:

        * PersistentPreRun()
      * PreRun()
      * Run()
      * PostRun()
      * PersistentPostRun()

      All functions get the same args, the arguments after the command name. The *PreRun and *PostRun functions will only be executed if the Run function of the current command has been declared.

      PersistentPreRun: children of this command will inherit and execute.

      Parameters

      Returns void

persistentPreRunE: ((cmd, args) => void)

Type declaration

    • (cmd, args): void
    • PersistentPreRunE: PersistentPreRun but returns an error.

      Parameters

      Returns void

postRun: ((cmd, args) => void)

Type declaration

    • (cmd, args): void
    • PostRun: run after the Run command.

      Parameters

      Returns void

postRunE: ((cmd, args) => void)

Type declaration

    • (cmd, args): void
    • PostRunE: PostRun but returns an error.

      Parameters

      Returns void

preRun: ((cmd, args) => void)

Type declaration

    • (cmd, args): void
    • PreRun: children of this command will not inherit.

      Parameters

      Returns void

preRunE: ((cmd, args) => void)

Type declaration

    • (cmd, args): void
    • PreRunE: PreRun but returns an error.

      Parameters

      Returns void

run: ((cmd, args) => void)

Type declaration

    • (cmd, args): void
    • Run: Typically the actual work function. Most commands will only implement this.

      Parameters

      Returns void

runE: ((cmd, args) => void)

Type declaration

    • (cmd, args): void
    • RunE: Run but returns an error.

      Parameters

      Returns void

short: string

Short is the short description shown in the 'help' output.

silenceErrors: boolean

SilenceErrors is an option to quiet errors down stream.

silenceUsage: boolean

SilenceUsage is an option to silence usage when an error occurs.

suggestFor: string[]

SuggestFor is an array of command names for which this command will be suggested - similar to aliases but only suggests.

suggestionsMinimumDistance: number

SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions. Must be > 0.

traverseChildren: boolean

TraverseChildren parses flags on all parents before executing child command.

use: string

Use is the one-line usage message. Recommended syntax is as follows:

  [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required.
... indicates that you can specify multiple values for the previous argument.
| indicates mutually exclusive information. You can use the argument to the left of the separator or the
argument to the right of the separator. You cannot use both arguments in a single use of the command.
{ } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are
optional, they are enclosed in brackets ([ ]).

Example: add [-F file | -D dir]... [-f format] profile

validArgs: string[]

ValidArgs is list of all valid non-flag arguments that are accepted in shell completions

validArgsFunction: ((cmd, args, toComplete) => [string[], ShellCompDirective])

Type declaration

    • (cmd, args, toComplete): [string[], ShellCompDirective]
    • ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion. It is a dynamic version of using ValidArgs. Only one of ValidArgs and ValidArgsFunction can be used for a command.

      Parameters

      Returns [string[], ShellCompDirective]

version: string

Version defines the version for this command. If this value is non-empty and the command does not define a "version" flag, a "version" boolean flag will be added to the command and, if specified, will print content of the "Version" variable. A shorthand "v" flag will also be added if the command does not define one.

Generated using TypeDoc