boot

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 29, 2024 License: Apache-2.0 Imports: 17 Imported by: 0

README

cobra logo

Cobra is a library for creating powerful modern CLI applications.

Cobra is used in many Go projects such as Kubernetes, Hugo, and GitHub CLI to name a few. This list contains a more extensive list of projects using Cobra.

Go Reference Go Report Card Slack

Overview

Cobra is a library providing a simple interface to create powerful modern CLI interfaces similar to git & go tools.

Cobra provides:

  • Easy subcommand-based CLIs: app server, app fetch, etc.
  • Fully POSIX-compliant flags (including short & long versions)
  • Nested subcommands
  • Global, local and cascading flags
  • Intelligent suggestions (app srver... did you mean app server?)
  • Automatic help generation for commands and flags
  • Grouping help for subcommands
  • Automatic help flag recognition of -h, --help, etc.
  • Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell)
  • Automatically generated man pages for your application
  • Command aliases so you can change things without breaking them
  • The flexibility to define your own help, usage, etc.
  • Optional seamless integration with viper for 12-factor apps

Concepts

Cobra is built on a structure of commands, arguments & flags.

Commands represent actions, Args are things and Flags are modifiers for those actions.

The best applications read like sentences when used, and as a result, users intuitively know how to interact with them.

The pattern to follow is APPNAME VERB NOUN --ADJECTIVE or APPNAME COMMAND ARG --FLAG.

A few good real world examples may better illustrate this point.

In the following example, 'server' is a command, and 'port' is a flag:

hugo server --port=1313

In this command we are telling Git to clone the url bare.

git clone URL --bare

Commands

Command is the central point of the application. Each interaction that the application supports will be contained in a Command. A command can have children commands and optionally run an action.

In the example above, 'server' is the command.

More about cobra.Command

Flags

A flag is a way to modify the behavior of a command. Cobra supports fully POSIX-compliant flags as well as the Go flag package. A Cobra command can define flags that persist through to children commands and flags that are only available to that command.

In the example above, 'port' is the flag.

Flag functionality is provided by the pflag library, a fork of the flag standard library which maintains the same interface while adding POSIX compliance.

Installing

Using Cobra is easy. First, use go get to install the latest version of the library.

go get -u github.com/spf13/cobra@latest

Next, include Cobra in your application:

import "github.com/spf13/cobra"

Usage

cobra-cli is a command line program to generate cobra applications and command files. It will bootstrap your application scaffolding to rapidly develop a Cobra-based application. It is the easiest way to incorporate Cobra into your application.

It can be installed by running:

go install github.com/spf13/cobra-cli@latest

For complete details on using the Cobra-CLI generator, please read The Cobra Generator README

For complete details on using the Cobra library, please read the The Cobra User Guide.

License

Cobra is released under the Apache 2.0 license. See LICENSE.txt

Documentation

Overview

package boot 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.

Index

Constants

View Source
const (
	BashCompFilenameExt     = "cobra_annotation_bash_completion_filename_extensions"
	BashCompCustom          = "cobra_annotation_bash_completion_custom"
	BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"
	BashCompSubdirsInDir    = "cobra_annotation_bash_completion_subdirs_in_dir"
)

Annotations for Bash completion.

View Source
const (
	FlagSetByCobraAnnotation     = "cobra_annotation_flag_set_by_cobra"
	CommandDisplayNameAnnotation = "cobra_annotation_command_display_name"
)
View Source
const (
	// ShellCompRequestCmd is the name of the hidden command that is used to request
	// completion results from the program.  It is used by the shell completion scripts.
	ShellCompRequestCmd = "__complete"
	// ShellCompNoDescRequestCmd is the name of the hidden command that is used to request
	// completion results without their description.  It is used by the shell completion scripts.
	ShellCompNoDescRequestCmd = "__completeNoDesc"
)

Variables

View Source
var EnableCaseInsensitive = defaultCaseInsensitive

EnableCaseInsensitive allows case-insensitive commands names. (case sensitive by default)

View Source
var EnableCommandSorting = defaultCommandSorting

EnableCommandSorting controls sorting of the slice of commands, which is turned on by default. To disable sorting, set it to false.

View Source
var EnablePrefixMatching = defaultPrefixMatching

EnablePrefixMatching allows setting automatic prefix matching. Automatic prefix matching can be a dangerous thing to automatically enable in CLI tools. Set this to true to enable it.

View Source
var EnableTraverseRunHooks = defaultTraverseRunHooks

EnableTraverseRunHooks executes persistent pre-run and post-run hooks from all parents. By default this is disabled, which means only the first run hook to be found is executed.

View Source
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.

View Source
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

func AddTemplateFunc(name string, tmplFunc interface{})

AddTemplateFunc adds a template function that's available to Usage and Help template generation.

func AddTemplateFuncs

func AddTemplateFuncs(tmplFuncs template.FuncMap)

AddTemplateFuncs adds multiple template functions that are available to Usage and Help template generation.

func AllChildCommandsHaveGroup

func AllChildCommandsHaveGroup(c Commander) bool

AllChildCommandsHaveGroup returns if all subcommands are assigned to a group

func AppendActiveHelp

func AppendActiveHelp(compArray []string, activeHelpStr string) []string

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

func ArbitraryArgs(cmd Commander, args []string) error

ArbitraryArgs never returns an error.

func ArgsLenAtDash

