cli
packagemoduleThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
README¶
Welcome to urfave/cli
urfave/cli is adeclarative, simple, fast, and fun package for buildingcommand line tools in Go featuring:
- commands and subcommands with alias and prefix match support
- flexible and permissive help system
- dynamic shell completion for
bash
,zsh
,fish
, andpowershell
- no dependencies except Go standard library
- input flags for simple types, slices of simple types, time, duration, andothers
- compound short flag support (
-a
-b
-c
can be shortened to-abc
) - documentation generation in
man
and Markdown (supported via theurfave/cli-docs
module) - input lookup from:
- environment variables
- plain text files
- structured file formats (supported via the
urfave/cli-altsrc
module)
Documentation
See the hosted documentation website athttps://cli.urfave.org. Contents ofthis website are built from the./docs
directory.
Support
Check theQ&A discussions. If you don't find answer to your question,createa new discussion.
If you found a bug or have a feature request,create a new issue.
Please keep in mind that this project is run by unpaid volunteers.
License
SeeLICENSE
.
Documentation¶
Overview¶
Package cli provides a minimal framework for creating and organizing command lineGo applications. cli is designed to be easy to understand and write, the most simplecli application can be written as follows:
func main() {(&cli.Command{}).Run(context.Background(), os.Args)}
Of course this application does not do much, so let's make this an actual application:
func main() {cmd := &cli.Command{ Name: "greet", Usage: "say a greeting", Action: func(c *cli.Context) error { fmt.Println("Greetings") return nil },}cmd.Run(context.Background(), os.Args)}
Index¶
- Variables
- func DefaultAppComplete(ctx context.Context, cmd *Command)
- func DefaultCompleteWithFlags(ctx context.Context, cmd *Command)
- func FlagNames(name string, aliases []string) []string
- func HandleExitCoder(err error)
- func ShowAppHelp(cmd *Command) error
- func ShowAppHelpAndExit(cmd *Command, exitCode int)
- func ShowCommandHelp(ctx context.Context, cmd *Command, commandName string) error
- func ShowCommandHelpAndExit(ctx context.Context, cmd *Command, command string, code int)
- func ShowSubcommandHelp(cmd *Command) error
- func ShowSubcommandHelpAndExit(cmd *Command, exitCode int)
- func ShowVersion(cmd *Command)
- type ActionFunc
- type ActionableFlag
- type AfterFunc
- type Args
- type Argument
- type ArgumentBase
- type BeforeFunc
- type BoolConfig
- type BoolFlag
- type BoolWithInverseFlag
- func (bif *BoolWithInverseFlag) Count() int
- func (bif *BoolWithInverseFlag) Get() any
- func (bif *BoolWithInverseFlag) GetCategory() string
- func (bif *BoolWithInverseFlag) GetDefaultText() string
- func (bif *BoolWithInverseFlag) GetEnvVars() []string
- func (bif *BoolWithInverseFlag) GetUsage() string
- func (bif *BoolWithInverseFlag) GetValue() string
- func (bif *BoolWithInverseFlag) IsBoolFlag() bool
- func (bif *BoolWithInverseFlag) IsDefaultVisible() bool
- func (bif *BoolWithInverseFlag) IsSet() bool
- func (bif *BoolWithInverseFlag) Names() []string
- func (bif *BoolWithInverseFlag) PostParse() error
- func (bif *BoolWithInverseFlag) PreParse() error
- func (bif *BoolWithInverseFlag) RunAction(ctx context.Context, cmd *Command) error
- func (bif *BoolWithInverseFlag) Set(name, val string) error
- func (bif *BoolWithInverseFlag) SetCategory(c string)
- func (bif *BoolWithInverseFlag) String() string
- func (bif *BoolWithInverseFlag) TakesValue() bool
- func (bif *BoolWithInverseFlag) TypeName() string
- type CategorizableFlag
- type Command
- func (cmd *Command) Args() Args
- func (cmd *Command) Bool(name string) bool
- func (cmd *Command) Command(name string) *Command
- func (cmd *Command) Count(name string) int
- func (cmd *Command) Duration(name string) time.Duration
- func (cmd *Command) FlagNames() []string
- func (cmd *Command) Float(name string) float64
- func (cmd *Command) FloatSlice(name string) []float64
- func (cmd *Command) FullName() string
- func (cmd *Command) Generic(name string) Value
- func (cmd *Command) HasName(name string) bool
- func (cmd *Command) Int(name string) int64
- func (cmd *Command) IntSlice(name string) []int64
- func (cmd *Command) IsSet(name string) bool
- func (cmd *Command) Lineage() []*Command
- func (cmd *Command) LocalFlagNames() []string
- func (cmd *Command) NArg() int
- func (cmd *Command) Names() []string
- func (cmd *Command) NumFlags() int
- func (cmd *Command) Root() *Command
- func (cmd *Command) Run(ctx context.Context, osArgs []string) (deferErr error)
- func (cmd *Command) Set(name, value string) error
- func (cmd *Command) String(name string) string
- func (cmd *Command) StringMap(name string) map[string]string
- func (cmd *Command) StringSlice(name string) []string
- func (cmd *Command) Timestamp(name string) time.Time
- func (cmd *Command) ToFishCompletion() (string, error)
- func (cmd *Command) Uint(name string) uint64
- func (cmd *Command) UintSlice(name string) []uint64
- func (cmd *Command) Value(name string) interface{}
- func (cmd *Command) VisibleCategories() []CommandCategory
- func (cmd *Command) VisibleCommands() []*Command
- func (cmd *Command) VisibleFlagCategories() []VisibleFlagCategory
- func (cmd *Command) VisibleFlags() []Flag
- func (cmd *Command) VisiblePersistentFlags() []Flag
- type CommandCategories
- type CommandCategory
- type CommandNotFoundFunc
- type Countable
- type DocGenerationFlag
- type DocGenerationMultiValueFlag
- type DurationFlag
- type EnvValueSource
- type ErrorFormatter
- type ExitCoder
- type ExitErrHandlerFunc
- type Flag
- type FlagBase
- func (f *FlagBase[T, C, VC]) Count() int
- func (f *FlagBase[T, C, V]) Get() any
- func (f *FlagBase[T, C, V]) GetCategory() string
- func (f *FlagBase[T, C, V]) GetDefaultText() string
- func (f *FlagBase[T, C, V]) GetEnvVars() []string
- func (f *FlagBase[T, C, V]) GetUsage() string
- func (f *FlagBase[T, C, V]) GetValue() string
- func (f *FlagBase[T, C, VC]) IsBoolFlag() bool
- func (f *FlagBase[T, C, V]) IsDefaultVisible() bool
- func (f *FlagBase[T, C, VC]) IsLocal() bool
- func (f *FlagBase[T, C, VC]) IsMultiValueFlag() bool
- func (f *FlagBase[T, C, V]) IsRequired() bool
- func (f *FlagBase[T, C, V]) IsSet() bool
- func (f *FlagBase[T, C, V]) IsVisible() bool
- func (f *FlagBase[T, C, V]) Names() []string
- func (f *FlagBase[T, C, V]) PostParse() error
- func (f *FlagBase[T, C, V]) PreParse() error
- func (f *FlagBase[T, C, V]) RunAction(ctx context.Context, cmd *Command) error
- func (f *FlagBase[T, C, V]) Set(_ string, val string) error
- func (f *FlagBase[T, C, V]) SetCategory(c string)
- func (f *FlagBase[T, C, V]) String() string
- func (f *FlagBase[T, C, V]) TakesValue() bool
- func (f *FlagBase[T, C, V]) TypeName() string
- type FlagCategories
- type FlagEnvHintFunc
- type FlagFileHintFunc
- type FlagNamePrefixFunc
- type FlagStringFunc
- type FlagsByName
- type FloatArg
- type FloatFlag
- type FloatSlice
- type FloatSliceFlag
- type GenericFlag
- type IntArg
- type IntFlag
- type IntSlice
- type IntSliceFlag
- type IntegerConfig
- type InvalidFlagAccessFunc
- type LocalFlag
- type MapBase
- func (i MapBase[T, C, VC]) Create(val map[string]T, p *map[string]T, c C) Value
- func (i *MapBase[T, C, VC]) Get() interface{}
- func (i *MapBase[T, C, VC]) Serialize() string
- func (i *MapBase[T, C, VC]) Set(value string) error
- func (i *MapBase[T, C, VC]) String() string
- func (i MapBase[T, C, VC]) ToString(t map[string]T) string
- func (i *MapBase[T, C, VC]) Value() map[string]T
- type MapSource
- type MultiError
- type MutuallyExclusiveFlags
- type NoConfig
- type OnUsageErrorFunc
- type RequiredFlag
- type Serializer
- type ShellCompleteFunc
- type SliceBase
- func (i SliceBase[T, C, VC]) Create(val []T, p *[]T, c C) Value
- func (i *SliceBase[T, C, VC]) Get() interface{}
- func (i *SliceBase[T, C, VC]) Serialize() string
- func (i *SliceBase[T, C, VC]) Set(value string) error
- func (i *SliceBase[T, C, VC]) String() string
- func (i SliceBase[T, C, VC]) ToString(t []T) string
- func (i *SliceBase[T, C, VC]) Value() []T
- type StringArg
- type StringConfig
- type StringFlag
- type StringMap
- type StringMapArg
- type StringMapFlag
- type StringSlice
- type StringSliceFlag
- type SuggestCommandFunc
- type SuggestFlagFunc
- type TimestampArg
- type TimestampConfig
- type TimestampFlag
- type UintArg
- type UintFlag
- type UintSlice
- type UintSliceFlag
- type Value
- type ValueCreator
- type ValueSource
- type ValueSourceChain
- func (vsc *ValueSourceChain) Append(other ValueSourceChain)
- func (vsc *ValueSourceChain) EnvKeys() []string
- func (vsc *ValueSourceChain) GoString() string
- func (vsc *ValueSourceChain) Lookup() (string, bool)
- func (vsc *ValueSourceChain) LookupWithSource() (string, ValueSource, bool)
- func (vsc *ValueSourceChain) String() string
- type VisibleFlag
- type VisibleFlagCategory
Examples¶
- BoolWithInverseFlag
- Command.Run
- Command.Run (AppHelp)
- Command.Run (CommandHelp)
- Command.Run (MapValues)
- Command.Run (NoAction)
- Command.Run (ShellComplete_bash)
- Command.Run (ShellComplete_bash_withLongFlag)
- Command.Run (ShellComplete_bash_withMultipleLongFlag)
- Command.Run (ShellComplete_bash_withShortFlag)
- Command.Run (ShellComplete_zsh)
- Command.Run (SliceValues)
- Command.Run (Subcommand)
- Command.Run (SubcommandNoAction)
Constants¶
This section is empty.
Variables¶
var (SuggestFlagSuggestFlagFunc = suggestFlagSuggestCommandSuggestCommandFunc = suggestCommandSuggestDidYouMeanTemplatestring = suggestDidYouMeanTemplate)
var AnyArguments = []Argument{&StringArg{Max: -1,},}
AnyArguments to differentiate between no arguments(nil) vs aleast one
var CommandHelpTemplate = ``/* 477-byte string literal not displayed */
CommandHelpTemplate is the text template for the command help topic.cli.go uses text/template to render templates. You canrender custom help text by setting this variable.
var DefaultInverseBoolPrefix = "no-"
var ErrWriterio.Writer =os.Stderr
ErrWriter is used to write errors to the user. This can be anythingimplementing the io.Writer interface and defaults to os.Stderr.
var FishCompletionTemplate = ``/* 366-byte string literal not displayed */
var HelpPrinter helpPrinter = printHelp
HelpPrinter is a function that writes the help output. If not set explicitly,this calls HelpPrinterCustom using only the default template functions.
If custom logic for printing help is required, this function can beoverridden. If the ExtraInfo field is defined on an App, this functionshould not be modified, as HelpPrinterCustom will be used directly in orderto capture the extra information.
var HelpPrinterCustom helpPrinterCustom = printHelpCustom
HelpPrinterCustom is a function that writes the help output. It is used asthe default implementation of HelpPrinter, and may be called directly ifthe ExtraInfo field is set on an App.
In the default implementation, if the customFuncs argument contains a"wrapAt" key, which is a function which takes no arguments and returnsan int, this int value will be used to produce a "wrap" function usedby the default template to wrap long lines.
var NewFloatSlice =NewSliceBase[float64,NoConfig, floatValue]
var NewIntSlice =NewSliceBase[int64,IntegerConfig, intValue]
var NewStringMap =NewMapBase[string,StringConfig, stringValue]
var NewStringSlice =NewSliceBase[string,StringConfig, stringValue]
var NewUintSlice =NewSliceBase[uint64,IntegerConfig, uintValue]
var OsExiter =os.Exit
OsExiter is the function used when the app exits. If not set defaults to os.Exit.
var RootCommandHelpTemplate = ``/* 873-byte string literal not displayed */
RootCommandHelpTemplate is the text template for the Default help topic.cli.go uses text/template to render templates. You canrender custom help text by setting this variable.
var SubcommandHelpTemplate = ``/* 638-byte string literal not displayed */
SubcommandHelpTemplate is the text template for the subcommand help topic.cli.go uses text/template to render templates. You canrender custom help text by setting this variable.
var VersionPrinter = printVersion
VersionPrinter prints the version for the App
Functions¶
funcDefaultAppComplete¶
DefaultAppComplete prints the list of subcommands as the default app completion method
funcHandleExitCoder¶
func HandleExitCoder(errerror)
HandleExitCoder handles errors implementing ExitCoder by printing theirmessage and calling OsExiter with the given exit code.
If the given error instead implements MultiError, each error will be checkedfor the ExitCoder interface, and OsExiter will be called with the last exitcode found, or exit code 1 if no ExitCoder is found.
This function is the default error-handling behavior for an App.
funcShowAppHelpAndExit¶
ShowAppHelpAndExit - Prints the list of subcommands for the app and exits with exit code.
funcShowCommandHelp¶
ShowCommandHelp prints help for the given command
funcShowCommandHelpAndExit¶
ShowCommandHelpAndExit - exits with code after showing help
funcShowSubcommandHelp¶
ShowSubcommandHelp prints help for the given subcommand
funcShowSubcommandHelpAndExit¶
ShowSubcommandHelpAndExit - Prints help for the given subcommand and exits with exit code.
Types¶
typeActionFunc¶
ActionFunc is the action to execute when no subcommands are specified
typeActionableFlag¶
ActionableFlag is an interface that wraps Flag interface and RunAction operation.
typeAfterFunc¶
AfterFunc is an action that executes after any subcommands are run and havefinished. The AfterFunc is run even if Action() panics.
typeArgs¶
type Args interface {// Get returns the nth argument, or else a blank stringGet(nint)string// First returns the first argument, or else a blank stringFirst()string// Tail returns the rest of the arguments (not the first one)// or else an empty string sliceTail() []string// Len returns the length of the wrapped sliceLen()int// Present checks if there are any arguments presentPresent()bool// Slice returns a copy of the internal sliceSlice() []string}
typeArgumentBase¶
type ArgumentBase[Tany, Cany, VCValueCreator[T, C]] struct {Namestring `json:"name"`// the name of this argumentValue T `json:"value"`// the default value of this argumentDestination *T `json:"-"`// the destination point for this argumentValues *[]T `json:"-"`// all the values of this argument, only if multiple are supportedUsageTextstring `json:"usageText"`// the usage text to showMinint `json:"minTimes"`// the min num of occurrences of this argumentMaxint `json:"maxTimes"`// the max num of occurrences of this argument, set to -1 for unlimitedConfig C `json:"config"`// config for this argument similar to Flag Config}
func (*ArgumentBase[T, C, VC])Parse¶
func (a *ArgumentBase[T, C, VC]) Parse(s []string) ([]string,error)
func (*ArgumentBase[T, C, VC])Usage¶
func (a *ArgumentBase[T, C, VC]) Usage()string
typeBeforeFunc¶
BeforeFunc is an action that executes prior to any subcommands being run oncethe context is ready. If a non-nil error is returned, no subcommands arerun.
typeBoolConfig¶
type BoolConfig struct {Count *int}
BoolConfig defines the configuration for bool flags
typeBoolFlag¶
type BoolFlag =FlagBase[bool,BoolConfig, boolValue]
typeBoolWithInverseFlag¶
type BoolWithInverseFlag struct {Namestring `json:"name"`// name of the flagCategorystring `json:"category"`// category of the flag, if anyDefaultTextstring `json:"defaultText"`// default text of the flag for usage purposesHideDefaultbool `json:"hideDefault"`// whether to hide the default value in outputUsagestring `json:"usage"`// usage string for help outputSourcesValueSourceChain `json:"-"`// sources to load flag value fromRequiredbool `json:"required"`// whether the flag is required or notHiddenbool `json:"hidden"`// whether to hide the flag in help outputLocalbool `json:"local"`// whether the flag needs to be applied to subcommands as wellValuebool `json:"defaultValue"`// default value for this flag if not set by from any sourceDestination *bool `json:"-"`// destination pointer for value when setAliases []string `json:"aliases"`// Aliases that are allowed for this flagTakesFilebool `json:"takesFileArg"`// whether this flag takes a file argument, mainly for shell completion purposesAction func(context.Context, *Command,bool)error `json:"-"`// Action callback to be called when flag is setOnlyOncebool `json:"onlyOnce"`// whether this flag can be duplicated on the command lineValidator func(bool)error `json:"-"`// custom function to validate this flag valueValidateDefaultsbool `json:"validateDefaults"`// whether to validate defaults or notConfigBoolConfig `json:"config"`// Additional/Custom configuration associated with this flag typeInversePrefixstring `json:"invPrefix"`// The prefix used to indicate a negative value. Default: `env` becomes `no-env`// contains filtered or unexported fields}
Example¶
package mainimport ("context""fmt"cli "github.com/urfave/cli/v3")func main() {flagWithInverse := &cli.BoolWithInverseFlag{Name: "env",}cmd := &cli.Command{Flags: []cli.Flag{flagWithInverse,},Action: func(_ context.Context, cmd *cli.Command) error {if flagWithInverse.IsSet() {if cmd.Bool("env") {fmt.Println("env is set")} else {fmt.Println("no-env is set")}}return nil},}_ = cmd.Run(context.Background(), []string{"prog", "--no-env"})fmt.Println("flags:", len(flagWithInverse.Names()))}
Output:no-env is setflags: 2
func (*BoolWithInverseFlag)Count¶
func (bif *BoolWithInverseFlag) Count()int
Count returns the number of times this flag has been invoked
func (*BoolWithInverseFlag)Get¶
func (bif *BoolWithInverseFlag) Get()any
func (*BoolWithInverseFlag)GetCategory¶
func (bif *BoolWithInverseFlag) GetCategory()string
GetCategory returns the category of the flag
func (*BoolWithInverseFlag)GetDefaultText¶
func (bif *BoolWithInverseFlag) GetDefaultText()string
GetDefaultText returns the default text for this flag
func (*BoolWithInverseFlag)GetEnvVars¶
func (bif *BoolWithInverseFlag) GetEnvVars() []string
GetEnvVars returns the env vars for this flag
func (*BoolWithInverseFlag)GetUsage¶
func (bif *BoolWithInverseFlag) GetUsage()string
GetUsage returns the usage string for the flag
func (*BoolWithInverseFlag)GetValue¶
func (bif *BoolWithInverseFlag) GetValue()string
GetValue returns the flags value as string representation and an emptystring if the flag takes no value at all.
func (*BoolWithInverseFlag)IsBoolFlag¶
func (bif *BoolWithInverseFlag) IsBoolFlag()bool
IsBoolFlag returns whether the flag doesnt need to accept args
func (*BoolWithInverseFlag)IsDefaultVisible¶
func (bif *BoolWithInverseFlag) IsDefaultVisible()bool
IsDefaultVisible returns true if the flag is not hidden, otherwise false
func (*BoolWithInverseFlag)IsSet¶
func (bif *BoolWithInverseFlag) IsSet()bool
func (*BoolWithInverseFlag)Names¶
func (bif *BoolWithInverseFlag) Names() []string
func (*BoolWithInverseFlag)PostParse¶
func (bif *BoolWithInverseFlag) PostParse()error
func (*BoolWithInverseFlag)PreParse¶
func (bif *BoolWithInverseFlag) PreParse()error
func (*BoolWithInverseFlag)RunAction¶
func (bif *BoolWithInverseFlag) RunAction(ctxcontext.Context, cmd *Command)error
func (*BoolWithInverseFlag)Set¶
func (bif *BoolWithInverseFlag) Set(name, valstring)error
func (*BoolWithInverseFlag)SetCategory¶
func (bif *BoolWithInverseFlag) SetCategory(cstring)
func (*BoolWithInverseFlag)String¶
func (bif *BoolWithInverseFlag) String()string
String implements the standard Stringer interface.
Example for BoolFlag{Name: "env"}--[no-]env(default: false)
func (*BoolWithInverseFlag)TakesValue¶
func (bif *BoolWithInverseFlag) TakesValue()bool
func (*BoolWithInverseFlag)TypeName¶
func (bif *BoolWithInverseFlag) TypeName()string
TypeName is used for stringify/docs. For bool its a no-op
typeCategorizableFlag¶
type CategorizableFlag interface {// Returns the category of the flagGetCategory()string// Sets the category of the flagSetCategory(string)}
CategorizableFlag is an interface that allows us to potentiallyuse a flag in a categorized representation.
typeCommand¶
type Command struct {// The name of the commandNamestring `json:"name"`// A list of aliases for the commandAliases []string `json:"aliases"`// A short description of the usage of this commandUsagestring `json:"usage"`// Text to override the USAGE section of helpUsageTextstring `json:"usageText"`// A short description of the arguments of this commandArgsUsagestring `json:"argsUsage"`// Version of the commandVersionstring `json:"version"`// Longer explanation of how the command worksDescriptionstring `json:"description"`// DefaultCommand is the (optional) name of a command// to run if no command names are passed as CLI arguments.DefaultCommandstring `json:"defaultCommand"`// The category the command is part ofCategorystring `json:"category"`// List of child commandsCommands []*Command `json:"commands"`// List of flags to parseFlags []Flag `json:"flags"`// Boolean to hide built-in help command and help flagHideHelpbool `json:"hideHelp"`// Ignored if HideHelp is true.HideHelpCommandbool `json:"hideHelpCommand"`// Boolean to hide built-in version flag and the VERSION section of helpHideVersionbool `json:"hideVersion"`// Boolean to enable shell completion commandsEnableShellCompletionbool `json:"-"`// Shell Completion generation command nameShellCompletionCommandNamestring `json:"-"`// The function to call when checking for shell command completionsShellCompleteShellCompleteFunc `json:"-"`// An action to execute before any subcommands are run, but after the context is ready// If a non-nil error is returned, no subcommands are runBeforeBeforeFunc `json:"-"`// An action to execute after any subcommands are run, but after the subcommand has finished// It is run even if Action() panicsAfterAfterFunc `json:"-"`// The function to call when this command is invokedActionActionFunc `json:"-"`// Execute this function if the proper command cannot be foundCommandNotFoundCommandNotFoundFunc `json:"-"`// Execute this function if a usage error occurs.OnUsageErrorOnUsageErrorFunc `json:"-"`// Execute this function when an invalid flag is accessed from the contextInvalidFlagAccessHandlerInvalidFlagAccessFunc `json:"-"`// Boolean to hide this command from help or completionHiddenbool `json:"hidden"`// List of all authors who contributed (string or fmt.Stringer)// TODO: ~string | fmt.Stringer when interface unions are availableAuthors []any `json:"authors"`// Copyright of the binary if anyCopyrightstring `json:"copyright"`// Reader reader to write input to (useful for tests)Readerio.Reader `json:"-"`// Writer writer to write output toWriterio.Writer `json:"-"`// ErrWriter writes error outputErrWriterio.Writer `json:"-"`// ExitErrHandler processes any error encountered while running an App before// it is returned to the caller. If no function is provided, HandleExitCoder// is used as the default behavior.ExitErrHandlerExitErrHandlerFunc `json:"-"`// Other custom infoMetadata map[string]interface{} `json:"metadata"`// Carries a function which returns app specific info.ExtraInfo func() map[string]string `json:"-"`// CustomRootCommandHelpTemplate the text template for app help topic.// cli.go uses text/template to render templates. You can// render custom help text by setting this variable.CustomRootCommandHelpTemplatestring `json:"-"`// SliceFlagSeparator is used to customize the separator for SliceFlag, the default is ","SliceFlagSeparatorstring `json:"sliceFlagSeparator"`// DisableSliceFlagSeparator is used to disable SliceFlagSeparator, the default is falseDisableSliceFlagSeparatorbool `json:"disableSliceFlagSeparator"`// Boolean to enable short-option handling so user can combine several// single-character bool arguments into one// i.e. foobar -o -v -> foobar -ovUseShortOptionHandlingbool `json:"useShortOptionHandling"`// Enable suggestions for commands and flagsSuggestbool `json:"suggest"`// Allows global flags set by libraries which use flag.XXXVar(...) directly// to be parsed through this libraryAllowExtFlagsbool `json:"allowExtFlags"`// Treat all flags as normal arguments if trueSkipFlagParsingbool `json:"skipFlagParsing"`// CustomHelpTemplate the text template for the command help topic.// cli.go uses text/template to render templates. You can// render custom help text by setting this variable.CustomHelpTemplatestring `json:"-"`// Use longest prefix match for commandsPrefixMatchCommandsbool `json:"prefixMatchCommands"`// Custom suggest command for matchingSuggestCommandFuncSuggestCommandFunc `json:"-"`// Flag exclusion groupMutuallyExclusiveFlags []MutuallyExclusiveFlags `json:"mutuallyExclusiveFlags"`// Arguments to parse for this commandArguments []Argument `json:"arguments"`// Whether to read arguments from stdin// applicable to root command onlyReadArgsFromStdinbool `json:"readArgsFromStdin"`// contains filtered or unexported fields}
Command contains everything needed to run an application thataccepts a string slice of arguments such as os.Args. A givenCommand may contain Flags and sub-commands in Commands.
func (*Command)FlagNames¶
FlagNames returns a slice of flag names used by the this commandand all of its parent commands.
func (*Command)FloatSlice¶
FloatSlice looks up the value of a local FloatSliceFlag, returnsnil if not found
func (*Command)FullName¶
FullName returns the full name of the command.For commands with parents this ensures that the parent commandsare part of the command path.
func (*Command)IntSlice¶
IntSlice looks up the value of a local IntSliceFlag, returnsnil if not found
func (*Command)Lineage¶
Lineage returns *this* command and all of its ancestor commandsin order from child to parent
func (*Command)LocalFlagNames¶
LocalFlagNames returns a slice of flag names used in thiscommand.
func (*Command)Run¶
Run is the entry point to the command graph. The positionalarguments are parsed according to the Flag and Commanddefinitions and the matching Action functions are run.
Example¶
package mainimport ("context""fmt""net/mail""os"cli "github.com/urfave/cli/v3")func main() {// Declare a commandcmd := &cli.Command{Name: "greet",Flags: []cli.Flag{&cli.StringFlag{Name: "name", Value: "pat", Usage: "a name to say"},},Action: func(_ context.Context, cmd *cli.Command) error {fmt.Printf("Hello %[1]v\n", cmd.String("name"))return nil},Authors: []any{&mail.Address{Name: "Oliver Allen", Address: "oliver@toyshop.example.com"},"gruffalo@soup-world.example.org",},Version: "v0.13.12",}// Simulate the command line argumentsos.Args = []string{"greet", "--name", "Jeremy"}if err := cmd.Run(context.Background(), os.Args); err != nil {// do something with unhandled errorsfmt.Fprintf(os.Stderr, "Unhandled error: %[1]v\n", err)os.Exit(86)}}
Output:Hello Jeremy
Example (AppHelp)¶
package mainimport ("context""fmt""net/mail""os""time"cli "github.com/urfave/cli/v3")func main() {cmd := &cli.Command{Name: "greet",Version: "0.1.0",Description: "This is how we describe greet the app",Authors: []any{&mail.Address{Name: "Harrison", Address: "harrison@lolwut.example.com"},"Oliver Allen <oliver@toyshop.example.com>",},Flags: []cli.Flag{&cli.StringFlag{Name: "name", Value: "bob", Usage: "a name to say"},},Arguments: cli.AnyArguments,Commands: []*cli.Command{{Name: "describeit",Aliases: []string{"d"},Usage: "use it to see a description",Description: "This is how we describe describeit the function",ArgsUsage: "[arguments...]",Action: func(context.Context, *cli.Command) error {fmt.Printf("i like to describe things")return nil},},},}ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)defer cancel()// Simulate the command line argumentsos.Args = []string{"greet", "help"}_ = cmd.Run(ctx, os.Args)}
Output:NAME: greet - A new cli applicationUSAGE: greet [global options] [command [command options]] [arguments...]VERSION: 0.1.0DESCRIPTION: This is how we describe greet the appAUTHORS: "Harrison" <harrison@lolwut.example.com> Oliver Allen <oliver@toyshop.example.com>COMMANDS: describeit, d use it to see a description help, h Shows a list of commands or help for one commandGLOBAL OPTIONS: --name string a name to say (default: "bob") --help, -h show help --version, -v print the version
Example (CommandHelp)¶
package mainimport ("context""fmt""os"cli "github.com/urfave/cli/v3")func main() {cmd := &cli.Command{Name: "greet",Flags: []cli.Flag{&cli.StringFlag{Name: "name", Value: "pat", Usage: "a name to say"},},Action: func(_ context.Context, cmd *cli.Command) error {fmt.Fprintf(cmd.Root().Writer, "hello to %[1]q\n", cmd.String("name"))return nil},Commands: []*cli.Command{{Name: "describeit",Aliases: []string{"d"},Usage: "use it to see a description",Description: "This is how we describe describeit the function",ArgsUsage: "[arguments...]",Action: func(context.Context, *cli.Command) error {fmt.Println("i like to describe things")return nil},},},}// Simulate the command line argumentsos.Args = []string{"greet", "h", "describeit"}_ = cmd.Run(context.Background(), os.Args)}
Output:NAME: greet describeit - use it to see a descriptionUSAGE: greet describeit [arguments...]DESCRIPTION: This is how we describe describeit the functionOPTIONS: --help, -h show help
Example (MapValues)¶
package mainimport ("context""fmt""os"cli "github.com/urfave/cli/v3")func main() {cmd := &cli.Command{Name: "multi_values",Flags: []cli.Flag{&cli.StringMapFlag{Name: "stringMap"},},HideHelp: true,Action: func(ctx context.Context, cmd *cli.Command) error {for i, v := range cmd.FlagNames() {fmt.Printf("%d-%s %#v\n", i, v, cmd.StringMap(v))}fmt.Printf("notfound %#v\n", cmd.StringMap("notfound"))err := ctx.Err()fmt.Println("error:", err)return err},}// Simulate command line argumentsos.Args = []string{"multi_values","--stringMap", "parsed1=parsed two", "--stringMap", "parsed3=",}_ = cmd.Run(context.Background(), os.Args)}
Output:0-stringMap map[string]string{"parsed1":"parsed two", "parsed3":""}notfound map[string]string(nil)error: <nil>
Example (NoAction)¶
package mainimport ("context""os"cli "github.com/urfave/cli/v3")func main() {cmd := &cli.Command{Name: "greet"}// Simulate the command line argumentsos.Args = []string{"greet"}_ = cmd.Run(context.Background(), os.Args)}
Output:NAME: greet - A new cli applicationUSAGE: greet [global options]GLOBAL OPTIONS: --help, -h show help
Example (ShellComplete_bash)¶
package mainimport ("context""fmt""os"cli "github.com/urfave/cli/v3")func main() {cmd := &cli.Command{Name: "greet",EnableShellCompletion: true,Commands: []*cli.Command{{Name: "describeit",Aliases: []string{"d"},Usage: "use it to see a description",Description: "This is how we describe describeit the function",Action: func(context.Context, *cli.Command) error {fmt.Printf("i like to describe things")return nil},}, {Name: "next",Usage: "next example",Description: "more stuff to see when generating shell completion",Action: func(context.Context, *cli.Command) error {fmt.Printf("the next example")return nil},},},}// Simulate a bash environment and command line argumentsos.Setenv("SHELL", "bash")os.Args = []string{"greet", "--generate-shell-completion"}_ = cmd.Run(context.Background(), os.Args)}
Output:describeitnexthelp
Example (ShellComplete_bash_withLongFlag)¶
package mainimport ("context""os"cli "github.com/urfave/cli/v3")func main() {cmd := &cli.Command{Name: "greet",EnableShellCompletion: true,Flags: []cli.Flag{&cli.IntFlag{Name: "other",Aliases: []string{"o"},},&cli.StringFlag{Name: "xyz",Aliases: []string{"x"},},&cli.StringFlag{Name: "some-flag,s",},&cli.StringFlag{Name: "similar-flag",},},}// Simulate a bash environment and command line argumentsos.Setenv("SHELL", "bash")os.Args = []string{"greet", "--s", "--generate-shell-completion"}_ = cmd.Run(context.Background(), os.Args)}
Output:--some-flag--similar-flag
Example (ShellComplete_bash_withMultipleLongFlag)¶
package mainimport ("context""os"cli "github.com/urfave/cli/v3")func main() {cmd := &cli.Command{Name: "greet",EnableShellCompletion: true,Flags: []cli.Flag{&cli.IntFlag{Name: "int-flag",Aliases: []string{"i"},},&cli.StringFlag{Name: "string",Aliases: []string{"s"},},&cli.StringFlag{Name: "string-flag-2",},&cli.StringFlag{Name: "similar-flag",},&cli.StringFlag{Name: "some-flag",},},}// Simulate a bash environment and command line argumentsos.Setenv("SHELL", "bash")os.Args = []string{"greet", "--st", "--generate-shell-completion"}_ = cmd.Run(context.Background(), os.Args)}
Output:--string--string-flag-2
Example (ShellComplete_bash_withShortFlag)¶
package mainimport ("context""os"cli "github.com/urfave/cli/v3")func main() {cmd := &cli.Command{Name: "greet",EnableShellCompletion: true,Flags: []cli.Flag{&cli.IntFlag{Name: "other",Aliases: []string{"o"},},&cli.StringFlag{Name: "xyz",Aliases: []string{"x"},},},}// Simulate a bash environment and command line argumentsos.Setenv("SHELL", "bash")os.Args = []string{"greet", "-", "--generate-shell-completion"}_ = cmd.Run(context.Background(), os.Args)}
Output:--other--xyz--help
Example (ShellComplete_zsh)¶
package mainimport ("context""fmt""os"cli "github.com/urfave/cli/v3")func main() {cmd := &cli.Command{Name: "greet",EnableShellCompletion: true,Commands: []*cli.Command{{Name: "describeit",Aliases: []string{"d"},Usage: "use it to see a description",Description: "This is how we describe describeit the function",Action: func(context.Context, *cli.Command) error {fmt.Printf("i like to describe things")return nil},}, {Name: "next",Usage: "next example",Description: "more stuff to see when generating bash completion",Action: func(context.Context, *cli.Command) error {fmt.Printf("the next example")return nil},},},}// Simulate a zsh environment and command line argumentsos.Args = []string{"greet", "--generate-shell-completion"}os.Setenv("SHELL", "/usr/bin/zsh")_ = cmd.Run(context.Background(), os.Args)}
Output:describeit:use it to see a descriptionnext:next examplehelp:Shows a list of commands or help for one command
Example (SliceValues)¶
package mainimport ("context""fmt""os"cli "github.com/urfave/cli/v3")func main() {cmd := &cli.Command{Name: "multi_values",Flags: []cli.Flag{&cli.StringSliceFlag{Name: "stringSlice"},&cli.FloatSliceFlag{Name: "float64Slice"},&cli.IntSliceFlag{Name: "intSlice"},},HideHelp: true,Action: func(ctx context.Context, cmd *cli.Command) error {for i, v := range cmd.FlagNames() {fmt.Printf("%d-%s %#v\n", i, v, cmd.Value(v))}err := ctx.Err()fmt.Println("error:", err)return err},}// Simulate command line argumentsos.Args = []string{"multi_values","--stringSlice", "parsed1,parsed2", "--stringSlice", "parsed3,parsed4","--float64Slice", "13.3,14.4", "--float64Slice", "15.5,16.6","--intSlice", "13,14", "--intSlice", "15,16",}_ = cmd.Run(context.Background(), os.Args)}
Output:0-stringSlice []string{"parsed1", "parsed2", "parsed3", "parsed4"}1-float64Slice []float64{13.3, 14.4, 15.5, 16.6}2-intSlice []int64{13, 14, 15, 16}error: <nil>
Example (Subcommand)¶
package mainimport ("context""fmt""os""time"cli "github.com/urfave/cli/v3")func main() {cmd := &cli.Command{Name: "say",Commands: []*cli.Command{{Name: "hello",Aliases: []string{"hi"},Usage: "use it to see a description",Description: "This is how we describe hello the function",Commands: []*cli.Command{{Name: "english",Aliases: []string{"en"},Usage: "sends a greeting in english",Description: "greets someone in english",Flags: []cli.Flag{&cli.StringFlag{Name: "name",Value: "Bob",Usage: "Name of the person to greet",},},Action: func(_ context.Context, cmd *cli.Command) error {fmt.Println("Hello,", cmd.String("name"))return nil},},},},},}ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)defer cancel()// Simulate the command line argumentsos.Args = []string{"say", "hi", "english", "--name", "Jeremy"}_ = cmd.Run(ctx, os.Args)}
Output:Hello, Jeremy
Example (SubcommandNoAction)¶
package mainimport ("context""os"cli "github.com/urfave/cli/v3")func main() {cmd := &cli.Command{Name: "greet",Commands: []*cli.Command{{Name: "describeit",Aliases: []string{"d"},Usage: "use it to see a description",ArgsUsage: "[arguments...]",Description: "This is how we describe describeit the function",},},}// Simulate the command line argumentsos.Args = []string{"greet", "describeit"}_ = cmd.Run(context.Background(), os.Args)}
Output:NAME: greet describeit - use it to see a descriptionUSAGE: greet describeit [command [command options]] [arguments...]DESCRIPTION: This is how we describe describeit the functionOPTIONS: --help, -h show help
func (*Command)StringMap¶
StringMap looks up the value of a local StringMapFlag, returnsnil if not found
func (*Command)StringSlice¶
StringSlice looks up the value of a local StringSliceFlag, returnsnil if not found
func (*Command)ToFishCompletion¶
ToFishCompletion creates a fish completion string for the `*App`The function errors if either parsing or writing of the string fails.
func (*Command)UintSlice¶
UintSlice looks up the value of a local UintSliceFlag, returnsnil if not found
func (*Command)VisibleCategories¶
func (cmd *Command) VisibleCategories() []CommandCategory
VisibleCategories returns a slice of categories and commands that areHidden=false
func (*Command)VisibleCommands¶
VisibleCommands returns a slice of the Commands with Hidden=false
func (*Command)VisibleFlagCategories¶
func (cmd *Command) VisibleFlagCategories() []VisibleFlagCategory
VisibleFlagCategories returns a slice containing all the visible flag categories with the flags they contain
func (*Command)VisibleFlags¶
VisibleFlags returns a slice of the Flags with Hidden=false
func (*Command)VisiblePersistentFlags¶
VisiblePersistentFlags returns a slice ofLocalFlag with Persistent=true and Hidden=false.
typeCommandCategories¶
type CommandCategories interface {// AddCommand adds a command to a category, creating a new category if necessary.AddCommand(categorystring, command *Command)// Categories returns a slice of categories sorted by nameCategories() []CommandCategory}
CommandCategories interface allows for category manipulation
typeCommandCategory¶
type CommandCategory interface {// Name returns the category name stringName()string// VisibleCommands returns a slice of the Commands with Hidden=falseVisibleCommands() []*Command}
CommandCategory is a category containing commands.
typeCommandNotFoundFunc¶
CommandNotFoundFunc is executed if the proper command cannot be found
typeCountable¶
type Countable interface {Count()int}
Countable is an interface to enable detection of flag values which supportrepetitive flags
typeDocGenerationFlag¶
type DocGenerationFlag interface {// TakesValue returns true if the flag takes a value, otherwise falseTakesValue()bool// GetUsage returns the usage string for the flagGetUsage()string// GetValue returns the flags value as string representation and an empty// string if the flag takes no value at all.GetValue()string// GetDefaultText returns the default text for this flagGetDefaultText()string// GetEnvVars returns the env vars for this flagGetEnvVars() []string// IsDefaultVisible returns whether the default value should be shown in// help textIsDefaultVisible()bool// TypeName to detect if a flag is a string, bool, etc.TypeName()string}
DocGenerationFlag is an interface that allows documentation generation for the flag
typeDocGenerationMultiValueFlag¶
type DocGenerationMultiValueFlag interface {DocGenerationFlag// IsMultiValueFlag returns true for flags that can be given multiple times.IsMultiValueFlag()bool}
DocGenerationMultiValueFlag extends DocGenerationFlag for slice/map based flags.
typeEnvValueSource¶
EnvValueSource is to specifically detect env sources whenprinting help text
typeErrorFormatter¶
ErrorFormatter is the interface that will suitably format the error output
typeExitCoder¶
ExitCoder is the interface checked by `App` and `Command` for a custom exitcode
funcExit¶
Exit wraps a message and exit code into an error, which by default ishandled with a call to os.Exit during default error handling.
This is the simplest way to trigger a non-zero exit code for an App withouthaving to call os.Exit manually. During testing, this behavior can be avoidedby overriding the ExitErrHandler function on an App or the package-globalOsExiter function.
typeExitErrHandlerFunc¶
ExitErrHandlerFunc is executed if provided in order to handle exitError valuesreturned by Actions and Before/After functions.
typeFlag¶
type Flag interface {fmt.Stringer// Retrieve the value of the FlagGet()any// Lifecycle methods.// flag callback prior to parsingPreParse()error// flag callback post parsingPostParse()error// Apply Flag settings to the given flag setSet(string,string)error// All possible names for this flagNames() []string// Whether the flag has been set or notIsSet()bool}
Flag is a common interface related to parsing flags in cli.For more advanced flag parsing techniques, it is recommended thatthis interface be implemented.
GenerateShellCompletionFlag enables shell completion
typeFlagBase¶
type FlagBase[Tany, Cany, VCValueCreator[T, C]] struct {Namestring `json:"name"`// name of the flagCategorystring `json:"category"`// category of the flag, if anyDefaultTextstring `json:"defaultText"`// default text of the flag for usage purposesHideDefaultbool `json:"hideDefault"`// whether to hide the default value in outputUsagestring `json:"usage"`// usage string for help outputSourcesValueSourceChain `json:"-"`// sources to load flag value fromRequiredbool `json:"required"`// whether the flag is required or notHiddenbool `json:"hidden"`// whether to hide the flag in help outputLocalbool `json:"local"`// whether the flag needs to be applied to subcommands as wellValue T `json:"defaultValue"`// default value for this flag if not set by from any sourceDestination *T `json:"-"`// destination pointer for value when setAliases []string `json:"aliases"`// Aliases that are allowed for this flagTakesFilebool `json:"takesFileArg"`// whether this flag takes a file argument, mainly for shell completion purposesAction func(context.Context, *Command, T)error `json:"-"`// Action callback to be called when flag is setConfig C `json:"config"`// Additional/Custom configuration associated with this flag typeOnlyOncebool `json:"onlyOnce"`// whether this flag can be duplicated on the command lineValidator func(T)error `json:"-"`// custom function to validate this flag valueValidateDefaultsbool `json:"validateDefaults"`// whether to validate defaults or not// contains filtered or unexported fields}
FlagBase [T,C,VC] is a generic flag base which can be usedas a boilerplate to implement the most common interfacesused by urfave/cli.
T specifies the typeC specifies the configuration required(if any for that flag type)VC specifies the value creator which creates the flag.Value emulation
func (*FlagBase[T, C, V])GetCategory¶
GetCategory returns the category of the flag
func (*FlagBase[T, C, V])GetDefaultText¶
GetDefaultText returns the default text for this flag
func (*FlagBase[T, C, V])GetEnvVars¶
GetEnvVars returns the env vars for this flag
func (*FlagBase[T, C, V])GetValue¶
GetValue returns the flags value as string representation and an emptystring if the flag takes no value at all.
func (*FlagBase[T, C, VC])IsBoolFlag¶
IsBoolFlag returns whether the flag doesnt need to accept args
func (*FlagBase[T, C, V])IsDefaultVisible¶
IsDefaultVisible returns true if the flag is not hidden, otherwise false
func (*FlagBase[T, C, VC])IsLocal¶
IsLocal returns false if flag needs to be persistent across subcommands
func (*FlagBase[T, C, VC])IsMultiValueFlag¶
IsMultiValueFlag returns true if the value type T can take multiplevalues from cmd line. This is true for slice and map type flags
func (*FlagBase[T, C, V])IsRequired¶
IsRequired returns whether or not the flag is required
func (*FlagBase[T, C, V])IsSet¶
IsSet returns whether or not the flag has been set through env or file
func (*FlagBase[T, C, V])IsVisible¶
IsVisible returns true if the flag is not hidden, otherwise false
func (*FlagBase[T, C, V])SetCategory¶
func (*FlagBase[T, C, V])String¶
String returns a readable representation of this value (for usage defaults)
func (*FlagBase[T, C, V])TakesValue¶
TakesValue returns true if the flag takes a value, otherwise false
typeFlagCategories¶
type FlagCategories interface {// AddFlags adds a flag to a category, creating a new category if necessary.AddFlag(categorystring, flFlag)// VisibleCategories returns a slice of visible flag categories sorted by nameVisibleCategories() []VisibleFlagCategory}
FlagCategories interface allows for category manipulation
typeFlagEnvHintFunc¶
FlagEnvHintFunc is used by the default FlagStringFunc to annotate flag helpwith the environment variable details.
var FlagEnvHinterFlagEnvHintFunc = withEnvHint
FlagEnvHinter annotates flag help message with the environment variabledetails. This is used by the default FlagStringer.
typeFlagFileHintFunc¶
FlagFileHintFunc is used by the default FlagStringFunc to annotate flag helpwith the file path details.
var FlagFileHinterFlagFileHintFunc = withFileHint
FlagFileHinter annotates flag help message with the environment variabledetails. This is used by the default FlagStringer.
typeFlagNamePrefixFunc¶
FlagNamePrefixFunc is used by the default FlagStringFunc to create prefixtext for a flag's full name.
var FlagNamePrefixerFlagNamePrefixFunc = prefixedNames
FlagNamePrefixer converts a full flag name and its placeholder into the helpmessage flag prefix. This is used by the default FlagStringer.
typeFlagStringFunc¶
FlagStringFunc is used by the help generation to display a flag, which isexpected to be a single line.
var FlagStringerFlagStringFunc = stringifyFlag
FlagStringer converts a flag definition to a string. This is used by helpto display a flag.
typeFlagsByName¶
type FlagsByName []Flag
FlagsByName is a slice of Flag.
func (FlagsByName)Len¶
func (fFlagsByName) Len()int
func (FlagsByName)Less¶
func (fFlagsByName) Less(i, jint)bool
func (FlagsByName)Swap¶
func (fFlagsByName) Swap(i, jint)
typeFloatArg¶
type FloatArg =ArgumentBase[float64,NoConfig, floatValue]
typeFloatSlice¶
typeFloatSliceFlag¶
type FloatSliceFlag =FlagBase[[]float64,NoConfig,FloatSlice]
typeGenericFlag¶
typeIntArg¶
type IntArg =ArgumentBase[int64,IntegerConfig, intValue]
typeIntFlag¶
type IntFlag =FlagBase[int64,IntegerConfig, intValue]
typeIntSlice¶
type IntSlice =SliceBase[int64,IntegerConfig, intValue]
typeIntSliceFlag¶
type IntSliceFlag =FlagBase[[]int64,IntegerConfig,IntSlice]
typeIntegerConfig¶
type IntegerConfig struct {Baseint}
IntegerConfig is the configuration for all integer type flags
typeInvalidFlagAccessFunc¶
InvalidFlagAccessFunc is executed when an invalid flag is accessed from the context.
typeLocalFlag¶
type LocalFlag interface {IsLocal()bool}
LocalFlag is an interface to enable detection of flags which are localto current command
typeMapBase¶
type MapBase[Tany, Cany, VCValueCreator[T, C]] struct {// contains filtered or unexported fields}
MapBase wraps map[string]T to satisfy flag.Value
funcNewMapBase¶
func NewMapBase[Tany, Cany, VCValueCreator[T, C]](defaults map[string]T) *MapBase[T, C, VC]
NewMapBase makes a *MapBase with default values
func (*MapBase[T, C, VC])Get¶
func (i *MapBase[T, C, VC]) Get() interface{}
Get returns the mapping of values set by this flag
typeMapSource¶
type MapSource interface {fmt.Stringerfmt.GoStringer// Lookup returns the value from the source based on key// and if it was found// or returns an empty string and falseLookup(string) (any,bool)}
MapSource is a source which can be used to look up a valuebased on a keytypically for use with a cli.Flag
typeMultiError¶
MultiError is an error that wraps multiple errors.
typeMutuallyExclusiveFlags¶
type MutuallyExclusiveFlags struct {// Flag listFlags [][]Flag// whether this group is requiredRequiredbool// Category to apply to all flags within groupCategorystring}
MutuallyExclusiveFlags defines a mutually exclusive flag groupMultiple option paths can be provided out of whichonly one can be defined on cmdlineSo for example[ --foo | [ --bar something --darth somethingelse ] ]
typeOnUsageErrorFunc¶
OnUsageErrorFunc is executed if a usage error occurs. This is useful for displayingcustomized usage error messages. This function is able to replace theoriginal error messages. If this function is not set, the "Incorrect usage"is displayed and the execution is interrupted.
typeRequiredFlag¶
type RequiredFlag interface {// whether the flag is a required flag or notIsRequired()bool}
RequiredFlag is an interface that allows us to mark flags as requiredit allows flags required flags to be backwards compatible with the Flag interface
typeSerializer¶
type Serializer interface {Serialize()string}
Serializer is used to circumvent the limitations of flag.FlagSet.Set
typeShellCompleteFunc¶
ShellCompleteFunc is an action to execute when the shell completion flag is set
typeSliceBase¶
type SliceBase[Tany, Cany, VCValueCreator[T, C]] struct {// contains filtered or unexported fields}
SliceBase wraps []T to satisfy flag.Value
funcNewSliceBase¶
func NewSliceBase[Tany, Cany, VCValueCreator[T, C]](defaults ...T) *SliceBase[T, C, VC]
NewSliceBase makes a *SliceBase with default values
func (*SliceBase[T, C, VC])Get¶
func (i *SliceBase[T, C, VC]) Get() interface{}
Get returns the slice of values set by this flag
typeStringArg¶
type StringArg =ArgumentBase[string,StringConfig, stringValue]
typeStringConfig¶
type StringConfig struct {// Whether to trim whitespace of parsed valueTrimSpacebool}
StringConfig defines the configuration for string flags
typeStringFlag¶
type StringFlag =FlagBase[string,StringConfig, stringValue]
typeStringMap¶
type StringMap =MapBase[string,StringConfig, stringValue]
typeStringMapArg¶
type StringMapArg =ArgumentBase[map[string]string,StringConfig,StringMap]
typeStringMapFlag¶
type StringMapFlag =FlagBase[map[string]string,StringConfig,StringMap]
typeStringSlice¶
type StringSlice =SliceBase[string,StringConfig, stringValue]
typeStringSliceFlag¶
type StringSliceFlag =FlagBase[[]string,StringConfig,StringSlice]
typeTimestampArg¶
type TimestampArg =ArgumentBase[time.Time,TimestampConfig, timestampValue]
typeTimestampConfig¶
type TimestampConfig struct {Timezone *time.Location// Available layouts for flag value.//// Note that value for formats with missing year/date will be interpreted as current year/date respectively.//// Read more about time layouts:https://pkg.go.dev/time#pkg-constantsLayouts []string}
TimestampConfig defines the config for timestamp flags
typeTimestampFlag¶
type TimestampFlag =FlagBase[time.Time,TimestampConfig, timestampValue]
typeUintArg¶
type UintArg =ArgumentBase[uint64,IntegerConfig, uintValue]
typeUintFlag¶
type UintFlag =FlagBase[uint64,IntegerConfig, uintValue]
typeUintSlice¶
type UintSlice =SliceBase[uint64,IntegerConfig, uintValue]
typeUintSliceFlag¶
type UintSliceFlag =FlagBase[[]uint64,IntegerConfig,UintSlice]
typeValue¶
Value represents a value as used by cli.For now it implements the golang flag.Value interface
typeValueCreator¶
ValueCreator is responsible for creating a flag.Value emulationas well as custom formatting
T specifies the typeC specifies the config for the type
typeValueSource¶
type ValueSource interface {fmt.Stringerfmt.GoStringer// Lookup returns the value from the source and if it was found// or returns an empty string and falseLookup() (string,bool)}
ValueSource is a source which can be used to look up a value,typically for use with a cli.Flag
funcEnvVar¶
func EnvVar(keystring)ValueSource
funcFile¶
func File(pathstring)ValueSource
funcNewMapValueSource¶
func NewMapValueSource(keystring, msMapSource)ValueSource
typeValueSourceChain¶
type ValueSourceChain struct {Chain []ValueSource}
ValueSourceChain contains an ordered series of ValueSource thatallows for lookup where the first ValueSource to resolve isreturned
funcEnvVars¶
func EnvVars(keys ...string)ValueSourceChain
EnvVars is a helper function to encapsulate a number ofenvVarValueSource together as a ValueSourceChain
funcFiles¶
func Files(paths ...string)ValueSourceChain
Files is a helper function to encapsulate a number offileValueSource together as a ValueSourceChain
funcNewValueSourceChain¶
func NewValueSourceChain(src ...ValueSource)ValueSourceChain
func (*ValueSourceChain)Append¶
func (vsc *ValueSourceChain) Append(otherValueSourceChain)
func (*ValueSourceChain)EnvKeys¶
func (vsc *ValueSourceChain) EnvKeys() []string
func (*ValueSourceChain)GoString¶
func (vsc *ValueSourceChain) GoString()string
func (*ValueSourceChain)Lookup¶
func (vsc *ValueSourceChain) Lookup() (string,bool)
func (*ValueSourceChain)LookupWithSource¶
func (vsc *ValueSourceChain) LookupWithSource() (string,ValueSource,bool)
func (*ValueSourceChain)String¶
func (vsc *ValueSourceChain) String()string
typeVisibleFlag¶
type VisibleFlag interface {// IsVisible returns true if the flag is not hidden, otherwise falseIsVisible()bool}
VisibleFlag is an interface that allows to check if a flag is visible
typeVisibleFlagCategory¶
type VisibleFlagCategory interface {// Name returns the category name stringName()string// Flags returns a slice of VisibleFlag sorted by nameFlags() []Flag}
VisibleFlagCategory is a category containing flags.
Source Files¶
- args.go
- category.go
- cli.go
- command.go
- command_parse.go
- command_run.go
- command_setup.go
- completion.go
- docs.go
- errors.go
- fish.go
- flag.go
- flag_bool.go
- flag_bool_with_inverse.go
- flag_duration.go
- flag_ext.go
- flag_float.go
- flag_float_slice.go
- flag_generic.go
- flag_impl.go
- flag_int.go
- flag_int_slice.go
- flag_map_impl.go
- flag_mutex.go
- flag_slice_base.go
- flag_string.go
- flag_string_map.go
- flag_string_slice.go
- flag_timestamp.go
- flag_uint.go
- flag_uint_slice.go
- funcs.go
- help.go
- sort.go
- suggestions.go
- template.go
- value_source.go