Package cli provides a minimal framework for creating and organizing command line Go applications. cli is designed to be easy to understand and write, the most simple cli 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)
}
- Variables
- func DefaultCompleteWithFlags(ctx context.Context, cmd *Command)
- func DefaultPrintHelp(out io.Writer, templ string, data any)
- func DefaultPrintHelpCustom(out io.Writer, templ string, data any, customFuncs map[string]any)
- func DefaultPrintVersion(cmd *Command)
- func DefaultRootCommandComplete(ctx context.Context, cmd *Command)
- func DefaultShowCommandHelp(ctx context.Context, cmd *Command, commandName string) error
- func DefaultShowRootCommandHelp(cmd *Command) error
- func DefaultShowSubcommandHelp(cmd *Command) error
- func FlagNames(name string, aliases []string) []string
- func HandleExitCoder(err error)
- func ShowCommandHelpAndExit(ctx context.Context, cmd *Command, command string, code int)
- func ShowRootCommandHelpAndExit(cmd *Command, exitCode int)
- func ShowSubcommandHelpAndExit(cmd *Command, exitCode int)
- func ShowVersion(cmd *Command)
- type ActionFunc
- type ActionableFlag
- type AfterFunc
- type Args
- type Argument
- type ArgumentBase
- type ArgumentsBase
- 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) IsLocal() bool
- func (bif *BoolWithInverseFlag) IsRequired() bool
- func (bif *BoolWithInverseFlag) IsSet() bool
- func (bif *BoolWithInverseFlag) IsVisible() 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) SchemaItemsType() string
- func (bif *BoolWithInverseFlag) SchemaType() string
- 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) Float32(name string) float32
- func (c *Command) Float32Arg(name string) float32
- func (c *Command) Float32Args(name string) []float32
- func (cmd *Command) Float32Slice(name string) []float32
- func (cmd *Command) Float64(name string) float64
- func (c *Command) Float64Arg(name string) float64
- func (c *Command) Float64Args(name string) []float64
- func (cmd *Command) Float64Slice(name string) []float64
- func (c *Command) FloatArg(name string) float64
- func (c *Command) FloatArgs(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) int
- func (cmd *Command) Int8(name string) int8
- func (c *Command) Int8Arg(name string) int8
- func (c *Command) Int8Args(name string) []int8
- func (cmd *Command) Int8Slice(name string) []int8
- func (cmd *Command) Int16(name string) int16
- func (c *Command) Int16Arg(name string) int16
- func (c *Command) Int16Args(name string) []int16
- func (cmd *Command) Int16Slice(name string) []int16
- func (cmd *Command) Int32(name string) int32
- func (c *Command) Int32Arg(name string) int32
- func (c *Command) Int32Args(name string) []int32
- func (cmd *Command) Int32Slice(name string) []int32
- func (cmd *Command) Int64(name string) int64
- func (c *Command) Int64Arg(name string) int64
- func (c *Command) Int64Args(name string) []int64
- func (cmd *Command) Int64Slice(name string) []int64
- func (c *Command) IntArg(name string) int
- func (c *Command) IntArgs(name string) []int
- func (cmd *Command) IntSlice(name string) []int
- 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) Path() []string
- 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 (c *Command) StringArg(name string) string
- func (c *Command) StringArgs(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 (c *Command) TimestampArg(name string) time.Time
- func (c *Command) TimestampArgs(name string) []time.Time
- func (cmd *Command) ToFishCompletion() (string, error)
- func (cmd *Command) Uint(name string) uint
- func (cmd *Command) Uint8(name string) uint8
- func (c *Command) Uint8Arg(name string) uint8
- func (c *Command) Uint8Args(name string) []uint8
- func (cmd *Command) Uint8Slice(name string) []uint8
- func (cmd *Command) Uint16(name string) uint16
- func (c *Command) Uint16Arg(name string) uint16
- func (c *Command) Uint16Args(name string) []uint16
- func (cmd *Command) Uint16Slice(name string) []uint16
- func (cmd *Command) Uint32(name string) uint32
- func (c *Command) Uint32Arg(name string) uint32
- func (c *Command) Uint32Args(name string) []uint32
- func (cmd *Command) Uint32Slice(name string) []uint32
- func (cmd *Command) Uint64(name string) uint64
- func (c *Command) Uint64Arg(name string) uint64
- func (c *Command) Uint64Args(name string) []uint64
- func (cmd *Command) Uint64Slice(name string) []uint64
- func (c *Command) UintArg(name string) uint
- func (c *Command) UintArgs(name string) []uint
- func (cmd *Command) UintSlice(name string) []uint
- func (cmd *Command) Value(name string) any
- 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
- func (cmd *Command) Walk(fn func(*Command) error) error
- type CommandCategories
- type CommandCategory
- type CommandNotFoundFunc
- type ConfigureShellCompletionCommand
- 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]) SchemaItemsType() string
- func (f *FlagBase[T, C, V]) SchemaType() string
- 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 Float32Arg
- type Float32Args
- type Float32Flag
- type Float32Slice
- type Float32SliceFlag
- type Float64Arg
- type Float64Args
- type Float64Flag
- type Float64Slice
- type Float64SliceFlag
- type FloatArg
- type FloatArgs
- type FloatFlag
- type FloatSlice
- type FloatSliceFlag
- type GenericFlag
- type HelpPrinterCustomFunc
- type HelpPrinterFunc
- type Int8Arg
- type Int8Args
- type Int8Flag
- type Int8Slice
- type Int8SliceFlag
- type Int16Arg
- type Int16Args
- type Int16Flag
- type Int16Slice
- type Int16SliceFlag
- type Int32Arg
- type Int32Args
- type Int32Flag
- type Int32Slice
- type Int32SliceFlag
- type Int64Arg
- type Int64Args
- type Int64Flag
- type Int64Slice
- type Int64SliceFlag
- type IntArg
- type IntArgs
- 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() any
- 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 SchemaItemsTyper
- type SchemaTyper
- 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() any
- 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 StringArgs
- type StringConfig
- type StringFlag
- type StringMap
- type StringMapArgs
- type StringMapFlag
- type StringSlice
- type StringSliceFlag
- type SuggestCommandFunc
- type SuggestFlagFunc
- type TimestampArg
- type TimestampArgs
- type TimestampConfig
- type TimestampFlag
- type Uint8Arg
- type Uint8Args
- type Uint8Flag
- type Uint8Slice
- type Uint8SliceFlag
- type Uint16Arg
- type Uint16Args
- type Uint16Flag
- type Uint16Slice
- type Uint16SliceFlag
- type Uint32Arg
- type Uint32Args
- type Uint32Flag
- type Uint32Slice
- type Uint32SliceFlag
- type Uint64Arg
- type Uint64Args
- type Uint64Flag
- type Uint64Slice
- type Uint64SliceFlag
- type UintArg
- type UintArgs
- 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
- 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_fish)
- Command.Run (ShellComplete_zsh)
- Command.Run (SliceValues)
- Command.Run (Subcommand)
- Command.Run (SubcommandNoAction)
This section is empty.
var ( NewIntSlice = NewSliceBase[int, IntegerConfig, intValue[int]] NewInt8Slice = NewSliceBase[int8, IntegerConfig, intValue[int8]] NewInt16Slice = NewSliceBase[int16, IntegerConfig, intValue[int16]] NewInt32Slice = NewSliceBase[int32, IntegerConfig, intValue[int32]] NewInt64Slice = NewSliceBase[int64, IntegerConfig, intValue[int64]] )
var ( NewUintSlice = NewSliceBase[uint, IntegerConfig, uintValue[uint]] NewUint8Slice = NewSliceBase[uint8, IntegerConfig, uintValue[uint8]] NewUint16Slice = NewSliceBase[uint16, IntegerConfig, uintValue[uint16]] NewUint32Slice = NewSliceBase[uint32, IntegerConfig, uintValue[uint32]] NewUint64Slice = NewSliceBase[uint64, IntegerConfig, uintValue[uint64]] )
var ( SuggestFlag SuggestFlagFunc = suggestFlag SuggestCommand SuggestCommandFunc = suggestCommand SuggestDidYouMeanTemplate string = suggestDidYouMeanTemplate )
AnyArguments to differentiate between no arguments(nil) vs aleast one
ArgsUsageCommandHelp is a short description of the arguments of the help command
CommandHelpTemplate is 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.
DefaultAppComplete is a backward-compatible name for DefaultRootCommandComplete.
ErrWriter is used to write errors to the user. This can be anything implementing the io.Writer interface and defaults to os.Stderr.
OsExiter is the function used when the app exits. If not set defaults to os.Exit.
RootCommandHelpTemplate is the text template for the Default help topic. cli.go uses text/template to render templates. You can render custom help text by setting this variable.
ShowAppHelp is a backward-compatible name for ShowRootCommandHelp.
ShowAppHelpAndExit is a backward-compatible name for ShowRootCommandHelp.
ShowCommandHelp prints help for the given command
ShowRootCommandHelp is an action that displays help for the root command.
ShowSubcommandHelp prints help for the given subcommand
SubcommandHelpTemplate is the text template for the subcommand help topic. cli.go uses text/template to render templates. You can render custom help text by setting this variable.
var UsageCommandHelp = "Shows a list of commands or help for one command"
UsageCommandHelp is the text to override the USAGE section of the help command
VersionPrinter prints the version for the root Command.
DefaultPrintHelp is the default implementation of HelpPrinter.
DefaultPrintHelpCustom is the default implementation of HelpPrinterCustom.
The customFuncs map will be combined with a default template.FuncMap to allow using arbitrary functions in template rendering.
func DefaultPrintVersion(cmd *Command)
DefaultPrintVersion is the default implementation of VersionPrinter.
func DefaultRootCommandComplete ¶ added in v3.4.0
DefaultRootCommandComplete prints the list of subcommands as the default completion method.
func DefaultShowCommandHelp ¶ added in v3.4.0
DefaultShowCommandHelp is the default implementation of ShowCommandHelp.
func DefaultShowRootCommandHelp ¶ added in v3.4.0
DefaultShowRootCommandHelp is the default implementation of ShowRootCommandHelp.
func DefaultShowSubcommandHelp ¶ added in v3.4.0
DefaultShowSubcommandHelp is the default implementation of ShowSubcommandHelp.
func HandleExitCoder ¶
func HandleExitCoder(err error)
HandleExitCoder handles errors implementing ExitCoder by printing their message and calling OsExiter with the given exit code.
If the given error instead implements MultiError, each error will be checked for the ExitCoder interface, and OsExiter will be called with the last exit code found, or exit code 1 if no ExitCoder is found.
This function is the default error-handling behavior for a Command.
func ShowRootCommandHelpAndExit ¶ added in v3.4.0
ShowRootCommandHelpAndExit prints the list of subcommands and exits with exit code.
func ShowSubcommandHelpAndExit ¶
ShowSubcommandHelpAndExit prints help for the given subcommand via ShowSubcommandHelp and exits with exit code.
func ShowVersion(cmd *Command)
ShowVersion prints the version number of the root Command.
ActionFunc is the action to execute when no subcommands are specified
ActionableFlag is an interface that wraps Flag interface and RunAction operation.
AfterFunc is an action that executes after any subcommands are run and have finished. The AfterFunc is run even if Action() panics.
Argument captures a positional argument that can be parsed
type ArgumentBase[T any, C any, VC ValueCreator[T, C]] struct { Name string `json:"name"` Value T `json:"value"` Destination *T `json:"-"` UsageText string `json:"usageText"` Config C `json:"config"` }
func (a *ArgumentBase[T, C, VC]) Get() any
type ArgumentsBase[T any, C any, VC ValueCreator[T, C]] struct { Name string `json:"name"` Value T `json:"value"` Destination *[]T `json:"-"` UsageText string `json:"usageText"` Min int `json:"minTimes"` Max int `json:"maxTimes"` Config C `json:"config"` }
ArgumentsBase is a base type for slice arguments
func (a *ArgumentsBase[T, C, VC]) Get() any
BeforeFunc is an action that executes prior to any subcommands being run once the context is ready. If a non-nil error is returned, no subcommands are run.
type BoolConfig struct {
Count *int
}
BoolConfig defines the configuration for bool flags
type BoolFlag = FlagBase[bool, BoolConfig, boolValue]
type BoolWithInverseFlag struct {
Name string `json:"name"`
Category string `json:"category"`
DefaultText string `json:"defaultText"`
HideDefault bool `json:"hideDefault"`
Usage string `json:"usage"`
Sources ValueSourceChain `json:"-"`
Required bool `json:"required"`
Hidden bool `json:"hidden"`
Local bool `json:"local"`
Value bool `json:"defaultValue"`
Destination *bool `json:"-"`
Aliases []string `json:"aliases"`
TakesFile bool `json:"takesFileArg"`
Action func(context.Context, *Command, bool) error `json:"-"`
OnlyOnce bool `json:"onlyOnce"`
Validator func(bool) error `json:"-"`
ValidateDefaults bool `json:"validateDefaults"`
Config BoolConfig `json:"config"`
InversePrefix string `json:"invPrefix"`
}
package main
import (
"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 set flags: 2
Count returns the number of times this flag has been invoked
GetCategory returns the category of the flag
GetDefaultText returns the default text for this flag
GetEnvVars returns the env vars for this flag
GetUsage returns the usage string for the flag
GetValue returns the flags value as string representation and an empty string if the flag takes no value at all.
func (bif *BoolWithInverseFlag) IsBoolFlag() bool
IsBoolFlag returns whether the flag doesn't need to accept args
func (bif *BoolWithInverseFlag) IsDefaultVisible() bool
IsDefaultVisible returns true if the flag is not hidden, otherwise false
func (bif *BoolWithInverseFlag) IsRequired() bool
String implements the standard Stringer interface.
Example for BoolFlag{Name: "env"} --[no-]env (default: false)
Example for BoolFlag{Name: "env", Aliases: []string{"e"}} --[no-]env, -e (default: false)
func (bif *BoolWithInverseFlag) TakesValue() bool
TypeName is used for stringify/docs. For bool its a no-op
CategorizableFlag is an interface that allows us to potentially use a flag in a categorized representation.
type Command ¶
type Command struct {
Name string `json:"name"`
Aliases []string `json:"aliases"`
Usage string `json:"usage"`
UsageText string `json:"usageText"`
ArgsUsage string `json:"argsUsage"`
Version string `json:"version"`
Description string `json:"description"`
DefaultCommand string `json:"defaultCommand"`
Category string `json:"category"`
Commands []*Command `json:"commands"`
Flags []Flag `json:"flags"`
HideHelp bool `json:"hideHelp"`
HideHelpCommand bool `json:"hideHelpCommand"`
HideVersion bool `json:"hideVersion"`
EnableShellCompletion bool `json:"-"`
ShellCompletionCommandName string `json:"-"`
ShellComplete ShellCompleteFunc `json:"-"`
ConfigureShellCompletionCommand ConfigureShellCompletionCommand `json:"-"`
Before BeforeFunc `json:"-"`
After AfterFunc `json:"-"`
Action ActionFunc `json:"-"`
CommandNotFound CommandNotFoundFunc `json:"-"`
OnUsageError OnUsageErrorFunc `json:"-"`
InvalidFlagAccessHandler InvalidFlagAccessFunc `json:"-"`
Hidden bool `json:"hidden"`
Authors []any `json:"authors"`
Copyright string `json:"copyright"`
Reader io.Reader `json:"-"`
Writer io.Writer `json:"-"`
ErrWriter io.Writer `json:"-"`
ExitErrHandler ExitErrHandlerFunc `json:"-"`
Metadata map[string]any `json:"metadata"`
ExtraInfo func() map[string]string `json:"-"`
CustomRootCommandHelpTemplate string `json:"-"`
SliceFlagSeparator string `json:"sliceFlagSeparator"`
DisableSliceFlagSeparator bool `json:"disableSliceFlagSeparator"`
MapFlagKeyValueSeparator string `json:"mapFlagKeyValueSeparator"`
UseShortOptionHandling bool `json:"useShortOptionHandling"`
Suggest bool `json:"suggest"`
AllowExtFlags bool `json:"allowExtFlags"`
SkipFlagParsing bool `json:"skipFlagParsing"`
CustomHelpTemplate string `json:"-"`
PrefixMatchCommands bool `json:"prefixMatchCommands"`
SuggestCommandFunc SuggestCommandFunc `json:"-"`
MutuallyExclusiveFlags []MutuallyExclusiveFlags `json:"mutuallyExclusiveFlags"`
Arguments []Argument `json:"arguments"`
ReadArgsFromStdin bool `json:"readArgsFromStdin"`
StopOnNthArg *int `json:"stopOnNthArg"`
}
Command contains everything needed to run an application that accepts a string slice of arguments such as os.Args. A given Command may contain Flags and sub-commands in Commands.
func (*Command) FlagNames ¶
FlagNames returns a slice of flag names used by the this command and all of its parent commands.
func (*Command) Float32 ¶ added in v3.3.0
Float32 looks up the value of a local Float32Flag, returns 0 if not found
func (*Command) Float32Slice ¶ added in v3.3.0
Float32Slice looks up the value of a local Float32Slice, returns nil if not found
func (*Command) Float64 ¶ added in v3.3.0
Float64 looks up the value of a local Float64Flag, returns 0 if not found
func (*Command) Float64Slice ¶ added in v3.3.0
Float64Slice looks up the value of a local Float64SliceFlag, returns nil if not found
func (*Command) FloatSlice ¶
FloatSlice looks up the value of a local FloatSliceFlag, returns nil if not found
func (*Command) FullName ¶
FullName returns the full name of the command. Includes parent commands separated by space.
func (*Command) Generic ¶
Generic looks up the value of a local GenericFlag, returns nil if not found
func (*Command) Int8 ¶ added in v3.2.0
Int8 looks up the value of a local Int8Flag, returns 0 if not found
func (*Command) Int8Slice ¶ added in v3.2.0
Int8Slice looks up the value of a local Int8SliceFlag, returns nil if not found
func (*Command) Int16 ¶ added in v3.2.0
Int16 looks up the value of a local Int16Flag, returns 0 if not found
func (*Command) Int16Slice ¶ added in v3.2.0
Int16Slice looks up the value of a local Int16SliceFlag, returns nil if not found
func (*Command) Int32 ¶ added in v3.2.0
Int32 looks up the value of a local Int32Flag, returns 0 if not found
func (*Command) Int32Slice ¶ added in v3.2.0
Int32Slice looks up the value of a local Int32SliceFlag, returns nil if not found
func (*Command) Int64 ¶ added in v3.2.0
Int64 looks up the value of a local Int64Flag, returns 0 if not found
func (*Command) Int64Slice ¶ added in v3.2.0
Int64Slice looks up the value of a local Int64SliceFlag, returns nil if not found
func (*Command) IntSlice ¶
IntSlice looks up the value of a local IntSliceFlag, returns nil if not found
func (*Command) Lineage ¶
Lineage returns *this* command and all of its ancestor commands in order from child to parent
func (*Command) LocalFlagNames ¶
LocalFlagNames returns a slice of flag names used in this command.
func (*Command) Path ¶ added in v3.10.0
Path returns the path of command names from the root to cmd, inclusive. Each element is a Command.Name. Path traverses upward via parent pointers similar to Lineage. FullName() is equivalent to strings.Join(cmd.Path(), " ").
func (*Command) Run ¶
Run is the entry point to the command graph. The positional arguments are parsed according to the Flag and Command definitions and the matching Action functions are run.
package main
import (
"context"
"fmt"
"net/mail"
"os"
cli "github.com/urfave/cli/v3"
)
func main() {
// Declare a command
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.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 arguments
os.Args = []string{"greet", "--name", "Jeremy"}
if err := cmd.Run(context.Background(), os.Args); err != nil {
// do something with unhandled errors
fmt.Fprintf(os.Stderr, "Unhandled error: %[1]v\n", err)
os.Exit(86)
}
}
Output: Hello Jeremy
package main
import (
"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 arguments
os.Args = []string{"greet", "help"}
_ = cmd.Run(ctx, os.Args)
}
Output: NAME: greet - A new cli application USAGE: greet [global options] [command [command options]] [arguments...] VERSION: 0.1.0 DESCRIPTION: This is how we describe greet the app AUTHORS: "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 command GLOBAL OPTIONS: --name string a name to say (default: "bob") --help, -h show help --version, -v print the version
package main
import (
"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 arguments
os.Args = []string{"greet", "h", "describeit"}
_ = cmd.Run(context.Background(), os.Args)
}
Output: NAME: greet describeit - use it to see a description USAGE: greet describeit [options] [arguments...] DESCRIPTION: This is how we describe describeit the function OPTIONS: --help, -h show help GLOBAL OPTIONS: --name string a name to say (default: "pat")
package main
import (
"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 arguments
os.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>
package main
import (
"context"
"os"
cli "github.com/urfave/cli/v3"
)
func main() {
cmd := &cli.Command{Name: "greet"}
// Simulate the command line arguments
os.Args = []string{"greet"}
_ = cmd.Run(context.Background(), os.Args)
}
Output: NAME: greet - A new cli application USAGE: greet [global options] GLOBAL OPTIONS: --help, -h show help
package main
import (
"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 arguments
os.Args = []string{"greet", "--generate-shell-completion"}
_ = cmd.Run(context.Background(), os.Args)
}
Output: describeit:use it to see a description next:next example help:Shows a list of commands or help for one command
package main
import (
"context"
"os"
cli "github.com/urfave/cli/v3"
)
func main() {
cmd := &cli.Command{
Name: "greet",
EnableShellCompletion: true,
Flags: []cli.Flag{
&cli.Int64Flag{
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 arguments
os.Args = []string{"greet", "--s", "--generate-shell-completion"}
_ = cmd.Run(context.Background(), os.Args)
}
Output: --some-flag --similar-flag
package main
import (
"context"
"os"
cli "github.com/urfave/cli/v3"
)
func main() {
cmd := &cli.Command{
Name: "greet",
EnableShellCompletion: true,
Flags: []cli.Flag{
&cli.Int64Flag{
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 arguments
os.Args = []string{"greet", "--st", "--generate-shell-completion"}
_ = cmd.Run(context.Background(), os.Args)
}
Output: --string --string-flag-2
package main
import (
"context"
"os"
cli "github.com/urfave/cli/v3"
)
func main() {
cmd := &cli.Command{
Name: "greet",
EnableShellCompletion: true,
Flags: []cli.Flag{
&cli.Int64Flag{
Name: "other",
Aliases: []string{"o"},
},
&cli.StringFlag{
Name: "xyz",
Aliases: []string{"x"},
},
},
}
// Simulate a bash environment and command line arguments
os.Args = []string{"greet", "-", "--generate-shell-completion"}
_ = cmd.Run(context.Background(), os.Args)
}
Output: --other --xyz --help:show help
package main
import (
"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 fish environment and command line arguments
os.Args = []string{"greet", "--generate-shell-completion"}
_ = cmd.Run(context.Background(), os.Args)
}
Output: describeit:use it to see a description next:next example help:Shows a list of commands or help for one command
package main
import (
"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 arguments
os.Args = []string{"greet", "--generate-shell-completion"}
_ = cmd.Run(context.Background(), os.Args)
}
Output: describeit:use it to see a description next:next example help:Shows a list of commands or help for one command
package main
import (
"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.Int64SliceFlag{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 arguments
os.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>
package main
import (
"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 arguments
os.Args = []string{"say", "hi", "english", "--name", "Jeremy"}
_ = cmd.Run(ctx, os.Args)
}
Output: Hello, Jeremy
package main
import (
"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 arguments
os.Args = []string{"greet", "describeit"}
_ = cmd.Run(context.Background(), os.Args)
}
Output: NAME: greet describeit - use it to see a description USAGE: greet describeit [options] [arguments...] DESCRIPTION: This is how we describe describeit the function OPTIONS: --help, -h show help
func (*Command) StringMap ¶
StringMap looks up the value of a local StringMapFlag, returns nil if not found
func (*Command) StringSlice ¶
StringSlice looks up the value of a local StringSliceFlag, returns nil if not found
func (*Command) ToFishCompletion ¶
ToFishCompletion creates a fish completion string for the `*Command` The function errors if either parsing or writing of the string fails.
func (*Command) Uint8 ¶ added in v3.2.0
Uint8 looks up the value of a local Uint8Flag, returns 0 if not found
func (*Command) Uint8Slice ¶ added in v3.2.0
Uint8Slice looks up the value of a local Uint8SliceFlag, returns nil if not found
func (*Command) Uint16 ¶ added in v3.2.0
Uint16 looks up the value of a local Uint16Flag, returns 0 if not found
func (*Command) Uint16Slice ¶ added in v3.2.0
Uint16Slice looks up the value of a local Uint16SliceFlag, returns nil if not found
func (*Command) Uint32 ¶ added in v3.2.0
Uint32 looks up the value of a local Uint32Flag, returns 0 if not found
func (*Command) Uint32Slice ¶ added in v3.2.0
Uint32Slice looks up the value of a local Uint32SliceFlag, returns nil if not found
func (*Command) Uint64 ¶ added in v3.2.0
Uint64 looks up the value of a local Uint64Flag, returns 0 if not found
func (*Command) Uint64Slice ¶ added in v3.2.0
Uint64Slice looks up the value of a local Uint64SliceFlag, returns nil if not found
func (*Command) UintSlice ¶
UintSlice looks up the value of a local UintSliceFlag, returns nil if not found
func (*Command) VisibleCategories ¶
func (cmd *Command) VisibleCategories() []CommandCategory
VisibleCategories returns a slice of categories and commands that are Hidden=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 of LocalFlag with Persistent=true and Hidden=false.
type CommandCategories ¶
type CommandCategories interface {
AddCommand(category string, command *Command)
Categories() []CommandCategory
}
CommandCategories interface allows for category manipulation
type CommandCategory ¶
CommandCategory is a category containing commands.
type ConfigureShellCompletionCommand ¶ added in v3.3.0
type ConfigureShellCompletionCommand func(*Command)
ConfigureShellCompletionCommand is a function to configure a shell completion command
type Countable interface {
Count() int
}
Countable is an interface to enable detection of flag values which support repetitive flags
DocGenerationFlag is an interface that allows documentation generation for the flag
type DocGenerationMultiValueFlag interface {
DocGenerationFlag
IsMultiValueFlag() bool
}
DocGenerationMultiValueFlag extends DocGenerationFlag for slice/map based flags.
EnvValueSource is to specifically detect env sources when printing help text
ErrorFormatter is the interface that will suitably format the error output
ExitCoder is the interface checked by `Command` for a custom exit code.
Exit wraps a message and exit code into an error, which by default is handled with a call to os.Exit during default error handling.
This is the simplest way to trigger a non-zero exit code for a Command without having to call os.Exit manually. During testing, this behavior can be avoided by overriding the ExitErrHandler function on a Command or the package-global OsExiter function.
type ExitErrHandlerFunc ¶
ExitErrHandlerFunc is executed if provided in order to handle exitError values returned by Actions and Before/After functions.
Flag is a common interface related to parsing flags in cli. For more advanced flag parsing techniques, it is recommended that this interface be implemented.
var GenerateShellCompletionFlag Flag = &BoolFlag{ Name: "generate-shell-completion", Hidden: true, }
GenerateShellCompletionFlag enables shell completion
type FlagBase[T any, C any, VC ValueCreator[T, C]] struct { Name string `json:"name"` Category string `json:"category"` DefaultText string `json:"defaultText"` HideDefault bool `json:"hideDefault"` Usage string `json:"usage"` Sources ValueSourceChain `json:"-"` Required bool `json:"required"` Hidden bool `json:"hidden"` Local bool `json:"local"` Value T `json:"defaultValue"` Destination *T `json:"-"` Aliases []string `json:"aliases"` TakesFile bool `json:"takesFileArg"` Action func(context.Context, *Command, T) error `json:"-"` Config C `json:"config"` OnlyOnce bool `json:"onlyOnce"` Validator func(T) error `json:"-"` ValidateDefaults bool `json:"validateDefaults"` }
FlagBase [T,C,VC] is a generic flag base which can be used as a boilerplate to implement the most common interfaces used by urfave/cli.
T specifies the type C specifies the configuration required(if any for that flag type) VC specifies the value creator which creates the flag.Value emulation
Count returns the number of times this flag has been invoked
GetDefaultText returns the default text for this flag
GetValue returns the flags value as string representation and an empty string if the flag takes no value at all.
IsBoolFlag returns whether the flag doesn't need to accept args
IsDefaultVisible returns true if the flag is not hidden, otherwise false
IsLocal returns false if flag needs to be persistent across subcommands
IsMultiValueFlag returns true if the value type T can take multiple values from cmd line. This is true for slice and map type flags
IsRequired returns whether or not the flag is required
IsSet returns whether or not the flag has been set through env or file
IsVisible returns true if the flag is not hidden, otherwise false
PostParse populates the flag given the flag set and environment
RunAction executes flag action if set
SchemaItemsType returns the JSON Schema element type for slice flags.
SchemaType returns the JSON Schema type for the flag's value type.
Set applies given value from string
String returns a readable representation of this value (for usage defaults)
TakesValue returns true if the flag takes a value, otherwise false
type FlagCategories interface {
AddFlag(category string, fl Flag)
VisibleCategories() []VisibleFlagCategory
}
FlagCategories interface allows for category manipulation
FlagEnvHintFunc is used by the default FlagStringFunc to annotate flag help with the environment variable details.
var FlagEnvHinter FlagEnvHintFunc = withEnvHint
FlagEnvHinter annotates flag help message with the environment variable details. This is used by the default FlagStringer.
FlagFileHintFunc is used by the default FlagStringFunc to annotate flag help with the file path details.
var FlagFileHinter FlagFileHintFunc = withFileHint
FlagFileHinter annotates flag help message with the environment variable details. This is used by the default FlagStringer.
FlagNamePrefixFunc is used by the default FlagStringFunc to create prefix text for a flag's full name.
var FlagNamePrefixer FlagNamePrefixFunc = prefixedNames
FlagNamePrefixer converts a full flag name and its placeholder into the help message flag prefix. This is used by the default FlagStringer.
FlagStringFunc is used by the help generation to display a flag, which is expected to be a single line.
var FlagStringer FlagStringFunc = stringifyFlag
FlagStringer converts a flag definition to a string. This is used by help to display a flag.
FlagsByName is a slice of Flag.
func (f FlagsByName) Swap(i, j int)
Prints help for the Command with custom template function.
var HelpPrinterCustom HelpPrinterCustomFunc = DefaultPrintHelpCustom
HelpPrinterCustom is a function that writes the help output. It is used as the default implementation of HelpPrinter, and may be called directly if the ExtraInfo field is set on a Command.
In the default implementation, if the customFuncs argument contains a "wrapAt" key, which is a function which takes no arguments and returns an int, this int value will be used to produce a "wrap" function used by the default template to wrap long lines.
HelpPrinterFunc prints help for the Command.
var HelpPrinter HelpPrinterFunc = DefaultPrintHelp
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 be overridden. If the ExtraInfo field is defined on a Command, this function should not be modified, as HelpPrinterCustom will be used directly in order to capture the extra information.
type IntSliceFlag = FlagBase[[]int, IntegerConfig, IntSlice]
type IntegerConfig struct {
Base int
}
IntegerConfig is the configuration for all integer type flags
InvalidFlagAccessFunc is executed when an invalid flag is accessed from the context.
type LocalFlag interface {
IsLocal() bool
}
LocalFlag is an interface to enable detection of flags which are local to current command
type MapBase[T any, C any, VC ValueCreator[T, C]] struct { }
MapBase wraps map[string]T to satisfy flag.Value
func NewMapBase[T any, C any, VC ValueCreator[T, C]](defaults map[string]T) *MapBase[T, C, VC]
NewMapBase makes a *MapBase with default values
Set parses the value and appends it to the list of values
String returns a readable representation of this value (for usage defaults)
MapSource is a source which can be used to look up a value based on a key typically for use with a cli.Flag
MultiError is an error that wraps multiple errors.
MutuallyExclusiveFlags defines a mutually exclusive flag group Multiple option paths can be provided out of which only one can be defined on cmdline So for example [ --foo | [ --bar something --darth somethingelse ] ]
type NoConfig struct{}
NoConfig is for flags which dont need a custom configuration
OnUsageErrorFunc is executed if a usage error occurs. This is useful for displaying customized usage error messages. This function is able to replace the original error messages. If this function is not set, the "Incorrect usage" is displayed and the execution is interrupted.
type RequiredFlag interface {
IsRequired() bool
}
RequiredFlag is an interface that allows us to mark flags as required it allows flags required flags to be backwards compatible with the Flag interface
type SchemaItemsTyper interface {
SchemaItemsType() string
}
SchemaItemsTyper is an optional interface for multi-value flags that can report the JSON Schema type of their elements.
type SchemaTyper interface {
SchemaType() string
}
SchemaTyper is an optional interface for flags that can report their JSON Schema type for programmatic introspection.
type Serializer interface {
Serialize() string
}
Serializer is used to circumvent the limitations of flag.FlagSet.Set
ShellCompleteFunc is an action to execute when the shell completion flag is set
type SliceBase[T any, C any, VC ValueCreator[T, C]] struct { }
SliceBase wraps []T to satisfy flag.Value
func NewSliceBase[T any, C any, VC ValueCreator[T, C]](defaults ...T) *SliceBase[T, C, VC]
NewSliceBase makes a *SliceBase with default values
Set parses the value and appends it to the list of values
String returns a readable representation of this value (for usage defaults)
func (i *SliceBase[T, C, VC]) Value() []T
Value returns the slice of values set by this flag
type StringConfig struct {
TrimSpace bool
}
StringConfig defines the configuration for string flags
type StringFlag = FlagBase[string, StringConfig, stringValue]
type StringMap = MapBase[string, StringConfig, stringValue]
type StringSlice = SliceBase[string, StringConfig, stringValue]
TimestampConfig defines the config for timestamp flags
Value represents a value as used by cli. For now it implements the golang flag.Value interface
ValueCreator is responsible for creating a flag.Value emulation as well as custom formatting
T specifies the type C specifies the config for the type
ValueSource is a source which can be used to look up a value, typically for use with a cli.Flag
func NewMapValueSource(key string, ms MapSource) ValueSource
type ValueSourceChain struct {
Chain []ValueSource
}
ValueSourceChain contains an ordered series of ValueSource that allows for lookup where the first ValueSource to resolve is returned
EnvVars is a helper function to encapsulate a number of envVarValueSource together as a ValueSourceChain
Files is a helper function to encapsulate a number of fileValueSource together as a ValueSourceChain
func NewValueSourceChain(src ...ValueSource) ValueSourceChain
func (vsc *ValueSourceChain) Append(other ValueSourceChain)
type VisibleFlag interface {
IsVisible() bool
}
VisibleFlag is an interface that allows to check if a flag is visible