func ArgsLenAtDash(c Commander) int

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

func Bind

func Bind(main Commander, commands ...Commander)

Add adds one or more commands to this parent command.

func CalledAs

func CalledAs(c Commander) string

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.

func CheckCommandGroups

func CheckCommandGroups(c Commander)

checkCommandGroups checks if a command has been added to a group that does not exists. If so, we panic because it indicates a coding error that should be corrected.

func CheckErr

func CheckErr(msg interface{})

CheckErr prints the msg with the prefix 'Error:' and exits with error code 1. If the msg is nil, it does nothing.

func CommandPath

func CommandPath(c Commander) string

CommandPath returns the full path to this command.

func CommandPathPadding

func CommandPathPadding(c Commander) int

CommandPathPadding return padding for the command path.

func CompDebug

func CompDebug(msg string, printToStdErr bool)

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

func CompDebugln(msg string, printToStdErr bool)

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

func CompError(msg string)

CompError prints the specified completion message to stderr.

func CompErrorln

func CompErrorln(msg string)

CompErrorln prints the specified completion message to stderr with a newline at the end.

func ContainsGroup

func ContainsGroup(c Commander, groupID string) bool

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

func DebugFlags

func DebugFlags(c Commander)

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

func Eq

func Eq(a interface{}, b interface{}) bool

Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.

func Execute

func Execute(c Commander) error

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

func FixedCompletions

func FixedCompletions(choices []string, directive ShellCompDirective) func(cmd Commander, args []string, toComplete string) ([]string, ShellCompDirective)

FixedCompletions can be used to create a completion function which always returns the same results.

func Flag

func Flag(c Commander, name string) (flag *flag.Flag)

Flag climbs up the command tree looking for matching flag.

func FlagErrorFunc

func FlagErrorFunc(c Commander) (f func(Commander, error) error)

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

func Flags

func Flags(c Commander) *flag.FlagSet

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

func GenBashCompletionFileV2

func GenBashCompletionFileV2(c Commander, filename string, includeDesc bool) error

GenBashCompletionFileV2 generates Bash completion version 2.

func GenBashCompletionV2

func GenBashCompletionV2(c Commander, w io.Writer, includeDesc bool) error

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

func GenFishCompletion

func GenFishCompletion(c Commander, w io.Writer, includeDesc bool) error

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

func GenFishCompletionFile

func GenFishCompletionFile(c Commander, filename string, includeDesc bool) error

GenFishCompletionFile generates fish completion file.

func GenPowerShellCompletion

func GenPowerShellCompletion(c Commander, w io.Writer) error

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

func GenPowerShellCompletionFile

func GenPowerShellCompletionFile(c Commander, filename string) error

GenPowerShellCompletionFile generates powershell completion file without descriptions.

func GenPowerShellCompletionFileWithDesc

func GenPowerShellCompletionFileWithDesc(c Commander, filename string) error

GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions.

func GenPowerShellCompletionWithDesc

func GenPowerShellCompletionWithDesc(c Commander, w io.Writer) error

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

func GenZshCompletion

func GenZshCompletion(c Commander, w io.Writer) error

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

func GenZshCompletionFile

func GenZshCompletionFile(c Commander, filename string) error

GenZshCompletionFile generates zsh completion file including descriptions.

func GenZshCompletionFileNoDesc

func GenZshCompletionFileNoDesc(c Commander, filename string) error

GenZshCompletionFileNoDesc generates zsh completion file without descriptions.

func GenZshCompletionNoDesc

func GenZshCompletionNoDesc(c Commander, w io.Writer) error

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

func GetActiveHelpConfig

func GetActiveHelpConfig(cmd Commander) string

