github.com/urfave/cli/v3
import "github.com/urfave/cli/v3"
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
var (
NewFloatSlice = NewSliceBase[float64, NoConfig, floatValue[float64]]
NewFloat32Slice = NewSliceBase[float32, NoConfig, floatValue[float32]]
NewFloat64Slice = NewSliceBase[float64, NoConfig, floatValue[float64]]
)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
var AnyArguments = []Argument{
&StringArgs{
Max: -1,
},
}ArgsUsageCommandHelp is a short description of the arguments of the help command
var ArgsUsageCommandHelp = "[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.
var CommandHelpTemplate = `NAME:
{{template "helpNameTemplate" .}}
USAGE:
{{template "usageTemplate" .}}{{if .Category}}
CATEGORY:
{{.Category}}{{end}}{{if .Description}}
DESCRIPTION:
{{template "descriptionTemplate" .}}{{end}}{{if .VisibleFlagCategories}}
OPTIONS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}}
OPTIONS:{{template "visibleFlagTemplate" .}}{{end}}{{if .VisiblePersistentFlags}}
GLOBAL OPTIONS:{{template "visiblePersistentFlagTemplate" .}}{{end}}
`DefaultAppComplete is a backward-compatible name for DefaultRootCommandComplete.
var DefaultAppComplete = DefaultRootCommandCompletevar DefaultInverseBoolPrefix = "no-"ErrWriter is used to write errors to the user. This can be anything implementing the io.Writer interface and defaults to os.Stderr.
var ErrWriter io.Writer = os.Stderrvar FishCompletionTemplate = `# {{ .Command.Name }} fish shell completion
function __fish_{{ .Command.Name }}_no_subcommand --description 'Test if there has been any subcommand yet'
for i in (commandline -opc)
if contains -- $i{{ range $v := .AllCommands }} {{ $v }}{{ end }}
return 1
end
end
return 0
end
{{ range $v := .Completions }}{{ $v }}
{{ end }}`var NewStringMap = NewMapBase[string, StringConfig, stringValue]var NewStringSlice = NewSliceBase[string, StringConfig, stringValue]OsExiter is the function used when the app exits. If not set defaults to os.Exit.
var OsExiter = os.ExitRootCommandHelpTemplate 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.
var RootCommandHelpTemplate = `NAME:
{{template "helpNameTemplate" .}}
USAGE:
{{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.FullName}} {{if .VisibleFlags}}[global options]{{end}}{{if .VisibleCommands}} [command [command options]]{{end}}{{if .ArgsUsage}} {{.ArgsUsage}}{{else}}{{if .Arguments}} [arguments...]{{end}}{{end}}{{end}}{{if .Version}}{{if not .HideVersion}}
VERSION:
{{.Version}}{{end}}{{end}}{{if .Description}}
DESCRIPTION:
{{template "descriptionTemplate" .}}{{end}}
{{- if len .Authors}}
AUTHOR{{template "authorsTemplate" .}}{{end}}{{if .VisibleCommands}}
COMMANDS:{{template "visibleCommandCategoryTemplate" .}}{{end}}{{if .VisibleFlagCategories}}
GLOBAL OPTIONS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}}
GLOBAL OPTIONS:{{template "visibleFlagTemplate" .}}{{end}}{{if .Copyright}}
COPYRIGHT:
{{template "copyrightTemplate" .}}{{end}}
`ShowAppHelp is a backward-compatible name for ShowRootCommandHelp.
var ShowAppHelp = ShowRootCommandHelpShowAppHelpAndExit is a backward-compatible name for ShowRootCommandHelp.
var ShowAppHelpAndExit = ShowRootCommandHelpAndExitShowCommandHelp prints help for the given command
var ShowCommandHelp = DefaultShowCommandHelpShowRootCommandHelp is an action that displays help for the root command.
var ShowRootCommandHelp = DefaultShowRootCommandHelpShowSubcommandHelp prints help for the given subcommand
var ShowSubcommandHelp = DefaultShowSubcommandHelpSubcommandHelpTemplate 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 SubcommandHelpTemplate = `NAME:
{{template "helpNameTemplate" .}}
USAGE:
{{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.FullName}}{{if .VisibleCommands}} [command [command options]]{{end}}{{if .ArgsUsage}} {{.ArgsUsage}}{{else}}{{if .Arguments}} [arguments...]{{end}}{{end}}{{end}}{{if .Category}}
CATEGORY:
{{.Category}}{{end}}{{if .Description}}
DESCRIPTION:
{{template "descriptionTemplate" .}}{{end}}{{if .VisibleCommands}}
COMMANDS:{{template "visibleCommandTemplate" .}}{{end}}{{if .VisibleFlagCategories}}
OPTIONS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}}
OPTIONS:{{template "visibleFlagTemplate" .}}{{end}}{{if .VisiblePersistentFlags}}
GLOBAL OPTIONS:{{template "visiblePersistentFlagTemplate" .}}{{end}}
`UsageCommandHelp is the text to override the USAGE section of the help command
var UsageCommandHelp = "Shows a list of commands or help for one command"VersionPrinter prints the version for the root Command.
var VersionPrinter = DefaultPrintVersionGenerateShellCompletionFlag enables shell completion
var GenerateShellCompletionFlag Flag = &BoolFlag{
Name: "generate-shell-completion",
Hidden: true,
}HelpFlag prints the help for all commands and subcommands. Set to nil to disable the flag. The subcommand will still be added unless HideHelp or HideHelpCommand is set to true.
var HelpFlag Flag = &BoolFlag{
Name: "help",
Aliases: []string{"h"},
Usage: "show help",
HideDefault: true,
Local: true,
}VersionFlag prints the version for the application
var VersionFlag Flag = &BoolFlag{
Name: "version",
Aliases: []string{"v"},
Usage: "print the version",
HideDefault: true,
Local: true,
}FlagEnvHinter annotates flag help message with the environment variable details. This is used by the default FlagStringer.
var FlagEnvHinter FlagEnvHintFunc = withEnvHintFlagFileHinter annotates flag help message with the environment variable details. This is used by the default FlagStringer.
var FlagFileHinter FlagFileHintFunc = withFileHintFlagNamePrefixer converts a full flag name and its placeholder into the help message flag prefix. This is used by the default FlagStringer.
var FlagNamePrefixer FlagNamePrefixFunc = prefixedNamesFlagStringer converts a flag definition to a string. This is used by help to display a flag.
var FlagStringer FlagStringFunc = stringifyFlagHelpPrinterCustom 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.
var HelpPrinterCustom HelpPrinterCustomFunc = DefaultPrintHelpCustomHelpPrinter 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.
var HelpPrinter HelpPrinterFunc = DefaultPrintHelpFunctions
func DefaultCompleteWithFlags(ctx context.Context, cmd *Command)
func DefaultPrintHelp(out io.Writer, templ string, data any)
DefaultPrintHelp is the default implementation of HelpPrinter.
func DefaultPrintHelpCustom(out io.Writer, templ string, data any, customFuncs map[string]any)
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(ctx context.Context, cmd *Command)
DefaultRootCommandComplete prints the list of subcommands as the default completion method.
func DefaultShowCommandHelp(ctx context.Context, cmd *Command, commandName string) error
DefaultShowCommandHelp is the default implementation of ShowCommandHelp.
func DefaultShowRootCommandHelp(cmd *Command) error
DefaultShowRootCommandHelp is the default implementation of ShowRootCommandHelp.
func DefaultShowSubcommandHelp(cmd *Command) error
DefaultShowSubcommandHelp is the default implementation of ShowSubcommandHelp.
func EnvVar(key string) ValueSource
func EnvVars(keys ...string) ValueSourceChain
EnvVars is a helper function to encapsulate a number of envVarValueSource together as a ValueSourceChain
func Exit(message any, exitCode int) ExitCoder
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.
func File(path string) ValueSource
func Files(paths ...string) ValueSourceChain
Files is a helper function to encapsulate a number of fileValueSource together as a ValueSourceChain
func FlagNames(name string, aliases []string) []string
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 NewMapBase[T any, C any, VC ValueCreator[T, C]](defaults map[string]T) *MapBase[T, C, VC]
NewMapBase makes a *MapBase with default values
func NewMapSource(name string, m map[any]any) MapSource
func NewMapValueSource(key string, ms MapSource) ValueSource
func NewSliceBase[T any, C any, VC ValueCreator[T, C]](defaults ...T) *SliceBase[T, C, VC]
NewSliceBase makes a *SliceBase with default values
func NewValueSourceChain(src ...ValueSource) ValueSourceChain
func ShowCommandHelpAndExit(ctx context.Context, cmd *Command, command string, code int)
ShowCommandHelpAndExit exits with code after showing help via ShowCommandHelp.
func ShowRootCommandHelpAndExit(cmd *Command, exitCode int)
ShowRootCommandHelpAndExit prints the list of subcommands and exits with exit code.
func ShowSubcommandHelpAndExit(cmd *Command, exitCode int)
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.
Types
type ActionFunc
ActionFunc is the action to execute when no subcommands are specified
type ActionFunc func(context.Context, *Command) errortype ActionableFlag
ActionableFlag is an interface that wraps Flag interface and RunAction operation.
type ActionableFlag interface {
RunAction(context.Context, *Command) error
}Methods
RunAction func(context.Context, *Command) error
type AfterFunc
AfterFunc is an action that executes after any subcommands are run and have finished. The AfterFunc is run even if Action() panics.
type AfterFunc func(context.Context, *Command) errortype Args
type Args interface {
// Get returns the nth argument, or else a blank string
Get(n int) string
// First returns the first argument, or else a blank string
First() string
// Tail returns the rest of the arguments (not the first one)
// or else an empty string slice
Tail() []string
// Len returns the length of the wrapped slice
Len() int
// Present checks if there are any arguments present
Present() bool
// Slice returns a copy of the internal slice
Slice() []string
}Methods
Get func(n int) stringGet returns the nth argument, or else a blank string
First func() stringFirst returns the first argument, or else a blank string
Tail func() []stringTail returns the rest of the arguments (not the first one) or else an empty string slice
Len func() intLen returns the length of the wrapped slice
Present func() boolPresent checks if there are any arguments present
Slice func() []stringSlice returns a copy of the internal slice
type Argument
Argument captures a positional argument that can be parsed
type Argument interface {
// which this argument can be accessed using the given name
HasName(string) bool
// Parse the given args and return unparsed args and/or error
Parse([]string) ([]string, error)
// The usage template for this argument to use in help
Usage() string
// The Value of this Arg
Get() any
}Methods
HasName func(string) boolwhich this argument can be accessed using the given name
Parse func([]string) ([]string, error)Parse the given args and return unparsed args and/or error
Usage func() stringThe usage template for this argument to use in help
Get func() anyThe Value of this Arg
type ArgumentBase
type ArgumentBase[T any, C any, VC ValueCreator[T, C]] struct {
Name string `json:"name"` // the name of this argument
Value T `json:"value"` // the default value of this argument
Destination *T `json:"-"` // the destination point for this argument
UsageText string `json:"usageText"` // the usage text to show
Config C `json:"config"` // config for this argument similar to Flag Config
// contains filtered or unexported fields
}Fields
Name string`json:"name"`the name of this argument
Value T`json:"value"`the default value of this argument
Destination *T`json:"-"`the destination point for this argument
UsageText string`json:"usageText"`the usage text to show
Config C`json:"config"`config for this argument similar to Flag Config
func Get() any
func HasName(s string) bool
func Parse(s []string) ([]string, error)
func Usage() string
type ArgumentsBase
ArgumentsBase is a base type for slice arguments
type ArgumentsBase[T any, C any, VC ValueCreator[T, C]] struct {
Name string `json:"name"` // the name of this argument
Value T `json:"value"` // the default value of this argument
Destination *[]T `json:"-"` // the destination point for this argument
UsageText string `json:"usageText"` // the usage text to show
Min int `json:"minTimes"` // the min num of occurrences of this argument
Max int `json:"maxTimes"` // the max num of occurrences of this argument, set to -1 for unlimited
Config C `json:"config"` // config for this argument similar to Flag Config
// contains filtered or unexported fields
}Fields
Name string`json:"name"`the name of this argument
Value T`json:"value"`the default value of this argument
Destination *[]T`json:"-"`the destination point for this argument
UsageText string`json:"usageText"`the usage text to show
Min int`json:"minTimes"`the min num of occurrences of this argument
Max int`json:"maxTimes"`the max num of occurrences of this argument, set to -1 for unlimited
Config C`json:"config"`config for this argument similar to Flag Config
func Get() any
func HasName(s string) bool
func Parse(s []string) ([]string, error)
func Usage() string
type BeforeFunc
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 BeforeFunc func(context.Context, *Command) (context.Context, error)type BoolConfig
BoolConfig defines the configuration for bool flags
type BoolConfig struct {
Count *int
}Fields
Count *int
type BoolFlag
type BoolFlag = FlagBase[bool, BoolConfig, boolValue]type BoolWithInverseFlag
type BoolWithInverseFlag struct {
Name string `json:"name"` // name of the flag
Category string `json:"category"` // category of the flag, if any
DefaultText string `json:"defaultText"` // default text of the flag for usage purposes
HideDefault bool `json:"hideDefault"` // whether to hide the default value in output
Usage string `json:"usage"` // usage string for help output
Sources ValueSourceChain `json:"-"` // sources to load flag value from
Required bool `json:"required"` // whether the flag is required or not
Hidden bool `json:"hidden"` // whether to hide the flag in help output
Local bool `json:"local"` // whether the flag needs to be applied to subcommands as well
Value bool `json:"defaultValue"` // default value for this flag if not set by from any source
Destination *bool `json:"-"` // destination pointer for value when set
Aliases []string `json:"aliases"` // Aliases that are allowed for this flag
TakesFile bool `json:"takesFileArg"` // whether this flag takes a file argument, mainly for shell completion purposes
Action func(context.Context, *Command, bool) error `json:"-"` // Action callback to be called when flag is set
OnlyOnce bool `json:"onlyOnce"` // whether this flag can be duplicated on the command line
Validator func(bool) error `json:"-"` // custom function to validate this flag value
ValidateDefaults bool `json:"validateDefaults"` // whether to validate defaults or not
Config BoolConfig `json:"config"` // Additional/Custom configuration associated with this flag type
InversePrefix string `json:"invPrefix"` // The prefix used to indicate a negative value. Default: `env` becomes `no-env`
// contains filtered or unexported fields
}Fields
Name string`json:"name"`name of the flag
Category string`json:"category"`category of the flag, if any
DefaultText string`json:"defaultText"`default text of the flag for usage purposes
HideDefault bool`json:"hideDefault"`whether to hide the default value in output
Usage string`json:"usage"`usage string for help output
Sources ValueSourceChain`json:"-"`sources to load flag value from
Required bool`json:"required"`whether the flag is required or not
Hidden bool`json:"hidden"`whether to hide the flag in help output
Local bool`json:"local"`whether the flag needs to be applied to subcommands as well
Value bool`json:"defaultValue"`default value for this flag if not set by from any source
Destination *bool`json:"-"`destination pointer for value when set
Aliases []string`json:"aliases"`Aliases that are allowed for this flag
TakesFile bool`json:"takesFileArg"`whether this flag takes a file argument, mainly for shell completion purposes
Action func(context.Context, *Command, bool) error`json:"-"`Action callback to be called when flag is set
OnlyOnce bool`json:"onlyOnce"`whether this flag can be duplicated on the command line
Validator func(bool) error`json:"-"`custom function to validate this flag value
ValidateDefaults bool`json:"validateDefaults"`whether to validate defaults or not
Config BoolConfig`json:"config"`Additional/Custom configuration associated with this flag type
InversePrefix string`json:"invPrefix"`The prefix used to indicate a negative value. Default:
envbecomesno-env
func Count() int
Count returns the number of times this flag has been invoked
func Get() any
func GetCategory() string
GetCategory returns the category of the flag
func GetDefaultText() string
GetDefaultText returns the default text for this flag
func GetEnvVars() []string
GetEnvVars returns the env vars for this flag
func GetUsage() string
GetUsage returns the usage string for the flag
func GetValue() string
GetValue returns the flags value as string representation and an empty string if the flag takes no value at all.
func IsBoolFlag() bool
IsBoolFlag returns whether the flag doesn't need to accept args
func IsDefaultVisible() bool
IsDefaultVisible returns true if the flag is not hidden, otherwise false
func IsLocal() bool
func IsRequired() bool
func IsSet() bool
func IsVisible() bool
func Names() []string
func PostParse() error
func PreParse() error
func RunAction(ctx context.Context, cmd *Command) error
func SchemaItemsType() string
func SchemaType() string
func Set(name, val string) error
func SetCategory(c string)
func String() string
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 TakesValue() bool
func TypeName() string
TypeName is used for stringify/docs. For bool its a no-op
Example
{
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: 2type CategorizableFlag
CategorizableFlag is an interface that allows us to potentially use a flag in a categorized representation.
type CategorizableFlag interface {
// Returns the category of the flag
GetCategory() string
// Sets the category of the flag
SetCategory(string)
}Methods
GetCategory func() stringReturns the category of the flag
SetCategory func(string)Sets the category of the flag
type Command
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.
type Command struct {
// The name of the command
Name string `json:"name"`
// A list of aliases for the command
Aliases []string `json:"aliases"`
// A short description of the usage of this command
Usage string `json:"usage"`
// Text to override the USAGE section of help
UsageText string `json:"usageText"`
// A short description of the arguments of this command
ArgsUsage string `json:"argsUsage"`
// Version of the command
Version string `json:"version"`
// Longer explanation of how the command works
Description string `json:"description"`
// DefaultCommand is the (optional) name of a command
// to run if no command names are passed as CLI arguments.
DefaultCommand string `json:"defaultCommand"`
// The category the command is part of
Category string `json:"category"`
// List of child commands
Commands []*Command `json:"commands"`
// List of flags to parse
Flags []Flag `json:"flags"`
// Boolean to hide built-in help command and help flag
HideHelp bool `json:"hideHelp"`
// Ignored if HideHelp is true.
HideHelpCommand bool `json:"hideHelpCommand"`
// Boolean to hide built-in version flag and the VERSION section of help
HideVersion bool `json:"hideVersion"`
// Boolean to enable shell completion commands
EnableShellCompletion bool `json:"-"`
// Shell Completion generation command name
ShellCompletionCommandName string `json:"-"`
// The function to call when checking for shell command completions
ShellComplete ShellCompleteFunc `json:"-"`
// The function to configure a shell completion command
ConfigureShellCompletionCommand ConfigureShellCompletionCommand `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 run
Before BeforeFunc `json:"-"`
// An action to execute after any subcommands are run, but after the subcommand has finished
// It is run even if Action() panics
After AfterFunc `json:"-"`
// The function to call when this command is invoked
Action ActionFunc `json:"-"`
// Execute this function if the proper command cannot be found
CommandNotFound CommandNotFoundFunc `json:"-"`
// Execute this function if a usage error occurs.
OnUsageError OnUsageErrorFunc `json:"-"`
// Execute this function when an invalid flag is accessed from the context
InvalidFlagAccessHandler InvalidFlagAccessFunc `json:"-"`
// Boolean to hide this command from help or completion
Hidden bool `json:"hidden"`
// List of all authors who contributed (string or fmt.Stringer)
// TODO: ~string | fmt.Stringer when interface unions are available
Authors []any `json:"authors"`
// Copyright of the binary if any
Copyright string `json:"copyright"`
// Reader reader to write input to (useful for tests)
Reader io.Reader `json:"-"`
// Writer writer to write output to
Writer io.Writer `json:"-"`
// ErrWriter writes error output
ErrWriter io.Writer `json:"-"`
// ExitErrHandler processes any error encountered while running a Command before it is
// returned to the caller. If no function is provided, HandleExitCoder is used as the
// default behavior.
ExitErrHandler ExitErrHandlerFunc `json:"-"`
// Other custom info
Metadata map[string]any `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.
CustomRootCommandHelpTemplate string `json:"-"`
// SliceFlagSeparator is used to customize the separator for SliceFlag, the default is ","
SliceFlagSeparator string `json:"sliceFlagSeparator"`
// DisableSliceFlagSeparator is used to disable SliceFlagSeparator, the default is false
DisableSliceFlagSeparator bool `json:"disableSliceFlagSeparator"`
// MapFlagKeyValueSeparator is used to customize the separator for MapFlag, the default is "="
MapFlagKeyValueSeparator string `json:"mapFlagKeyValueSeparator"`
// Boolean to enable short-option handling so user can combine several
// single-character bool arguments into one
// i.e. foobar -o -v -> foobar -ov
UseShortOptionHandling bool `json:"useShortOptionHandling"`
// Enable suggestions for commands and flags
Suggest bool `json:"suggest"`
// Allows global flags set by libraries which use flag.XXXVar(...) directly
// to be parsed through this library
AllowExtFlags bool `json:"allowExtFlags"`
// Treat all flags as normal arguments if true
SkipFlagParsing bool `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.
CustomHelpTemplate string `json:"-"`
// Use longest prefix match for commands
PrefixMatchCommands bool `json:"prefixMatchCommands"`
// Custom suggest command for matching
SuggestCommandFunc SuggestCommandFunc `json:"-"`
// Flag exclusion group
MutuallyExclusiveFlags []MutuallyExclusiveFlags `json:"mutuallyExclusiveFlags"`
// Arguments to parse for this command
Arguments []Argument `json:"arguments"`
// Whether to read arguments from stdin
// applicable to root command only
ReadArgsFromStdin bool `json:"readArgsFromStdin"`
// StopOnNthArg provides v2-like behavior for specific commands by stopping
// flag parsing after N positional arguments are encountered. When set to N,
// all remaining arguments after the Nth positional argument will be treated
// as arguments, not flags.
//
// A value of 0 means all arguments are treated as positional (no flag parsing).
// A nil value means normal v3 flag parsing behavior (flags can appear anywhere).
StopOnNthArg *int `json:"stopOnNthArg"`
// contains filtered or unexported fields
}Fields
Name string`json:"name"`The name of the command
Aliases []string`json:"aliases"`A list of aliases for the command
Usage string`json:"usage"`A short description of the usage of this command
UsageText string`json:"usageText"`Text to override the USAGE section of help
ArgsUsage string`json:"argsUsage"`A short description of the arguments of this command
Version string`json:"version"`Version of the command
Description string`json:"description"`Longer explanation of how the command works
DefaultCommand string`json:"defaultCommand"`DefaultCommand is the (optional) name of a command to run if no command names are passed as CLI arguments.
Category string`json:"category"`The category the command is part of
Commands []*Command`json:"commands"`List of child commands
Flags []Flag`json:"flags"`List of flags to parse
HideHelp bool`json:"hideHelp"`Boolean to hide built-in help command and help flag
HideHelpCommand bool`json:"hideHelpCommand"`Ignored if HideHelp is true.
HideVersion bool`json:"hideVersion"`Boolean to hide built-in version flag and the VERSION section of help
EnableShellCompletion bool`json:"-"`Boolean to enable shell completion commands
ShellCompletionCommandName string`json:"-"`Shell Completion generation command name
ShellComplete ShellCompleteFunc`json:"-"`The function to call when checking for shell command completions
ConfigureShellCompletionCommand ConfigureShellCompletionCommand`json:"-"`The function to configure a shell completion command
Before BeforeFunc`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 run
After AfterFunc`json:"-"`An action to execute after any subcommands are run, but after the subcommand has finished It is run even if Action() panics
Action ActionFunc`json:"-"`The function to call when this command is invoked
CommandNotFound CommandNotFoundFunc`json:"-"`Execute this function if the proper command cannot be found
OnUsageError OnUsageErrorFunc`json:"-"`Execute this function if a usage error occurs.
InvalidFlagAccessHandler InvalidFlagAccessFunc`json:"-"`Execute this function when an invalid flag is accessed from the context
Hidden bool`json:"hidden"`Boolean to hide this command from help or completion
Authors []any`json:"authors"`List of all authors who contributed (string or fmt.Stringer) TODO: ~string | fmt.Stringer when interface unions are available
Copyright string`json:"copyright"`Copyright of the binary if any
Reader io.Reader`json:"-"`Reader reader to write input to (useful for tests)
Writer io.Writer`json:"-"`Writer writer to write output to
ErrWriter io.Writer`json:"-"`ErrWriter writes error output
ExitErrHandler ExitErrHandlerFunc`json:"-"`ExitErrHandler processes any error encountered while running a Command before it is returned to the caller. If no function is provided, HandleExitCoder is used as the default behavior.
Metadata map[string]any`json:"metadata"`Other custom info
ExtraInfo func() map[string]string`json:"-"`Carries a function which returns app specific info.
CustomRootCommandHelpTemplate 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.
SliceFlagSeparator string`json:"sliceFlagSeparator"`SliceFlagSeparator is used to customize the separator for SliceFlag, the default is ","
DisableSliceFlagSeparator bool`json:"disableSliceFlagSeparator"`DisableSliceFlagSeparator is used to disable SliceFlagSeparator, the default is false
MapFlagKeyValueSeparator string`json:"mapFlagKeyValueSeparator"`MapFlagKeyValueSeparator is used to customize the separator for MapFlag, the default is "="
UseShortOptionHandling bool`json:"useShortOptionHandling"`Boolean to enable short-option handling so user can combine several single-character bool arguments into one i.e. foobar -o -v -> foobar -ov
Suggest bool`json:"suggest"`Enable suggestions for commands and flags
AllowExtFlags bool`json:"allowExtFlags"`Allows global flags set by libraries which use flag.XXXVar(...) directly to be parsed through this library
SkipFlagParsing bool`json:"skipFlagParsing"`Treat all flags as normal arguments if true
CustomHelpTemplate string`json:"-"`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.
PrefixMatchCommands bool`json:"prefixMatchCommands"`Use longest prefix match for commands
SuggestCommandFunc SuggestCommandFunc`json:"-"`Custom suggest command for matching
MutuallyExclusiveFlags []MutuallyExclusiveFlags`json:"mutuallyExclusiveFlags"`Flag exclusion group
Arguments []Argument`json:"arguments"`Arguments to parse for this command
ReadArgsFromStdin bool`json:"readArgsFromStdin"`Whether to read arguments from stdin applicable to root command only
StopOnNthArg *int`json:"stopOnNthArg"`StopOnNthArg provides v2-like behavior for specific commands by stopping flag parsing after N positional arguments are encountered. When set to N, all remaining arguments after the Nth positional argument will be treated as arguments, not flags.
A value of 0 means all arguments are treated as positional (no flag parsing). A nil value means normal v3 flag parsing behavior (flags can appear anywhere).
func Args() Args
Args returns the command line arguments associated with the command.
func Bool(name string) bool
func Command) Command(name string) *Command
func Count(name string) int
Count returns the num of occurrences of this flag
func Duration(name string) time.Duration
func FlagNames() []string
FlagNames returns a slice of flag names used by the this command and all of its parent commands.
func Float(name string) float64
Float looks up the value of a local FloatFlag, returns 0 if not found
func Float32(name string) float32
Float32 looks up the value of a local Float32Flag, returns 0 if not found
func Float32Arg(name string) float32
func Float32Args(name string) []float32
func Float32Slice(name string) []float32
Float32Slice looks up the value of a local Float32Slice, returns nil if not found
func Float64(name string) float64
Float64 looks up the value of a local Float64Flag, returns 0 if not found
func Float64Arg(name string) float64
func Float64Args(name string) []float64
func Float64Slice(name string) []float64
Float64Slice looks up the value of a local Float64SliceFlag, returns nil if not found
func FloatArg(name string) float64
func FloatArgs(name string) []float64
func FloatSlice(name string) []float64
FloatSlice looks up the value of a local FloatSliceFlag, returns nil if not found
func FullName() string
FullName returns the full name of the command. Includes parent commands separated by space.
func Generic(name string) Value
Generic looks up the value of a local GenericFlag, returns nil if not found
func HasName(name string) bool
HasName returns true if Command.Name matches given name
func Int(name string) int
Int looks up the value of a local Int64Flag, returns 0 if not found
func Int16(name string) int16
Int16 looks up the value of a local Int16Flag, returns 0 if not found
func Int16Arg(name string) int16
func Int16Args(name string) []int16
func Int16Slice(name string) []int16
Int16Slice looks up the value of a local Int16SliceFlag, returns nil if not found
func Int32(name string) int32
Int32 looks up the value of a local Int32Flag, returns 0 if not found
func Int32Arg(name string) int32
func Int32Args(name string) []int32
func Int32Slice(name string) []int32
Int32Slice looks up the value of a local Int32SliceFlag, returns nil if not found
func Int64(name string) int64
Int64 looks up the value of a local Int64Flag, returns 0 if not found
func Int64Arg(name string) int64
func Int64Args(name string) []int64
func Int64Slice(name string) []int64
Int64Slice looks up the value of a local Int64SliceFlag, returns nil if not found
func Int8(name string) int8
Int8 looks up the value of a local Int8Flag, returns 0 if not found
func Int8Arg(name string) int8
func Int8Args(name string) []int8
func Int8Slice(name string) []int8
Int8Slice looks up the value of a local Int8SliceFlag, returns nil if not found
func IntArg(name string) int
func IntArgs(name string) []int
func IntSlice(name string) []int
IntSlice looks up the value of a local IntSliceFlag, returns nil if not found
func IsSet(name string) bool
IsSet determines if the flag was actually set
func Lineage() []*Command
Lineage returns this command and all of its ancestor commands in order from child to parent
func LocalFlagNames() []string
LocalFlagNames returns a slice of flag names used in this command.
func NArg() int
NArg returns the number of the command line arguments.
func Names() []string
Names returns the names including short names and aliases.
func NumFlags() int
NumFlags returns the number of flags set
func Path() []string
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 Root() *Command
Root returns the Command at the root of the graph
func Run(ctx context.Context, osArgs []string) (deferErr error)
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.
Example
{
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",
}
os.Args = []string{"greet", "--name", "Jeremy"}
if err := cmd.Run(context.Background(), os.Args); err != nil {
fmt.Fprintf(os.Stderr, "Unhandled error: %[1]v\n", err)
os.Exit(86)
}
}Output:
Hello Jeremyfunc Set(name, value string) error
Set sets a context flag to a value.
func String(name string) string
func StringArg(name string) string
func StringArgs(name string) []string
func StringMap(name string) map[string]string
StringMap looks up the value of a local StringMapFlag, returns nil if not found
func StringSlice(name string) []string
StringSlice looks up the value of a local StringSliceFlag, returns nil if not found
func Timestamp(name string) time.Time
Timestamp gets the timestamp from a flag name
func TimestampArg(name string) time.Time
func TimestampArgs(name string) []time.Time
func ToFishCompletion() (string, error)
ToFishCompletion creates a fish completion string for the *Command
The function errors if either parsing or writing of the string fails.
func Uint(name string) uint
Uint looks up the value of a local Uint64Flag, returns 0 if not found
func Uint16(name string) uint16
Uint16 looks up the value of a local Uint16Flag, returns 0 if not found
func Uint16Arg(name string) uint16
func Uint16Args(name string) []uint16
func Uint16Slice(name string) []uint16
Uint16Slice looks up the value of a local Uint16SliceFlag, returns nil if not found
func Uint32(name string) uint32
Uint32 looks up the value of a local Uint32Flag, returns 0 if not found
func Uint32Arg(name string) uint32
func Uint32Args(name string) []uint32
func Uint32Slice(name string) []uint32
Uint32Slice looks up the value of a local Uint32SliceFlag, returns nil if not found
func Uint64(name string) uint64
Uint64 looks up the value of a local Uint64Flag, returns 0 if not found
func Uint64Arg(name string) uint64
func Uint64Args(name string) []uint64
func Uint64Slice(name string) []uint64
Uint64Slice looks up the value of a local Uint64SliceFlag, returns nil if not found
func Uint8(name string) uint8
Uint8 looks up the value of a local Uint8Flag, returns 0 if not found
func Uint8Arg(name string) uint8
func Uint8Args(name string) []uint8
func Uint8Slice(name string) []uint8
Uint8Slice looks up the value of a local Uint8SliceFlag, returns nil if not found
func UintArg(name string) uint
func UintArgs(name string) []uint
func UintSlice(name string) []uint
UintSlice looks up the value of a local UintSliceFlag, returns nil if not found
func Value(name string) any
Value returns the value of the flag corresponding to name
func VisibleCategories() []CommandCategory
VisibleCategories returns a slice of categories and commands that are Hidden=false
func VisibleCommands() []*Command
VisibleCommands returns a slice of the Commands with Hidden=false
func VisibleFlagCategories() []VisibleFlagCategory
VisibleFlagCategories returns a slice containing all the visible flag categories with the flags they contain
func VisibleFlags() []Flag
VisibleFlags returns a slice of the Flags with Hidden=false
func VisiblePersistentFlags() []Flag
VisiblePersistentFlags returns a slice of [LocalFlag] with Persistent=true and Hidden=false.
func Walk(fn func(*Command) error) error
Walk visits cmd and every descendant. If fn returns a non-nil error, the walk terminates and the error is returned to the caller.
type CommandCategories
CommandCategories interface allows for category manipulation
type CommandCategories interface {
// AddCommand adds a command to a category, creating a new category if necessary.
AddCommand(category string, command *Command)
// Categories returns a slice of categories sorted by name
Categories() []CommandCategory
}Methods
AddCommand func(category string, command *Command)AddCommand adds a command to a category, creating a new category if necessary.
Categories func() []CommandCategoryCategories returns a slice of categories sorted by name
type CommandCategory
CommandCategory is a category containing commands.
type CommandCategory interface {
// Name returns the category name string
Name() string
// VisibleCommands returns a slice of the Commands with Hidden=false
VisibleCommands() []*Command
}Methods
Name func() stringName returns the category name string
VisibleCommands func() []*CommandVisibleCommands returns a slice of the Commands with Hidden=false
type CommandNotFoundFunc
CommandNotFoundFunc is executed if the proper command cannot be found
type CommandNotFoundFunc func(context.Context, *Command, string)type ConfigureShellCompletionCommand
ConfigureShellCompletionCommand is a function to configure a shell completion command
type ConfigureShellCompletionCommand func(*Command)type Countable
Countable is an interface to enable detection of flag values which support repetitive flags
type Countable interface {
Count() int
}Methods
Count func() int
type DocGenerationFlag
DocGenerationFlag is an interface that allows documentation generation for the flag
type DocGenerationFlag interface {
// TakesValue returns true if the flag takes a value, otherwise false
TakesValue() bool
// GetUsage returns the usage string for the flag
GetUsage() 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 flag
GetDefaultText() string
// GetEnvVars returns the env vars for this flag
GetEnvVars() []string
// IsDefaultVisible returns whether the default value should be shown in
// help text
IsDefaultVisible() bool
// TypeName to detect if a flag is a string, bool, etc.
TypeName() string
}Methods
TakesValue func() boolTakesValue returns true if the flag takes a value, otherwise false
GetUsage func() stringGetUsage returns the usage string for the flag
GetValue func() stringGetValue returns the flags value as string representation and an empty string if the flag takes no value at all.
GetDefaultText func() stringGetDefaultText returns the default text for this flag
GetEnvVars func() []stringGetEnvVars returns the env vars for this flag
IsDefaultVisible func() boolIsDefaultVisible returns whether the default value should be shown in help text
TypeName func() stringTypeName to detect if a flag is a string, bool, etc.
type DocGenerationMultiValueFlag
DocGenerationMultiValueFlag extends DocGenerationFlag for slice/map based flags.
type DocGenerationMultiValueFlag interface {
DocGenerationFlag
// IsMultiValueFlag returns true for flags that can be given multiple times.
IsMultiValueFlag() bool
}Methods
DocGenerationFlagIsMultiValueFlag func() boolIsMultiValueFlag returns true for flags that can be given multiple times.
type DurationFlag
type DurationFlag = FlagBase[time.Duration, NoConfig, durationValue]type EnvValueSource
EnvValueSource is to specifically detect env sources when printing help text
type EnvValueSource interface {
IsFromEnv() bool
Key() string
}Methods
IsFromEnv func() boolKey func() string
type ErrorFormatter
ErrorFormatter is the interface that will suitably format the error output
type ErrorFormatter interface {
Format(s fmt.State, verb rune)
}Methods
Format func(s fmt.State, verb rune)
type ExitCoder
ExitCoder is the interface checked by Command for a custom exit code.
type ExitCoder interface {
error
ExitCode() int
}Methods
errorExitCode func() int
type ExitErrHandlerFunc
ExitErrHandlerFunc is executed if provided in order to handle exitError values returned by Actions and Before/After functions.
type ExitErrHandlerFunc func(context.Context, *Command, error)type Flag
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.
type Flag interface {
fmt.Stringer
// Retrieve the value of the Flag
Get() any
// Lifecycle methods.
// flag callback prior to parsing
PreParse() error
// flag callback post parsing
PostParse() error
// Apply Flag settings to the given flag set
Set(string, string) error
// All possible names for this flag
Names() []string
// Whether the flag has been set or not
IsSet() bool
}Methods
fmt.StringerGet func() anyRetrieve the value of the Flag
PreParse func() errorLifecycle methods. flag callback prior to parsing
PostParse func() errorflag callback post parsing
Set func(string, string) errorApply Flag settings to the given flag set
Names func() []stringAll possible names for this flag
IsSet func() boolWhether the flag has been set or not
type FlagBase
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 emulationtype FlagBase[T any, C any, VC ValueCreator[T, C]] struct {
Name string `json:"name"` // name of the flag
Category string `json:"category"` // category of the flag, if any
DefaultText string `json:"defaultText"` // default text of the flag for usage purposes
HideDefault bool `json:"hideDefault"` // whether to hide the default value in output
Usage string `json:"usage"` // usage string for help output
Sources ValueSourceChain `json:"-"` // sources to load flag value from
Required bool `json:"required"` // whether the flag is required or not
Hidden bool `json:"hidden"` // whether to hide the flag in help output
Local bool `json:"local"` // whether the flag needs to be applied to subcommands as well
Value T `json:"defaultValue"` // default value for this flag if not set by from any source
Destination *T `json:"-"` // destination pointer for value when set
Aliases []string `json:"aliases"` // Aliases that are allowed for this flag
TakesFile bool `json:"takesFileArg"` // whether this flag takes a file argument, mainly for shell completion purposes
Action func(context.Context, *Command, T) error `json:"-"` // Action callback to be called when flag is set
Config C `json:"config"` // Additional/Custom configuration associated with this flag type
OnlyOnce bool `json:"onlyOnce"` // whether this flag can be duplicated on the command line
Validator func(T) error `json:"-"` // custom function to validate this flag value
ValidateDefaults bool `json:"validateDefaults"` // whether to validate defaults or not
// contains filtered or unexported fields
}Fields
Name string`json:"name"`name of the flag
Category string`json:"category"`category of the flag, if any
DefaultText string`json:"defaultText"`default text of the flag for usage purposes
HideDefault bool`json:"hideDefault"`whether to hide the default value in output
Usage string`json:"usage"`usage string for help output
Sources ValueSourceChain`json:"-"`sources to load flag value from
Required bool`json:"required"`whether the flag is required or not
Hidden bool`json:"hidden"`whether to hide the flag in help output
Local bool`json:"local"`whether the flag needs to be applied to subcommands as well
Value T`json:"defaultValue"`default value for this flag if not set by from any source
Destination *T`json:"-"`destination pointer for value when set
Aliases []string`json:"aliases"`Aliases that are allowed for this flag
TakesFile bool`json:"takesFileArg"`whether this flag takes a file argument, mainly for shell completion purposes
Action func(context.Context, *Command, T) error`json:"-"`Action callback to be called when flag is set
Config C`json:"config"`Additional/Custom configuration associated with this flag type
OnlyOnce bool`json:"onlyOnce"`whether this flag can be duplicated on the command line
Validator func(T) error`json:"-"`custom function to validate this flag value
ValidateDefaults bool`json:"validateDefaults"`whether to validate defaults or not
func Count() int
Count returns the number of times this flag has been invoked
func Get() any
func GetCategory() string
GetCategory returns the category of the flag
func GetDefaultText() string
GetDefaultText returns the default text for this flag
func GetEnvVars() []string
GetEnvVars returns the env vars for this flag
func GetUsage() string
GetUsage returns the usage string for the flag
func GetValue() string
GetValue returns the flags value as string representation and an empty string if the flag takes no value at all.
func IsBoolFlag() bool
IsBoolFlag returns whether the flag doesn't need to accept args
func IsDefaultVisible() bool
IsDefaultVisible returns true if the flag is not hidden, otherwise false
func IsLocal() bool
IsLocal returns false if flag needs to be persistent across subcommands
func IsMultiValueFlag() bool
IsMultiValueFlag returns true if the value type T can take multiple values from cmd line. This is true for slice and map type flags
func IsRequired() bool
IsRequired returns whether or not the flag is required
func IsSet() bool
IsSet returns whether or not the flag has been set through env or file
func IsVisible() bool
IsVisible returns true if the flag is not hidden, otherwise false
func Names() []string
Names returns the names of the flag
func PostParse() error
PostParse populates the flag given the flag set and environment
func PreParse() error
func RunAction(ctx context.Context, cmd *Command) error
RunAction executes flag action if set
func SchemaItemsType() string
SchemaItemsType returns the JSON Schema element type for slice flags.
func SchemaType() string
SchemaType returns the JSON Schema type for the flag's value type.
func Set(_ string, val string) error
Set applies given value from string
func SetCategory(c string)
func String() string
String returns a readable representation of this value (for usage defaults)
func TakesValue() bool
TakesValue returns true if the flag takes a value, otherwise false
func TypeName() string
TypeName returns the type of the flag.
type FlagCategories
FlagCategories interface allows for category manipulation
type FlagCategories interface {
// AddFlags adds a flag to a category, creating a new category if necessary.
AddFlag(category string, fl Flag)
// VisibleCategories returns a slice of visible flag categories sorted by name
VisibleCategories() []VisibleFlagCategory
}Methods
AddFlag func(category string, fl Flag)AddFlags adds a flag to a category, creating a new category if necessary.
VisibleCategories func() []VisibleFlagCategoryVisibleCategories returns a slice of visible flag categories sorted by name
type FlagEnvHintFunc
FlagEnvHintFunc is used by the default FlagStringFunc to annotate flag help with the environment variable details.
type FlagEnvHintFunc func(envVars []string, str string) stringtype FlagFileHintFunc
FlagFileHintFunc is used by the default FlagStringFunc to annotate flag help with the file path details.
type FlagFileHintFunc func(filePath, str string) stringtype FlagNamePrefixFunc
FlagNamePrefixFunc is used by the default FlagStringFunc to create prefix text for a flag's full name.
type FlagNamePrefixFunc func(fullName []string, placeholder string) stringtype FlagStringFunc
FlagStringFunc is used by the help generation to display a flag, which is expected to be a single line.
type FlagStringFunc func(Flag) stringtype FlagsByName
FlagsByName is a slice of Flag.
type FlagsByName []Flagfunc Len() int
func Less(i, j int) bool
func Swap(i, j int)
type Float32Arg
type Float32Arg = ArgumentBase[float32, NoConfig, floatValue[float32]]type Float32Args
type Float32Args = ArgumentsBase[float32, NoConfig, floatValue[float32]]type Float32Flag
type Float32Flag = FlagBase[float32, NoConfig, floatValue[float32]]type Float32Slice
type Float32Slice = SliceBase[float32, NoConfig, floatValue[float32]]type Float32SliceFlag
type Float32SliceFlag = FlagBase[[]float32, NoConfig, Float32Slice]type Float64Arg
type Float64Arg = ArgumentBase[float64, NoConfig, floatValue[float64]]type Float64Args
type Float64Args = ArgumentsBase[float64, NoConfig, floatValue[float64]]type Float64Flag
type Float64Flag = FlagBase[float64, NoConfig, floatValue[float64]]type Float64Slice
type Float64Slice = SliceBase[float64, NoConfig, floatValue[float64]]type Float64SliceFlag
type Float64SliceFlag = FlagBase[[]float64, NoConfig, Float64Slice]type FloatArg
type FloatArg = ArgumentBase[float64, NoConfig, floatValue[float64]]type FloatArgs
type FloatArgs = ArgumentsBase[float64, NoConfig, floatValue[float64]]type FloatFlag
type FloatFlag = FlagBase[float64, NoConfig, floatValue[float64]]type FloatSlice
type FloatSlice = SliceBase[float64, NoConfig, floatValue[float64]]type FloatSliceFlag
type FloatSliceFlag = FlagBase[[]float64, NoConfig, FloatSlice]type GenericFlag
type GenericFlag = FlagBase[Value, NoConfig, genericValue]type HelpPrinterCustomFunc
Prints help for the Command with custom template function.
type HelpPrinterCustomFunc func(w io.Writer, templ string, data any, customFunc map[string]any)type HelpPrinterFunc
HelpPrinterFunc prints help for the Command.
type HelpPrinterFunc func(w io.Writer, templ string, data any)type Int16Arg
type Int16Arg = ArgumentBase[int16, IntegerConfig, intValue[int16]]type Int16Args
type Int16Args = ArgumentsBase[int16, IntegerConfig, intValue[int16]]type Int16Flag
type Int16Flag = FlagBase[int16, IntegerConfig, intValue[int16]]type Int16Slice
type Int16Slice = SliceBase[int16, IntegerConfig, intValue[int16]]type Int16SliceFlag
type Int16SliceFlag = FlagBase[[]int16, IntegerConfig, Int16Slice]type Int32Arg
type Int32Arg = ArgumentBase[int32, IntegerConfig, intValue[int32]]type Int32Args
type Int32Args = ArgumentsBase[int32, IntegerConfig, intValue[int32]]type Int32Flag
type Int32Flag = FlagBase[int32, IntegerConfig, intValue[int32]]type Int32Slice
type Int32Slice = SliceBase[int32, IntegerConfig, intValue[int32]]type Int32SliceFlag
type Int32SliceFlag = FlagBase[[]int32, IntegerConfig, Int32Slice]type Int64Arg
type Int64Arg = ArgumentBase[int64, IntegerConfig, intValue[int64]]type Int64Args
type Int64Args = ArgumentsBase[int64, IntegerConfig, intValue[int64]]type Int64Flag
type Int64Flag = FlagBase[int64, IntegerConfig, intValue[int64]]type Int64Slice
type Int64Slice = SliceBase[int64, IntegerConfig, intValue[int64]]type Int64SliceFlag
type Int64SliceFlag = FlagBase[[]int64, IntegerConfig, Int64Slice]type Int8Arg
type Int8Arg = ArgumentBase[int8, IntegerConfig, intValue[int8]]type Int8Args
type Int8Args = ArgumentsBase[int8, IntegerConfig, intValue[int8]]type Int8Flag
type Int8Flag = FlagBase[int8, IntegerConfig, intValue[int8]]type Int8Slice
type Int8Slice = SliceBase[int8, IntegerConfig, intValue[int8]]type Int8SliceFlag
type Int8SliceFlag = FlagBase[[]int8, IntegerConfig, Int8Slice]type IntArg
type IntArg = ArgumentBase[int, IntegerConfig, intValue[int]]type IntArgs
type IntArgs = ArgumentsBase[int, IntegerConfig, intValue[int]]type IntFlag
type IntFlag = FlagBase[int, IntegerConfig, intValue[int]]type IntSlice
type IntSlice = SliceBase[int, IntegerConfig, intValue[int]]type IntSliceFlag
type IntSliceFlag = FlagBase[[]int, IntegerConfig, IntSlice]type IntegerConfig
IntegerConfig is the configuration for all integer type flags
type IntegerConfig struct {
Base int
}Fields
Base int
type InvalidFlagAccessFunc
InvalidFlagAccessFunc is executed when an invalid flag is accessed from the context.
type InvalidFlagAccessFunc func(context.Context, *Command, string)type LocalFlag
LocalFlag is an interface to enable detection of flags which are local to current command
type LocalFlag interface {
IsLocal() bool
}Methods
IsLocal func() bool
type MapBase
MapBase wraps map[string]T to satisfy flag.Value
type MapBase[T any, C any, VC ValueCreator[T, C]] struct {
// contains filtered or unexported fields
}func Create(val map[string]T, p *map[string]T, c C) Value
func Get() any
Get returns the mapping of values set by this flag
func Serialize() string
Serialize allows MapBase to fulfill Serializer
func Set(value string) error
Set parses the value and appends it to the list of values
func String() string
String returns a readable representation of this value (for usage defaults)
func ToString(t map[string]T) string
func Value() map[string]T
Value returns the mapping of values set by this flag
type MapSource
MapSource is a source which can be used to look up a value based on a key typically for use with a cli.Flag
type MapSource interface {
fmt.Stringer
fmt.GoStringer
// Lookup returns the value from the source based on key
// and if it was found
// or returns an empty string and false
Lookup(string) (any, bool)
}Methods
fmt.Stringerfmt.GoStringerLookup func(string) (any, bool)Lookup returns the value from the source based on key and if it was found or returns an empty string and false
type MultiError
MultiError is an error that wraps multiple errors.
type MultiError interface {
error
Errors() []error
}Methods
errorErrors func() []error
type MutuallyExclusiveFlags
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 MutuallyExclusiveFlags struct {
// Flag list
Flags [][]Flag
// whether this group is required
Required bool
// Category to apply to all flags within group
Category string
}Fields
Flags [][]FlagFlag list
Required boolwhether this group is required
Category stringCategory to apply to all flags within group
type NoConfig
NoConfig is for flags which dont need a custom configuration
type NoConfig struct{}type OnUsageErrorFunc
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 OnUsageErrorFunc func(ctx context.Context, cmd *Command, err error, isSubcommand bool) errortype RequiredFlag
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 RequiredFlag interface {
// whether the flag is a required flag or not
IsRequired() bool
}Methods
IsRequired func() boolwhether the flag is a required flag or not
type SchemaItemsTyper
SchemaItemsTyper is an optional interface for multi-value flags that can report the JSON Schema type of their elements.
type SchemaItemsTyper interface {
// SchemaItemsType returns the JSON Schema type of elements for
// array-type flags. Returns "" for single-value or object flags.
SchemaItemsType() string
}Methods
SchemaItemsType func() stringSchemaItemsType returns the JSON Schema type of elements for array-type flags. Returns "" for single-value or object flags.
type SchemaTyper
SchemaTyper is an optional interface for flags that can report their JSON Schema type for programmatic introspection.
type SchemaTyper interface {
// SchemaType returns the JSON Schema type name for the value this
// flag accepts: "boolean", "integer", "number", "string", "array",
// "object". Returns "" if the flag does not map cleanly.
SchemaType() string
}Methods
SchemaType func() stringSchemaType returns the JSON Schema type name for the value this flag accepts: "boolean", "integer", "number", "string", "array", "object". Returns "" if the flag does not map cleanly.
type Serializer
Serializer is used to circumvent the limitations of flag.FlagSet.Set
type Serializer interface {
Serialize() string
}Methods
Serialize func() string
type ShellCompleteFunc
ShellCompleteFunc is an action to execute when the shell completion flag is set
type ShellCompleteFunc func(context.Context, *Command)type SliceBase
SliceBase wraps []T to satisfy flag.Value
type SliceBase[T any, C any, VC ValueCreator[T, C]] struct {
// contains filtered or unexported fields
}func Create(val []T, p *[]T, c C) Value
func Get() any
Get returns the slice of values set by this flag
func Serialize() string
Serialize allows SliceBase to fulfill Serializer
func Set(value string) error
Set parses the value and appends it to the list of values
func String() string
String returns a readable representation of this value (for usage defaults)
func ToString(t []T) string
func Value() []T
Value returns the slice of values set by this flag
type StringArg
type StringArg = ArgumentBase[string, StringConfig, stringValue]type StringArgs
type StringArgs = ArgumentsBase[string, StringConfig, stringValue]type StringConfig
StringConfig defines the configuration for string flags
type StringConfig struct {
// Whether to trim whitespace of parsed value
TrimSpace bool
}Fields
TrimSpace boolWhether to trim whitespace of parsed value
type StringFlag
type StringFlag = FlagBase[string, StringConfig, stringValue]type StringMap
type StringMap = MapBase[string, StringConfig, stringValue]type StringMapArgs
type StringMapArgs = ArgumentBase[map[string]string, StringConfig, StringMap]type StringMapFlag
type StringMapFlag = FlagBase[map[string]string, StringConfig, StringMap]type StringSlice
type StringSlice = SliceBase[string, StringConfig, stringValue]type StringSliceFlag
type StringSliceFlag = FlagBase[[]string, StringConfig, StringSlice]type SuggestCommandFunc
type SuggestCommandFunc func(commands []*Command, provided string) stringtype SuggestFlagFunc
type SuggestFlagFunc func(flags []Flag, provided string, hideHelp bool) stringtype TimestampArg
type TimestampArg = ArgumentBase[time.Time, TimestampConfig, timestampValue]type TimestampArgs
type TimestampArgs = ArgumentsBase[time.Time, TimestampConfig, timestampValue]type TimestampConfig
TimestampConfig defines the config for timestamp flags
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-constants
Layouts []string
}Fields
Timezone *time.LocationLayouts []stringAvailable 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-constants
type TimestampFlag
type TimestampFlag = FlagBase[time.Time, TimestampConfig, timestampValue]type Uint16Arg
type Uint16Arg = ArgumentBase[uint16, IntegerConfig, uintValue[uint16]]type Uint16Args
type Uint16Args = ArgumentsBase[uint16, IntegerConfig, uintValue[uint16]]type Uint16Flag
type Uint16Flag = FlagBase[uint16, IntegerConfig, uintValue[uint16]]type Uint16Slice
type Uint16Slice = SliceBase[uint16, IntegerConfig, uintValue[uint16]]type Uint16SliceFlag
type Uint16SliceFlag = FlagBase[[]uint16, IntegerConfig, Uint16Slice]type Uint32Arg
type Uint32Arg = ArgumentBase[uint32, IntegerConfig, uintValue[uint32]]type Uint32Args
type Uint32Args = ArgumentsBase[uint32, IntegerConfig, uintValue[uint32]]type Uint32Flag
type Uint32Flag = FlagBase[uint32, IntegerConfig, uintValue[uint32]]type Uint32Slice
type Uint32Slice = SliceBase[uint32, IntegerConfig, uintValue[uint32]]type Uint32SliceFlag
type Uint32SliceFlag = FlagBase[[]uint32, IntegerConfig, Uint32Slice]type Uint64Arg
type Uint64Arg = ArgumentBase[uint64, IntegerConfig, uintValue[uint64]]type Uint64Args
type Uint64Args = ArgumentsBase[uint64, IntegerConfig, uintValue[uint64]]type Uint64Flag
type Uint64Flag = FlagBase[uint64, IntegerConfig, uintValue[uint64]]type Uint64Slice
type Uint64Slice = SliceBase[uint64, IntegerConfig, uintValue[uint64]]type Uint64SliceFlag
type Uint64SliceFlag = FlagBase[[]uint64, IntegerConfig, Uint64Slice]type Uint8Arg
type Uint8Arg = ArgumentBase[uint8, IntegerConfig, uintValue[uint8]]type Uint8Args
type Uint8Args = ArgumentsBase[uint8, IntegerConfig, uintValue[uint8]]type Uint8Flag
type Uint8Flag = FlagBase[uint8, IntegerConfig, uintValue[uint8]]type Uint8Slice
type Uint8Slice = SliceBase[uint8, IntegerConfig, uintValue[uint8]]type Uint8SliceFlag
type Uint8SliceFlag = FlagBase[[]uint8, IntegerConfig, Uint8Slice]type UintArg
type UintArg = ArgumentBase[uint, IntegerConfig, uintValue[uint]]type UintArgs
type UintArgs = ArgumentsBase[uint, IntegerConfig, uintValue[uint]]type UintFlag
type UintFlag = FlagBase[uint, IntegerConfig, uintValue[uint]]type UintSlice
type UintSlice = SliceBase[uint, IntegerConfig, uintValue[uint]]type UintSliceFlag
type UintSliceFlag = FlagBase[[]uint, IntegerConfig, UintSlice]type Value
Value represents a value as used by cli. For now it implements the golang flag.Value interface
type Value interface {
flag.Value
flag.Getter
}Methods
flag.Valueflag.Getter
type ValueCreator
ValueCreator is responsible for creating a flag.Value emulation as well as custom formatting
T specifies the type
C specifies the config for the typetype ValueCreator[T any, C any] interface {
Create(T, *T, C) Value
ToString(T) string
}Methods
Create func(T, *T, C) ValueToString func(T) string
type ValueSource
ValueSource is a source which can be used to look up a value, typically for use with a cli.Flag
type ValueSource interface {
fmt.Stringer
fmt.GoStringer
// Lookup returns the value from the source and if it was found
// or returns an empty string and false
Lookup() (string, bool)
}Methods
fmt.Stringerfmt.GoStringerLookup func() (string, bool)Lookup returns the value from the source and if it was found or returns an empty string and false
type ValueSourceChain
ValueSourceChain contains an ordered series of ValueSource that allows for lookup where the first ValueSource to resolve is returned
type ValueSourceChain struct {
Chain []ValueSource
}Fields
Chain []ValueSource
func Append(other ValueSourceChain)
func EnvKeys() []string
func GoString() string
func Lookup() (string, bool)
func LookupWithSource() (string, ValueSource, bool)
func String() string
type VisibleFlag
VisibleFlag is an interface that allows to check if a flag is visible
type VisibleFlag interface {
// IsVisible returns true if the flag is not hidden, otherwise false
IsVisible() bool
}Methods
IsVisible func() boolIsVisible returns true if the flag is not hidden, otherwise false
type VisibleFlagCategory
VisibleFlagCategory is a category containing flags.
type VisibleFlagCategory interface {
// Name returns the category name string
Name() string
// Flags returns a slice of VisibleFlag sorted by name
Flags() []Flag
}Methods
Name func() stringName returns the category name string
Flags func() []FlagFlags returns a slice of VisibleFlag sorted by name
