Cobra 在pkg.go.dev上的文档
12 分钟阅读
Cobra 在pkg.go.dev上的文档
Overview
Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code.
Constants
|
|
Annotations for Bash completion.
|
|
|
|
Variables
var EnableCaseInsensitive = defaultCaseInsensitive
EnableCaseInsensitive allows case-insensitive commands names. (case sensitive by default)
var EnableCommandSorting = defaultCommandSorting
EnableCommandSorting controls sorting of the slice of commands, which is turned on by default. To disable sorting, set it to false.
var EnablePrefixMatching = defaultPrefixMatching
EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing to automatically enable in CLI tools. Set this to true to enable it.
var MousetrapDisplayDuration = 5 * time.Second
MousetrapDisplayDuration controls how long the MousetrapHelpText message is displayed on Windows if the CLI is started from explorer.exe. Set to 0 to wait for the return key to be pressed. To disable the mousetrap, just set MousetrapHelpText to blank string (""). Works only on Microsoft Windows.
var MousetrapHelpText = `This is a command line tool.
You need to open cmd.exe and run it from there.
`
MousetrapHelpText enables an information splash screen on Windows if the CLI is started from explorer.exe. To disable the mousetrap, just set this variable to blank string (""). Works only on Microsoft Windows.
Functions
func AddTemplateFunc
|
|
AddTemplateFunc adds a template function that’s available to Usage and Help template generation.
func AddTemplateFuncs
|
|
AddTemplateFuncs adds multiple template functions that are available to Usage and Help template generation.
func AppendActiveHelp <- v1.5.0
|
|
AppendActiveHelp adds the specified string to the specified array to be used as ActiveHelp. Such strings will be processed by the completion script and will be shown as ActiveHelp to the user. The array parameter should be the array that will contain the completions. This function can be called multiple times before and/or after completions are added to the array. Each time this function is called with the same array, the new ActiveHelp line will be shown below the previous ones when completion is triggered.
func ArbitraryArgs
|
|
ArbitraryArgs never returns an error.
func CheckErr <- v1.1.2
|
|
CheckErr prints the msg with the prefix ‘Error:’ and exits with error code 1. If the msg is nil, it does nothing.
func CompDebug <- v1.0.0
|
|
CompDebug prints the specified string to the same file as where the completion script prints its logs. Note that completion printouts should never be on stdout as they would be wrongly interpreted as actual completion choices by the completion script.
func CompDebugln <- v1.0.0
|
|
CompDebugln prints the specified string with a newline at the end to the same file as where the completion script prints its logs. Such logs are only printed when the user has set the environment variable BASH_COMP_DEBUG_FILE to the path of some file to be used.
func CompError <- v1.0.0
|
|
CompError prints the specified completion message to stderr.
func CompErrorln <- v1.0.0
|
|
CompErrorln prints the specified completion message to stderr with a newline at the end.
func Eq
|
|
Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.
func FixedCompletions <- v1.5.0
|
|
FixedCompletions can be used to create a completion function which always returns the same results.
func GetActiveHelpConfig <- v1.5.0
|
|
GetActiveHelpConfig returns the value of the ActiveHelp environment variable
func Gt
|
|
Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans, Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as ints and then compared.
func MarkFlagCustom
|
|
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.
func MarkFlagDirname <- v0.0.5
|
|
MarkFlagDirname instructs the various shell completion implementations to limit completions for the named flag to directory names.
func MarkFlagFilename
|
|
MarkFlagFilename instructs the various shell completion implementations to limit completions for the named flag to the specified file extensions.
func MarkFlagRequired
|
|
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.
func NoArgs
|
|
NoArgs returns an error if any args are included.
func OnFinalize <- v1.6.0
|
|
OnFinalize sets the passed functions to be run when each command’s Execute method is terminated.
func OnInitialize
|
|
OnInitialize sets the passed functions to be run when each command’s Execute method is called.
func OnlyValidArgs
|
|
OnlyValidArgs returns an error if there are any positional args that are not in the ValidArgs
field of Command
func WriteStringAndCheck <- v1.1.2
|
|
WriteStringAndCheck writes a string into a buffer, and checks if the error is not nil.
Types
type Command
|
|
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.
(*Command) AddCommand
|
|
AddCommand adds one or more commands to this parent command.
(*Command) AddGroup <- v1.6.0
|
|
AddGroup adds one or more command groups to this parent command.
(*Command) AllChildCommandsHaveGroup <- v1.6.0
|
|
AllChildCommandsHaveGroup returns if all subcommands are assigned to a group
(*Command) ArgsLenAtDash
|
|
ArgsLenAtDash will return the length of c.Flags().Args at the moment when a – was found during args parsing.
(*Command) CalledAs <- v0.0.2
|
|
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.
(*Command) CommandPath
|
|
CommandPath returns the full path to this command.
(*Command) CommandPathPadding
|
|
CommandPathPadding return padding for the command path.
(*Command) Commands
|
|
Commands returns a sorted slice of child commands.
(*Command) ContainsGroup <- v1.6.0
|
|
ContainsGroup return if groupID exists in the list of command groups.
(*Command) Context <- v0.0.6
|
|
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.
(*Command) DebugFlags
|
|
DebugFlags used to determine which flags have been assigned to which commands and which persist.
(*Command) ErrOrStderr <- v0.0.5
|
|
ErrOrStderr returns output to stderr
(*Command) Execute
|
|
Execute uses the args (os.Args[1:] by default) and run through the command tree finding appropriate matches for commands and then corresponding flags.
(*Command) ExecuteC
|
|
ExecuteC executes the command.
(*Command) ExecuteContext <- v0.0.6
|
|
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.
(*Command) ExecuteContextC <- v1.2.0
|
|
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.
(*Command) Find
|
|
Find the target command given the args and command tree Meant to be run on the highest node. Only searches down.
(*Command) Flag
|
|
Flag climbs up the command tree looking for matching flag.
(*Command) FlagErrorFunc
|
|
FlagErrorFunc returns either the function set by SetFlagErrorFunc for this command or a parent, or it returns a function which returns the original error.
(*Command) Flags
|
|
Flags returns the complete FlagSet that applies to this command (local and persistent declared here and by all parents).
(*Command) GenBashCompletion
|
|
GenBashCompletion generates bash completion file and writes to the passed writer.
(*Command) GenBashCompletionFile
|
|
GenBashCompletionFile generates bash completion file.
(*Command) GenBashCompletionFileV2 <- v1.2.0
|
|
GenBashCompletionFileV2 generates Bash completion version 2.
(*Command) GenBashCompletionV2 <- v1.2.0
|
|
GenBashCompletionV2 generates Bash completion file version 2 and writes it to the passed writer.
(*Command) GenFishCompletion <- v1.0.0
|
|
GenFishCompletion generates fish completion file and writes to the passed writer.
(*Command) GenFishCompletionFile <- v1.0.0
|
|
GenFishCompletionFile generates fish completion file.
(*Command) GenPowerShellCompletion <- v0.0.5
|
|
GenPowerShellCompletion generates powershell completion file without descriptions and writes it to the passed writer.
(*Command) GenPowerShellCompletionFile <- v0.0.5
|
|
GenPowerShellCompletionFile generates powershell completion file without descriptions.
(*Command) GenPowerShellCompletionFileWithDesc <- v1.1.2
|
|
GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions.
(*Command) GenPowerShellCompletionWithDesc <- v1.1.2
|
|
GenPowerShellCompletionWithDesc generates powershell completion file with descriptions and writes it to the passed writer.
(*Command) GenZshCompletion
|
|
GenZshCompletion generates zsh completion file including descriptions and writes it to the passed writer.
(*Command) GenZshCompletionFile
|
|
GenZshCompletionFile generates zsh completion file including descriptions.
(*Command) GenZshCompletionFileNoDesc <- v1.1.0
|
|
GenZshCompletionFileNoDesc generates zsh completion file without descriptions.
(*Command) GenZshCompletionNoDesc <- v1.1.0
|
|
GenZshCompletionNoDesc generates zsh completion file without descriptions and writes it to the passed writer.
(*Command) GlobalNormalizationFunc
|
|
GlobalNormalizationFunc returns the global normalization function or nil if it doesn’t exist.
(*Command) Groups <- v1.6.0
|
|
Groups returns a slice of child command groups.
(*Command) HasAlias
|
|
HasAlias determines if a given string is an alias of the command.
(*Command) HasAvailableFlags
|
|
HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire structure) which are not hidden or deprecated.
(*Command) HasAvailableInheritedFlags
|
|
HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are not hidden or deprecated.
(*Command) HasAvailableLocalFlags
|
|
HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden or deprecated.
(*Command) HasAvailablePersistentFlags
|
|
HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.
(*Command) HasAvailableSubCommands
|
|
HasAvailableSubCommands determines if a command has available sub commands that need to be shown in the usage/help default template under ‘available commands’.
(*Command) HasExample
|
|
HasExample determines if the command has example.
(*Command) HasFlags
|
|
HasFlags checks if the command contains any flags (local plus persistent from the entire structure).
(*Command) HasHelpSubCommands
|
|
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’.
(*Command) HasInheritedFlags
|
|
HasInheritedFlags checks if the command has flags inherited from its parent command.
(*Command) HasLocalFlags
|
|
HasLocalFlags checks if the command has flags specifically declared locally.
(*Command) HasParent
|
|
HasParent determines if the command is a child command.
(*Command) HasPersistentFlags
|
|
HasPersistentFlags checks if the command contains persistent flags.
(*Command) HasSubCommands
|
|
HasSubCommands determines if the command has children commands.
(*Command) Help
|
|
Help puts out the help for the command. Used when a user calls help [command]. Can be defined by user by overriding HelpFunc.
(*Command) HelpFunc
|
|
HelpFunc returns either the function set by SetHelpFunc for this command or a parent, or it returns a function with default help behavior.
(*Command) HelpTemplate
|
|
HelpTemplate return help template for the command.
(*Command) InOrStdin <- v0.0.5
|
|
InOrStdin returns input to stdin
(*Command) InheritedFlags
|
|
InheritedFlags returns all flags which were inherited from parent commands.
(*Command) InitDefaultCompletionCmd <- v1.6.0
|
|
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.
(*Command) InitDefaultHelpCmd
|
|
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.
(*Command) InitDefaultHelpFlag
|
|
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.
(*Command) InitDefaultVersionFlag <- v0.0.2
|
|
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.
(*Command) IsAdditionalHelpTopicCommand
|
|
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.
(*Command) IsAvailableCommand
|
|
IsAvailableCommand determines if a command is available as a non-help command (this includes all non deprecated/hidden commands).
(*Command) LocalFlags
|
|
LocalFlags returns the local FlagSet specifically set in the current command.
(*Command) LocalNonPersistentFlags
|
|
LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.
(*Command) MarkFlagCustom
|
|
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.
(*Command) MarkFlagDirname <- v0.0.5
|
|
MarkFlagDirname instructs the various shell completion implementations to limit completions for the named flag to directory names.
(*Command) MarkFlagFilename
|
|
MarkFlagFilename instructs the various shell completion implementations to limit completions for the named flag to the specified file extensions.
(*Command) MarkFlagRequired
|
|
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.
(*Command) MarkFlagsMutuallyExclusive <- v1.5.0
|
|
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.
(*Command) MarkFlagsRequiredTogether <- v1.5.0
|
|
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.
(*Command) MarkPersistentFlagDirname <- v0.0.5
|
|
MarkPersistentFlagDirname instructs the various shell completion implementations to limit completions for the named persistent flag to directory names.
(*Command) MarkPersistentFlagFilename
|
|
MarkPersistentFlagFilename instructs the various shell completion implementations to limit completions for the named persistent flag to the specified file extensions.
(*Command) MarkPersistentFlagRequired
|
|
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.
(*Command) MarkZshCompPositionalArgumentFile <- v0.0.5
|
|
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
(*Command) MarkZshCompPositionalArgumentWords <- v0.0.5
|
|
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
(*Command) Name
|
|
Name returns the command’s name: the first word in the use line.
(*Command) NameAndAliases
|
|
NameAndAliases returns a list of the command name and all aliases
(*Command) NamePadding
|
|
NamePadding returns padding for the name.
(*Command) NonInheritedFlags
|
|
NonInheritedFlags returns all flags which were not inherited from parent commands.
(*Command) OutOrStderr
|
|
OutOrStderr returns output to stderr
(*Command) OutOrStdout
|
|
OutOrStdout returns output to stdout.
(*Command) Parent
|
|
Parent returns a commands parent command.
(*Command) ParseFlags
|
|
ParseFlags parses persistent flag tree and local flags.
(*Command) PersistentFlags
|
|
PersistentFlags returns the persistent FlagSet specifically set in the current command.
(*Command) Print
|
|
Print is a convenience method to Print to the defined output, fallback to Stderr if not set.
(*Command) PrintErr <- v0.0.5
|
|
PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set.
(*Command) PrintErrf <- v0.0.5
|
|
PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set.
(*Command) PrintErrln <- v0.0.5
|
|
PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set.
(*Command) Printf
|
|
Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.
(*Command) Println
|
|
Println is a convenience method to Println to the defined output, fallback to Stderr if not set.
(*Command) RegisterFlagCompletionFunc <- v1.0.0
|
|
RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.
(*Command) RemoveCommand
|
|
RemoveCommand removes one or more commands from a parent command.
(*Command) ResetCommands
|
|
ResetCommands delete parent, subcommand and help command from c.
(*Command) ResetFlags
|
|
ResetFlags deletes all flags from command.
(*Command) Root
|
|
Root finds root command.
(*Command) Runnable
|
|
Runnable determines if the command is itself runnable.
(*Command) SetArgs
|
|
SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden particularly useful when testing.
(*Command) SetCompletionCommandGroupID <- v1.6.0
|
|
SetCompletionCommandGroupID sets the group id of the completion command.
(*Command) SetContext <- v1.5.0
|
|
SetContext sets context for the command. This context will be overwritten by Command.ExecuteContext or Command.ExecuteContextC.
(*Command) SetErr <- v0.0.5
|
|
SetErr sets the destination for error messages. If newErr is nil, os.Stderr is used.
(*Command) SetFlagErrorFunc
|
|
SetFlagErrorFunc sets a function to generate an error when flag parsing fails.
(*Command) SetGlobalNormalizationFunc
|
|
SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands. The user should not have a cyclic dependency on commands.
(*Command) SetHelpCommand
|
|
SetHelpCommand sets help command.
(*Command) SetHelpCommandGroupID <- v1.6.0
|
|
SetHelpCommandGroupID sets the group id of the help command.
(*Command) SetHelpFunc
|
|
SetHelpFunc sets help function. Can be defined by Application.
(*Command) SetHelpTemplate
|
|
SetHelpTemplate sets help template to be used. Application can use it to set custom template.
(*Command) SetIn <- v0.0.5
|
|
SetIn sets the source for input data If newIn is nil, os.Stdin is used.
(*Command) SetOut <- v0.0.5
|
|
SetOut sets the destination for usage messages. If newOut is nil, os.Stdout is used.
(*Command) SetOutput
|
|
SetOutput sets the destination for usage and error messages. If output is nil, os.Stderr is used. Deprecated: Use SetOut and/or SetErr instead
(*Command) SetUsageFunc
|
|
SetUsageFunc sets usage function. Usage can be defined by application.
(*Command) SetUsageTemplate
|
|
SetUsageTemplate sets usage template. Can be defined by Application.
(*Command) SetVersionTemplate <- v0.0.2
|
|
SetVersionTemplate sets version template to be used. Application can use it to set custom template.
(*Command) SuggestionsFor
|
|
SuggestionsFor provides suggestions for the typedName.
(*Command) Traverse
|
|
Traverse the command tree to find the command, and parse args for each parent.
(*Command) Usage
|
|
Usage puts out the usage for the command. Used when a user provides invalid input. Can be defined by user by overriding UsageFunc.
(*Command) UsageFunc
|
|
UsageFunc returns either the function set by SetUsageFunc for this command or a parent, or it returns a default usage function.
(*Command) UsagePadding
|
|
UsagePadding return padding for the usage.
(*Command) UsageString
|
|
UsageString returns usage string.
(*Command) UsageTemplate
|
|
UsageTemplate returns usage template for the command.
(*Command) UseLine
|
|
UseLine puts out the full usage for a given command (including parents).
(*Command) ValidateArgs
|
|
(*Command) ValidateFlagGroups <- v1.6.0
|
|
ValidateFlagGroups validates the mutuallyExclusive/requiredAsGroup logic and returns the first error encountered.
(*Command) ValidateRequiredFlags <- v1.6.0
|
|
ValidateRequiredFlags validates all required flags are present and returns an error otherwise
(*Command) VersionTemplate <- v0.0.2
|
|
VersionTemplate return version template for the command.
(*Command) VisitParents
|
|
VisitParents visits all parents of the command and invokes fn on each parent.
type CompletionOptions <- v1.2.0
|
|
CompletionOptions are the options to control shell completion
type FParseErrWhitelist <- v0.0.3
|
|
FParseErrWhitelist configures Flag parse errors to be ignored
type Group <- v1.6.0
|
|
Group Structure to manage groups for commands
type PositionalArgs
|
|
func ExactArgs
|
|
ExactArgs returns an error if there are not exactly n args.
funcExactValidArgsDEPRECATEDadded in v0.0.4
func MatchAll <- v1.3.0
|
|
MatchAll allows combining several PositionalArgs to work in concert.
func MaximumNArgs
|
|
MaximumNArgs returns an error if there are more than N args.
func MinimumNArgs
|
|
MinimumNArgs returns an error if there is not at least N args.
func RangeArgs
|
|
RangeArgs returns an error if the number of args is not within the expected range.
type ShellCompDirective <- v1.0.0
|
|
ShellCompDirective is a bit map representing the different behaviors the shell can be instructed to have once completions have been provided.
|
|
func NoFileCompletions <- v1.2.0
|
|
NoFileCompletions can be used to disable file completion for commands that should not trigger file completions.