GetActiveHelpConfig returns the value of the ActiveHelp environment variable <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`. It will always return "0" if the global environment variable COBRA_ACTIVE_HELP is set to "0".

func Gt

func Gt(a interface{}, b interface{}) bool

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 HasAlias

func HasAlias(c Commander, s string) bool

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

func HasAvailableFlags

func HasAvailableFlags(c Commander) bool

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

func HasAvailableInheritedFlags

func HasAvailableInheritedFlags(c Commander) bool

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

func HasAvailableLocalFlags

func HasAvailableLocalFlags(c Commander) bool

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

func HasAvailablePersistentFlags

func HasAvailablePersistentFlags(c Commander) bool

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

func HasAvailableSubCommands

func HasAvailableSubCommands(c Commander) bool

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

func HasExample

func HasExample(c Commander) bool

HasExample determines if the command has example.

func HasFlags

func HasFlags(c Commander) bool

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

func HasHelpSubCommands

func HasHelpSubCommands(c Commander) bool

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'.

func HasInheritedFlags

func HasInheritedFlags(c Commander) bool

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

func HasLocalFlags

func HasLocalFlags(c Commander) bool

HasLocalFlags checks if the command has flags specifically declared locally.

func HasParent

func HasParent(c Commander) bool

HasParent determines if the command is a child command.

func HasPersistentFlags

func HasPersistentFlags(c Commander) bool

HasPersistentFlags checks if the command contains persistent flags.

func HasSubCommands

func HasSubCommands(c Commander) bool

HasSubCommands determines if the command has children commands.

func Help

func Help(c Commander) error

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

func HelpFunc

func HelpFunc(c Commander, a []string)

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

func HelpTemplate

func HelpTemplate(c Commander) string

HelpTemplate return help template for the command.

func InheritedFlagUsages

func InheritedFlagUsages(c Commander) string

func InheritedFlags

func InheritedFlags(c Commander) *flag.FlagSet

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.

func InitDefaultCompletionCmd

func InitDefaultCompletionCmd(c Commander)

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.

func InitDefaultHelpCmd

func InitDefaultHelpCmd(c Commander)

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.

func InitDefaultHelpFlag

func InitDefaultHelpFlag(c Commander)

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.

func InitDefaultVersionFlag

func InitDefaultVersionFlag(c Commander)

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.

func IsAdditionalHelpTopicCommand

func IsAdditionalHelpTopicCommand(c Commander) bool

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.

func IsAvailableCommand

func IsAvailableCommand(c Commander) bool

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

func LocalFlagUsages

func LocalFlagUsages(c Commander) string

func LocalFlags

func LocalFlags(c Commander) *flag.FlagSet

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.

func LocalNonPersistentFlags

func LocalNonPersistentFlags(c Commander) *flag.FlagSet

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.

func MarkFlagCustom

func MarkFlagCustom(flags *flag.FlagSet, name string, f string) error

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

func MarkFlagDirname(flags *flag.FlagSet, name string) error

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

func MarkFlagFilename

func MarkFlagFilename(flags *flag.FlagSet, name string, extensions ...string) error

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

func MarkFlagRequired

func MarkFlagRequired(c Commander, name string) error

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 MarkFlagsMutuallyExclusive

func MarkFlagsMutuallyExclusive(c Commander, flagNames ...string)

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.

func MarkFlagsOneRequired

func MarkFlagsOneRequired(c Commander, flagNames ...string)

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.

func MarkFlagsRequiredTogether

func MarkFlagsRequiredTogether(c Commander, flagNames ...string)

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.

func MarkPersistentFlagFilename

func MarkPersistentFlagFilename(c Commander, name string, extensions ...string) error

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

func MarkPersistentFlagRequired

func MarkPersistentFlagRequired(c Commander, name string) error

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.

func MarkZshCompPositionalArgumentFile

func MarkZshCompPositionalArgumentFile(c Commander, argPosition int, patterns ...string) error

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

func MarkZshCompPositionalArgumentWords

func MarkZshCompPositionalArgumentWords(c Commander, argPosition int, words ...string) error

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

func NamePadding

func NamePadding(c Commander) int

NamePadding returns padding for the name.

func NoArgs

func NoArgs(cmd Commander, args []string) error

NoArgs returns an error if any args are included.

func NonInheritedFlags

func NonInheritedFlags(c Commander) *flag.FlagSet

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.

func OnFinalize

func OnFinalize(y ...func())

OnFinalize sets the passed functions to be run when each command's Execute method is terminated.

func OnInitialize

func OnInitialize(y ...func())

OnInitialize sets the passed functions to be run when each command's Execute method is called.

func OnlyValidArgs

func OnlyValidArgs(cmd Commander, args []string) error

OnlyValidArgs returns an error if there are any positional args that are not in the `ValidArgs` field of `Command`

func ParseFlags

func ParseFlags(c Commander, args []string) error

ParseFlags parses persistent flag tree and local flags.

func ParseName

func ParseName(c Commander) string

func PersistentFlags

func PersistentFlags(c Commander) *flag.FlagSet

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

func RemoveCommand

func RemoveCommand(c Commander, cmds ...Commander)

RemoveCommand removes one or more commands from a parent command.

func Run

func Run(root Commander, commands ...Commander) error

func SetGlobalNormalizationFunc

func SetGlobalNormalizationFunc(c Commander, n func(f *flag.FlagSet, name string) flag.NormalizedName)

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

func SuggestionsFor

func SuggestionsFor(c Commander, typedName string) []string

SuggestionsFor provides suggestions for the typedName.

func Usage

func Usage(c Commander) error

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

func UsagePadding

func UsagePadding(c Commander) int

UsagePadding return padding for the usage.

func UsageString

func UsageString(c Commander) string

UsageString returns usage string.

func UsageTemplate

func UsageTemplate(c Commander) string

UsageTemplate returns usage template for the command.

func UseLine

func UseLine(c Commander) string

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

func ValidateArgs

func ValidateArgs(c Commander, args []string) error

func ValidateFlagGroups

func ValidateFlagGroups(c Commander) error

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

func ValidateRequiredFlags

func ValidateRequiredFlags(c Commander) error

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

func VersionTemplate

func VersionTemplate(c Commander) string

VersionTemplate return version template for the command.

func VisitParents

func VisitParents(c Commander, fn func(Commander))

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

func WriteStringAndCheck

func WriteStringAndCheck(b io.StringWriter, s string)

WriteStringAndCheck writes a string into a buffer, and checks if the error is not nil.

Types

type BashCompleteCmd

type BashCompleteCmd struct {
	Command
}

func NewBashCompleteCmd

func NewBashCompleteCmd(cmd Commander, shortDesc string) *BashCompleteCmd

func (*BashCompleteCmd) GetUse

func (cmd *BashCompleteCmd) GetUse() string

func (*BashCompleteCmd) Run

func (cmd *BashCompleteCmd) Run(args []string) error

type Command

type Command struct {
	Default
	// 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
	Use string

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

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

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

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

	// Long is the long message shown in the 'help <this-command>' output.
	Long string

	// Example is examples of how to use the command.
	Example string

	// ValidArgs is list of all valid non-flag arguments that are accepted in shell completions
	ValidArgs []string
	// 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.
	ValidArgsFunction func(cmd Commander, args []string, toComplete string) ([]string, ShellCompDirective)

	// Expected arguments
	Args PositionalArgs

	// ArgAliases is List of aliases for ValidArgs.
	// These are not suggested to the user in the shell completion,
	// but accepted if entered manually.
	ArgAliases []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
	BashCompletionFunction string

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

	// Annotations are key/value pairs that can be used by applications to identify or
	// group commands or set special options.
	Annotations map[string]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.
	Version string

	// 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.
	PersistentPreRun func(cmd Commander, args []string)
	// PersistentPreRunE: PersistentPreRun but returns an error.
	PersistentPreRunE func(cmd Commander, args []string) error
	// PreRun: children of this command will not inherit.
	// PreRun func(cmd Commander, args []string)
	// PreRunE: PreRun but returns an error.
	PreRunE func(cmd Commander, args []string) error
	// Run: Typically the actual work function. Most commands will only implement this.
	// Run func(cmd Commander, args []string)
	// RunE: Run but returns an error.
	// RunE func(cmd Commander, args []string) error
	RunE func(cmd Commander, args []string) error

	// PostRun: run after the Run command.
	// PostRun func(cmd Commander, args []string)
	// PostRunE: PostRun but returns an error.
	PostRunE func(cmd Commander, args []string) error
	// PersistentPostRun: children of this command will inherit and execute after PostRun.
	PersistentPostRun func(cmd Commander, args []string)
	// PersistentPostRunE: PersistentPostRun but returns an error.
	PersistentPostRunE func(cmd Commander, args []string) error

	// FParseErrWhitelist flag parse errors to be ignored
	FParseErrWhitelist FParseErrWhitelist

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

	// TraverseChildren parses flags on all parents before executing child command.
	TraverseChildren bool

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

	// SilenceErrors is an option to quiet errors down stream.
	SilenceErrors bool

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

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

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

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

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

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

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.

func Root

func Root(use string, commands ...Commander) *Command

func (*Command) Add

func (c *Command) Add(v ...Commander)

func (*Command) Exec

func (c *Command) Exec(args ...string) error

func (*Command) Execute

func (c *Command) Execute() error

func (*Command) GenBashCompletion

func (c *Command) GenBashCompletion(w io.Writer) error

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

func (*Command) GenBashCompletionFile

func (c *Command) GenBashCompletionFile(filename string) error

GenBashCompletionFile generates bash completion file.

func (*Command) GetAliases

func (c *Command) GetAliases() []string

func (*Command) GetAnnotations

func (c *Command) GetAnnotations() map[string]string

func (*Command) GetArgAliases

func (c *Command) GetArgAliases() []string

func (*Command) GetCompletionOptions

func (c *Command) GetCompletionOptions() *CompletionOptions

func (*Command) GetDeprecated

func (c *Command) GetDeprecated() string

func (*Command) GetDisableAutoGenTag

func (c *Command) GetDisableAutoGenTag() bool

func (*Command) GetDisableFlagParsing

func (c *Command) GetDisableFlagParsing() bool

func (*Command) GetDisableFlagsInUseLine

func (c *Command) GetDisableFlagsInUseLine() bool

func (*Command) GetDisableSuggestions

func (c *Command) GetDisableSuggestions() bool

func (*Command) GetExample

func (c *Command) GetExample() string

func (*Command) GetFParseErrWhitelist

func (c *Command) GetFParseErrWhitelist() FParseErrWhitelist

GetFParseErrWhitelist implements Commander.

func (*Command) GetFlagCompletionFunc

func (c *Command) GetFlagCompletionFunc(flagName string) (func(Commander, []string, string) ([]string, ShellCompDirective), bool)

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

func (*Command) GetGlobNormFunc

func (c *Command) GetGlobNormFunc() func(f *flag.FlagSet, name string) flag.NormalizedName

GetGlobNormFunc implements Commander.

func (*Command) GetGroupID

func (c *Command) GetGroupID() string

func (*Command) GetHidden

func (c *Command) GetHidden() bool

func (*Command) GetLong

func (c *Command) GetLong() string

func (*Command) GetPersistentPostRun

func (c *Command) GetPersistentPostRun() func(cmd Commander, args []string)

func (*Command) GetPersistentPostRunE

func (c *Command) GetPersistentPostRunE() func(cmd Commander, args []string) error

func (*Command) GetPositionalArgs

func (c *Command) GetPositionalArgs() PositionalArgs

func (*Command) GetShort

func (c *Command) GetShort() string

func (*Command) GetSilenceErrors

func (c *Command) GetSilenceErrors() bool

func (*Command) GetSilenceUsage

func (c *Command) GetSilenceUsage() bool

func (*Command) GetSuggestFor

func (c *Command) GetSuggestFor() []string

func (*Command) GetTraverseChildren

func (c *Command) GetTraverseChildren() bool

func (*Command) GetUse

func (c *Command) GetUse() string

func (*Command) GetValidArgs

func (c *Command) GetValidArgs() []string

func (*Command) GetValidArgsFunction

func (c *Command) GetValidArgsFunction() func(cmd Commander, args []string, toComplete string) ([]string, ShellCompDirective)

func (*Command) GetVersion

func (c *Command) GetVersion() string

func (*Command) GlobalNormalizationFunc

func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName

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

func (*Command) MarkFlagCustom

func (c *Command) MarkFlagCustom(name string, f string) error

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 (*Command) MarkFlagDirname

func (c *Command) MarkFlagDirname(name string) error

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

func (*Command) MarkFlagFilename

func (c *Command) MarkFlagFilename(name string, extensions ...string) error

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

func (*Command) MarkPersistentFlagDirname

func (c *Command) MarkPersistentFlagDirname(name string) error

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

func (*Command) Parent

func (c *Command) Parent() Commander

Parent returns a commands parent command.

func (*Command) PostExec

func (c *Command) PostExec(args []string) error

func (*Command) PreExec

func (c *Command) PreExec(args []string) error

func (*Command) RegisterFlagCompletionFunc

func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd Commander, args []string, toComplete string) ([]string, ShellCompDirective)) error

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

func (*Command) Runnable

func (c *Command) Runnable() bool

Runnable determines if the command is itself runnable.

func (*Command) SetDisableAutoGenTag

func (c *Command) SetDisableAutoGenTag(d bool)

func (*Command) SetFParseErrWhitelist

func (c *Command) SetFParseErrWhitelist(fp FParseErrWhitelist)

SetFParseErrWhitelist implements Commander.

func (*Command) SetGlobNormFunc

func (c *Command) SetGlobNormFunc(f func(f *flag.FlagSet, name string) flag.NormalizedName)

SetGlobNormFunc implements Commander.

func (*Command) SetGroupID

func (c *Command) SetGroupID(groupID string)

func (*Command) SetVersionTemplate

func (c *Command) SetVersionTemplate(s string)

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

type CommandCalledAs

type CommandCalledAs struct {
	// contains filtered or unexported fields
}

type Commander

type Commander interface {
	// 参数
	GetUse() string
	GetHelpCommand() Commander
	GetShort() string
	GetSilenceErrors() bool
	GetSilenceUsage() bool
	GetValidArgs() []string
	GetHidden() bool
	GetLong() string
	GetExample() string
	GetCommandCalledAs() *CommandCalledAs
	// run
	// GetPersistentPreRunE() func(cmd Commander, args []string) error
	Init()
	PersistentPreExec(args []string) error
	Exec(args ...string) error // Typically the actual work function. Most commands will only implement this.
	PreExec(args []string) error
	PostExec(args []string) error
	PersistentPostExec(args []string) error

	Context() context.Context
	SetContext(ctx context.Context)

	ErrPrefix() string
	GetPositionalArgs() PositionalArgs
	GetCommandsMaxUseLen() int
	GetCommandsMaxCommandPathLen() int
	GetCommandsMaxNameLen() int
	SetCommandsMaxUseLen(v int)
	SetCommandsMaxCommandPathLen(v int)
	SetCommandsMaxNameLen(v int)
	GetTraverseChildren() bool
	GetDisableFlagParsing() bool

	GetAliases() []string
	GetDisableAutoGenTag() bool
	SetDisableAutoGenTag(d bool)
	GetVersion() string
	GetAnnotations() map[string]string
	GetDisableSuggestions() bool
	GetSuggestionsMinimumDistance() int
	GetDeprecated() string
	SetCommandsAreSorted(v bool)
	SetCommands(...Commander)

	// 层级关系
	SetParent(Commander)
	Parent() Commander
	GetGroupID() string
	SetGroupID(groupID string)

	// PersistentFlags() *flag.FlagSet
	GetArgs() []string
	// Add(cmds ...Commander)
	// ResetAdd(cmds ...Commander)
	GetCompletionOptions() *CompletionOptions
	GetCompletionCommandGroupID() string
	SetCompletionCommandGroupID(v string)

	GetValidArgsFunction() func(cmd Commander, args []string, toComplete string) ([]string, ShellCompDirective)
	GetArgAliases() []string

	Runnable() bool
	GetCommandGroups() []*Group

	Commands() []Commander

	// Flags
	GetFlags() *flag.FlagSet
	SetFlags(*flag.FlagSet)
	GetPFlags() *flag.FlagSet
	SetPFlags(*flag.FlagSet)
	GetLFlags() *flag.FlagSet
	SetLFlags(*flag.FlagSet)
	GetIFlags() *flag.FlagSet
	SetIFlags(*flag.FlagSet)
	GetParentsPFlags() *flag.FlagSet
	SetParentsPFlags(*flag.FlagSet)
	SetGlobNormFunc(f func(f *flag.FlagSet, name string) flag.NormalizedName)
	GetGlobNormFunc() func(f *flag.FlagSet, name string) flag.NormalizedName
	GetDisableFlagsInUseLine() bool
	GetFParseErrWhitelist() FParseErrWhitelist
	SetFParseErrWhitelist(FParseErrWhitelist)
	GetFlagErrorFunc() func(Commander, error) error
	SetFlagErrorBuf(*bytes.Buffer)
	GetFlagErrorBuf() *bytes.Buffer
	GetSuggestFor() []string
	// contains filtered or unexported methods
}

func Base

func Base(c Commander) Commander

Base finds root command.

func ExecuteC

func ExecuteC(c Commander) (cmd Commander, err error)

ExecuteC executes the command.

func Find

func Find(c Commander, args []string) (Commander, []string, error)

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

func Func

func Func(use string, exec func(args ...string) error) Commander

func Traverse

func Traverse(c Commander, args []string) (Commander, []string, error)

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

type CompleteCmd

type CompleteCmd struct {
	Command
}

func NewCompleteCmd

func NewCompleteCmd(cmd Commander) *CompleteCmd

func (*CompleteCmd) GetUse

func (cmd *CompleteCmd) GetUse() string

func (*CompleteCmd) Run

func (cmd *CompleteCmd) Run(args []string) error

type CompletionOptions

type CompletionOptions struct {
	// DisableDefaultCmd prevents Cobra from creating a default 'completion' command
	DisableDefaultCmd bool
	// DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag
	// for shells that support completion descriptions
	DisableNoDescFlag bool
	// DisableDescriptions turns off all completion descriptions for shells
	// that support them
	DisableDescriptions bool
	// HiddenDefaultCmd makes the default 'completion' command hidden
	HiddenDefaultCmd bool
}

CompletionOptions are the options to control shell completion

type Default

type Default struct {
	// contains filtered or unexported fields
}

Root 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.

func (*Default) AddGroup

func (d *Default) AddGroup(groups ...*Group)

func (*Default) CommandPathPadding

func (d *Default) CommandPathPadding() int

CommandPathPadding return padding for the command path.

func (*Default) Commands

func (d *Default) Commands() []Commander

Commands returns a sorted slice of child commands.

func (*Default) ContainsGroup

func (d *Default) ContainsGroup(groupID string) bool

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

func (*Default) Context

func (d *Default) Context() context.Context

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.

func (*Default) ErrPrefix

func (d *Default) ErrPrefix() string

ErrPrefix return error message prefix for the command

func (*Default) GetAliases

func (d *Default) GetAliases() []string

func (*Default) GetAnnotations

func (d *Default) GetAnnotations() map[string]string

func (d *Default) GetUse() string { return "" } // todo: 这个考虑不默认实现

func (*Default) GetArgAliases

func (d *Default) GetArgAliases() []string

func (*Default) GetArgs

func (d *Default) GetArgs() []string

func (*Default) GetCommandCalledAs

func (d *Default) GetCommandCalledAs() *CommandCalledAs

func (*Default) GetCommandGroups

func (d *Default) GetCommandGroups() []*Group

func (*Default) GetCommands

func (d *Default) GetCommands() []Commander

func (*Default) GetCommandsMaxCommandPathLen

func (d *Default) GetCommandsMaxCommandPathLen() int

func (*Default) GetCommandsMaxNameLen

func (d *Default) GetCommandsMaxNameLen() int

func (*Default) GetCommandsMaxUseLen

func (d *Default) GetCommandsMaxUseLen() int

func (*Default) GetCompletionCommandGroupID

func (d *Default) GetCompletionCommandGroupID() string

func (*Default) GetCompletionOptions

func (d *Default) GetCompletionOptions() *CompletionOptions

func (*Default) GetDeprecated

func (d *Default) GetDeprecated() string

func (*Default) GetDisableAutoGenTag

func (d *Default) GetDisableAutoGenTag() bool

func (*Default) GetDisableFlagParsing

func (d *Default) GetDisableFlagParsing() bool

func (*Default) GetDisableFlagsInUseLine

func (d *Default) GetDisableFlagsInUseLine() bool

func (*Default) GetDisableSuggestions

func (d *Default) GetDisableSuggestions() bool

func (*Default) GetExample

func (d *Default) GetExample() string

func (*Default) GetFParseErrWhitelist

func (d *Default) GetFParseErrWhitelist() FParseErrWhitelist

GetFParseErrWhitelist implements Commander.

func (*Default) GetFlagErrorBuf

func (d *Default) GetFlagErrorBuf() *bytes.Buffer

func (*Default) GetFlagErrorFunc

func (d *Default) GetFlagErrorFunc() func(Commander, error) error

func (*Default) GetFlags

func (d *Default) GetFlags() *flag.FlagSet

func (*Default) GetGlobNormFunc

func (d *Default) GetGlobNormFunc() func(f *flag.FlagSet, name string) flag.NormalizedName

GetGlobNormFunc implements Commander.

func (*Default) GetGroupID

func (d *Default) GetGroupID() string

func (*Default) GetHelpCommand

func (d *Default) GetHelpCommand() Commander

func (*Default) GetHidden

func (d *Default) GetHidden() bool

func (*Default) GetIFlags

func (d *Default) GetIFlags() *flag.FlagSet

GetIFlags implements Commander.

func (*Default) GetLFlags

func (d *Default) GetLFlags() *flag.FlagSet

GetLFlags implements Commander.

func (*Default) GetLong

func (d *Default) GetLong() string

func (*Default) GetPFlags

func (d *Default) GetPFlags() *flag.FlagSet

GetPFlags implements Commander.

func (*Default) GetParentsPFlags

func (d *Default) GetParentsPFlags() *flag.FlagSet

GetParentsPFlags implements Commander.

func (*Default) GetPositionalArgs

func (d *Default) GetPositionalArgs() PositionalArgs

func (*Default) GetShort

func (d *Default) GetShort() string

func (*Default) GetSilenceErrors

func (d *Default) GetSilenceErrors() bool

func (*Default) GetSilenceUsage

func (d *Default) GetSilenceUsage() bool

func (*Default) GetSuggestFor

func (d *Default) GetSuggestFor() []string

func (*Default) GetSuggestionsMinimumDistance

func (d *Default) GetSuggestionsMinimumDistance() int

func (*Default) GetTraverseChildren

func (d *Default) GetTraverseChildren() bool

func (*Default) GetValidArgs

func (d *Default) GetValidArgs() []string

func (*Default) GetValidArgsFunction

func (d *Default) GetValidArgsFunction() func(cmd Commander, args []string, toComplete string) ([]string, ShellCompDirective)

func (*Default) GetVersion

func (d *Default) GetVersion() string

func (*Default) GlobalNormalizationFunc

func (d *Default) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName

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

func (*Default) Groups

func (d *Default) Groups() []*Group

func (*Default) Init

func (d *Default) Init()

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

func (*Default) Parent

func (d *Default) Parent() Commander

func (*Default) PersistentPostExec

func (d *Default) PersistentPostExec(args []string) error

func (*Default) PersistentPreExec

func (d *Default) PersistentPreExec(args []string) error

func (*Default) PostExec

func (d *Default) PostExec(args []string) error

func (d *Default) Exec(args []string) error { return nil } // todo: 这个考虑不默认实现

func (*Default) PreExec

func (d *Default) PreExec(args []string) error

func (*Default) ResetCommands

func (d *Default) ResetCommands()

ResetCommands delete parent, subcommand and help command from c.

func (*Default) Runnable

func (d *Default) Runnable() bool

func (*Default) SetArgs

func (d *Default) SetArgs(a ...string)

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

func (*Default) SetCommands

func (d *Default) SetCommands(v ...Commander)

func (*Default) SetCommandsAreSorted

func (d *Default) SetCommandsAreSorted(v bool)

func (*Default) SetCommandsMaxCommandPathLen

func (d *Default) SetCommandsMaxCommandPathLen(v int)

func (*Default) SetCommandsMaxNameLen

func (d *Default) SetCommandsMaxNameLen(v int)

func (*Default) SetCommandsMaxUseLen

func (d *Default) SetCommandsMaxUseLen(v int)

func (*Default) SetCompletionCommandGroupID

func (d *Default) SetCompletionCommandGroupID(groupID string)

SetCompletionCommandGroupID sets the group id of the completion command.

func (*Default) SetContext

func (d *Default) SetContext(ctx context.Context)

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

func (*Default) SetDisableAutoGenTag

func (d *Default) SetDisableAutoGenTag(v bool)

func (*Default) SetFParseErrWhitelist

func (d *Default) SetFParseErrWhitelist(fp FParseErrWhitelist)

SetFParseErrWhitelist implements Commander.

func (*Default) SetFlagErrorBuf

func (d *Default) SetFlagErrorBuf(b *bytes.Buffer)

func (*Default) SetFlagErrorFunc

func (d *Default) SetFlagErrorFunc(f func(Commander, error) error)

func (*Default) SetFlags

func (d *Default) SetFlags(f *flag.FlagSet)

func (*Default) SetGlobNormFunc

func (d *Default) SetGlobNormFunc(f func(f *flag.FlagSet, name string) flag.NormalizedName)

SetGlobNormFunc implements Commander.

func (*Default) SetGroupID

func (d *Default) SetGroupID(groupID string)

func (*Default) SetHelpCommand

func (d *Default) SetHelpCommand(cmd Commander)

func (*Default) SetHelpCommandGroupID

func (d *Default) SetHelpCommandGroupID(groupID string)

SetHelpCommandGroupID sets the group id of the help command.

func (*Default) SetIFlags

func (d *Default) SetIFlags(i *flag.FlagSet)

SetIFlags implements Commander.

func (*Default) SetLFlags

func (d *Default) SetLFlags(l *flag.FlagSet)

SetLFlags implements Commander.

func (*Default) SetPFlags

func (d *Default) SetPFlags(l *flag.FlagSet)

SetPFlags implements Commander.

func (*Default) SetParent

func (d *Default) SetParent(c Commander)

func (*Default) SetParentsPFlags

func (d *Default) SetParentsPFlags(pf *flag.FlagSet)

SetParentsPFlags implements Commander.

func (*Default) SetSuggestionsMinimumDistance

func (d *Default) SetSuggestionsMinimumDistance(v int)

type FParseErrWhitelist

type FParseErrWhitelist flag.ParseErrorsWhitelist

FParseErrWhitelist configures Flag parse errors to be ignored

type FishCompleteCmd

type FishCompleteCmd struct {
	Command
	// contains filtered or unexported fields
}

func NewFishCompleteCmd

func NewFishCompleteCmd(cmd Commander, shortDesc string, noDesc bool) *FishCompleteCmd

func (*FishCompleteCmd) GetUse

func (p *FishCompleteCmd) GetUse() string

func (*FishCompleteCmd) Run

func (p *FishCompleteCmd) Run(args []string) error

type Group

type Group struct {
	ID    string
	Title string
}

Group Structure to manage groups for commands

type HelpCmd

type HelpCmd struct {
	Command
}

func NewHelpCmd

func NewHelpCmd(cmd Commander) *HelpCmd

func (*HelpCmd) GetUse

func (p *HelpCmd) GetUse() string

func (*HelpCmd) Run

func (p *HelpCmd) Run(args []string) error

type PositionalArgs

type PositionalArgs func(cmd Commander, args []string) error

func ExactArgs

func ExactArgs(n int) PositionalArgs

ExactArgs returns an error if there are not exactly n args.

func ExactValidArgs deprecated

func ExactValidArgs(n int) PositionalArgs

ExactValidArgs returns an error if there are not exactly N positional args OR there are any positional args that are not in the `ValidArgs` field of `Command`

Deprecated: use MatchAll(ExactArgs(n), OnlyValidArgs) instead

func MatchAll

func MatchAll(pargs ...PositionalArgs) PositionalArgs

MatchAll allows combining several PositionalArgs to work in concert.

func MaximumNArgs

func MaximumNArgs(n int) PositionalArgs

MaximumNArgs returns an error if there are more than N args.

func MinimumNArgs

func MinimumNArgs(n int) PositionalArgs

MinimumNArgs returns an error if there is not at least N args.

func RangeArgs

func RangeArgs(min int, max int) PositionalArgs

RangeArgs returns an error if the number of args is not within the expected range.

type PowershellCompleteCmd

type PowershellCompleteCmd struct {
	Command
	// contains filtered or unexported fields
}

func NewPowershellCompleteCmd

func NewPowershellCompleteCmd(cmd Commander, shortDesc string, noDesc bool) *PowershellCompleteCmd

func (*PowershellCompleteCmd) GetUse

func (cmd *PowershellCompleteCmd) GetUse() string

func (*PowershellCompleteCmd) Run

func (cmd *PowershellCompleteCmd) Run(args []string) error

type Print

type Print struct {
	// contains filtered or unexported fields
}

func (*Print) ErrOrStderr

func (c *Print) ErrOrStderr() io.Writer

ErrOrStderr returns output to stderr

func (*Print) GetIn

func (c *Print) GetIn() io.Reader

func (*Print) GetOut

func (c *Print) GetOut() io.Writer

func (*Print) InOrStdin

func (c *Print) InOrStdin() io.Reader

InOrStdin returns input to stdin

func (*Print) OutOrStderr

func (c *Print) OutOrStderr() io.Writer

OutOrStderr returns output to stderr

func (*Print) OutOrStdout

func (c *Print) OutOrStdout() io.Writer

OutOrStdout returns output to stdout.

func (*Print) Print

func (c *Print) Print(i ...interface{})

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

func (*Print) PrintErr

func (c *Print) PrintErr(i ...interface{})

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

func (*Print) PrintErrF

func (c *Print) PrintErrF(format string, i ...interface{})

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

func (*Print) PrintErrLn

func (c *Print) PrintErrLn(i ...interface{})

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

func (*Print) Printf

func (c *Print) Printf(format string, i ...interface{})

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

func (*Print) Println

func (c *Print) Println(i ...interface{})

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

func (*Print) SetErr

func (c *Print) SetErr(newErr io.Writer)

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

func (*Print) SetIn

func (c *Print) SetIn(newIn io.Reader)

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

func (*Print) SetOut

func (c *Print) SetOut(newOut io.Writer)

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

func (*Print) SetOutput

func (c *Print) SetOutput(output io.Writer)

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

type ShellCompDirective

type ShellCompDirective int

ShellCompDirective is a bit map representing the different behaviors the shell can be instructed to have once completions have been provided.

const (
	// ShellCompDirectiveError indicates an error occurred and completions should be ignored.
	ShellCompDirectiveError ShellCompDirective = 1 << iota

	// ShellCompDirectiveNoSpace indicates that the shell should not add a space
	// after the completion even if there is a single completion provided.
	ShellCompDirectiveNoSpace

	// ShellCompDirectiveNoFileComp indicates that the shell should not provide
	// file completion even when no completion is provided.
	ShellCompDirectiveNoFileComp

	// ShellCompDirectiveFilterFileExt indicates that the provided completions
	// should be used as file extension filters.
	// For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename()
	// is a shortcut to using this directive explicitly.  The BashCompFilenameExt
	// annotation can also be used to obtain the same behavior for flags.
	ShellCompDirectiveFilterFileExt

	// ShellCompDirectiveFilterDirs indicates that only directory names should
	// be provided in file completion.  To request directory names within another
	// directory, the returned completions should specify the directory within
	// which to search.  The BashCompSubdirsInDir annotation can be used to
	// obtain the same behavior but only for flags.
	ShellCompDirectiveFilterDirs

	// ShellCompDirectiveKeepOrder indicates that the shell should preserve the order
	// in which the completions are provided
	ShellCompDirectiveKeepOrder

	// ShellCompDirectiveDefault indicates to let the shell perform its default
	// behavior after completions have been provided.
	// This one must be last to avoid messing up the iota count.
	ShellCompDirectiveDefault ShellCompDirective = 0
)

func NoFileCompletions

func NoFileCompletions(cmd Commander, args []string, toComplete string) ([]string, ShellCompDirective)

NoFileCompletions can be used to disable file completion for commands that should not trigger file completions.

type ZshCompleteCmd

type ZshCompleteCmd struct {
	Command
	// contains filtered or unexported fields
}

func NewZshCompleteCmd

func NewZshCompleteCmd(cmd Commander, shortDesc string, noDesc bool) *ZshCompleteCmd

func (*ZshCompleteCmd) GetUse

func (p *ZshCompleteCmd) GetUse() string

func (*ZshCompleteCmd) Run

func (p *ZshCompleteCmd) Run(args []string) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL