Documentation ¶
Overview ¶
Package kong aims to support arbitrarily complex command-line structures with as little developer effort as possible.
Here's an example:
shell rm [-f] [-r] <paths> ... shell ls [<paths> ...]
This can be represented by the following command-line structure:
package main import "github.com/alecthomas/kong" var CLI struct { Rm struct { Force bool `short:"f" help:"Force removal."` Recursive bool `short:"r" help:"Recursively remove files."` Paths []string `arg help:"Paths to remove." type:"path"` } `cmd help:"Remove files."` Ls struct { Paths []string `arg optional help:"Paths to list." type:"path"` } `cmd help:"List paths."` } func main() { kong.Parse(&CLI) }
See https://github.com/alecthomas/kong for details.
Index ¶
- Variables
- func ApplyDefaults(target any, options ...Option) error
- func BindW(w func(s string) string)
- func DefaultHelpPrinter(options HelpOptions, ctx *Context) error
- func DefaultHelpValueFormatter(value *Value) string
- func DefaultShortHelpPrinter(options HelpOptions, ctx *Context) error
- func ExpandPath(path string) string
- func HasInterpolatedVar(s string, v string) bool
- func JoinEscaped(s []string, sep rune) string
- func LineIndenter(prefix string) string
- func SpaceIndenter(prefix string) string
- func SplitEscaped(s string, sep rune) (out []string)
- func ToText(w io.Writer, text string, prefix, codePrefix string, width int)
- func TreeIndenter(prefix string) string
- func Visit(node Visitable, visitor Visitor) error
- type AfterApply
- type Application
- type Argument
- type BeforeApply
- type BeforeResolve
- type BoolMapper
- type BoolMapperExt
- type BoolMapperValue
- type ChangeDirFlag
- type Command
- type ConfigFlag
- type ConfigurationLoader
- type Context
- func (c *Context) AddResolver(resolver Resolver)
- func (c *Context) Apply() (string, error)
- func (c *Context) ApplyDefaults() error
- func (c *Context) Bind(args ...any)
- func (c *Context) BindTo(impl, iface any)
- func (c *Context) BindToProvider(provider any) error
- func (c *Context) Call(fn any, binds ...any) (out []any, err error)
- func (c *Context) Command() string
- func (c *Context) Empty() bool
- func (c *Context) FlagValue(flag *Flag) any
- func (c *Context) Flags() (flags []*Flag)
- func (c *Context) PrintUsage(summary bool) error
- func (c *Context) Reset() error
- func (c *Context) Resolve() error
- func (c *Context) Run(binds ...any) (err error)
- func (c *Context) RunNode(node *Node, binds ...any) (err error)
- func (c *Context) Selected() *Node
- func (c *Context) Validate() error
- func (c *Context) Value(path *Path) reflect.Value
- type DecodeContext
- type FileContentFlag
- type Flag
- type Group
- type Groups
- type HelpIndenter
- type HelpOptions
- type HelpPrinter
- type HelpProvider
- type HelpValueFormatter
- type Kong
- func (k *Kong) Errorf(format string, args ...any) *Kong
- func (k *Kong) FatalIfErrorf(err error, args ...any)
- func (k *Kong) Fatalf(format string, args ...any)
- func (k *Kong) LoadConfig(path string) (Resolver, error)
- func (k *Kong) Parse(args []string) (ctx *Context, err error)
- func (k *Kong) Printf(format string, args ...any) *Kong
- type Mapper
- type MapperFunc
- type MapperValue
- type NamedFileContentFlag
- type Next
- type Node
- func (n *Node) AllFlags(hide bool) (out [][]*Flag)
- func (n *Node) ClosestGroup() *Group
- func (n *Node) Depth() int
- func (n *Node) Find(ptr any) *Node
- func (n *Node) FlagSummary(hide bool) string
- func (n *Node) FullPath() string
- func (n *Node) Leaf() bool
- func (n *Node) Leaves(hide bool) (out []*Node)
- func (n *Node) Path() (out string)
- func (n *Node) Summary() string
- func (n *Node) Vars() Vars
- type NodeType
- type Option
- func AutoGroup(format func(parent Visitable, flag *Flag) *Group) Option
- func Bind(args ...any) Option
- func BindTo(impl, iface any) Option
- func BindToProvider(provider any) Option
- func ClearResolvers() Option
- func Configuration(loader ConfigurationLoader, paths ...string) Option
- func ConfigureHelp(options HelpOptions) Option
- func DefaultEnvars(prefix string) Option
- func Description(description string) Option
- func DynamicCommand(name, help, group string, cmd any, tags ...string) Option
- func Embed(strct any, tags ...string) Option
- func Exit(exit func(int)) Option
- func ExplicitGroups(groups []Group) Option
- func FlagNamer(namer func(fieldName string) string) Option
- func Help(help HelpPrinter) Option
- func HelpFormatter(helpFormatter HelpValueFormatter) Optiondeprecated
- func IgnoreFields(regexes ...string) Option
- func KindMapper(kind reflect.Kind, mapper Mapper) Option
- func Name(name string) Option
- func NamedMapper(name string, mapper Mapper) Option
- func NoDefaultHelp() Option
- func PostBuild(fn func(*Kong) error) Option
- func Resolvers(resolvers ...Resolver) Option
- func ShortHelp(shortHelp HelpPrinter) Option
- func ShortUsageOnError() Option
- func TypeMapper(typ reflect.Type, mapper Mapper) Option
- func UsageOnError() Option
- func ValueFormatter(helpFormatter HelpValueFormatter) Option
- func ValueMapper(ptr any, mapper Mapper) Option
- func Writers(stdout, stderr io.Writer) Option
- type OptionFunc
- type ParseError
- type PassthroughProvider
- type Path
- type PlaceHolderProvider
- type Plugins
- type Positional
- type Registry
- func (r *Registry) ForNamedType(name string, typ reflect.Type) Mapper
- func (r *Registry) ForNamedValue(name string, value reflect.Value) Mapper
- func (r *Registry) ForType(typ reflect.Type) Mapper
- func (r *Registry) ForValue(value reflect.Value) Mapper
- func (r *Registry) RegisterDefaults() *Registry
- func (r *Registry) RegisterKind(kind reflect.Kind, mapper Mapper) *Registry
- func (r *Registry) RegisterName(name string, mapper Mapper) *Registry
- func (r *Registry) RegisterType(typ reflect.Type, mapper Mapper) *Registry
- func (r *Registry) RegisterValue(ptr any, mapper Mapper) *Registry
- type Resolver
- type ResolverFunc
- type Scanner
- func (s *Scanner) Len() int
- func (s *Scanner) Peek() Token
- func (s *Scanner) Pop() Token
- func (s *Scanner) PopUntil(predicate func(Token) bool) (values []Token)
- func (s *Scanner) PopValue(context string) (Token, error)
- func (s *Scanner) PopValueInto(context string, target any) error
- func (s *Scanner) PopWhile(predicate func(Token) bool) (values []Token)
- func (s *Scanner) Push(arg any) *Scanner
- func (s *Scanner) PushToken(token Token) *Scanner
- func (s *Scanner) PushTyped(arg any, typ TokenType) *Scanner
- type SummaryProvider
- type Tag
- func (t *Tag) Get(k string) string
- func (t *Tag) GetAll(k string) []string
- func (t *Tag) GetBool(k string) (bool, error)
- func (t *Tag) GetFloat(k string) (float64, error)
- func (t *Tag) GetInt(k string) (int64, error)
- func (t *Tag) GetRune(k string) (rune, error)
- func (t *Tag) GetSep(k string, dflt rune) (rune, error)
- func (t *Tag) Has(k string) bool
- func (t *Tag) String() string
- type Token
- type TokenType
- type Value
- func (v *Value) Apply(value reflect.Value)
- func (v *Value) ApplyDefault() error
- func (v *Value) EnumMap() map[string]bool
- func (v *Value) EnumSlice() []string
- func (v *Value) IsBool() bool
- func (v *Value) IsCounter() bool
- func (v *Value) IsCumulative() bool
- func (v *Value) IsMap() bool
- func (v *Value) IsSlice() bool
- func (v *Value) Parse(scan *Scanner, target reflect.Value) (err error)
- func (v *Value) Reset() error
- func (v *Value) ShortSummary() string
- func (v *Value) Summary() string
- type Vars
- type VarsContributor
- type VersionFlag
- type Visitable
- type Visitor
Constants ¶
This section is empty.
Variables ¶
var (
W = func(s string) string {
return s
}
)
Functions ¶
func ApplyDefaults ¶
ApplyDefaults if they are not already set.
func DefaultHelpPrinter ¶
func DefaultHelpPrinter(options HelpOptions, ctx *Context) error
DefaultHelpPrinter is the default HelpPrinter.
func DefaultHelpValueFormatter ¶
DefaultHelpValueFormatter is the default HelpValueFormatter.
func DefaultShortHelpPrinter ¶
func DefaultShortHelpPrinter(options HelpOptions, ctx *Context) error
DefaultShortHelpPrinter is the default HelpPrinter for short help on error.
func ExpandPath ¶
ExpandPath is a helper function to expand a relative or home-relative path to an absolute path.
eg. ~/.someconf -> /home/alec/.someconf
func HasInterpolatedVar ¶
HasInterpolatedVar returns true if the variable "v" is interpolated in "s".
func JoinEscaped ¶
JoinEscaped joins a slice of strings on sep, but also escapes any instances of sep in the fields with \. eg.
JoinEscaped([]string{"hello,there", "bob"}, ',') == `hello\,there,bob`
func LineIndenter ¶
LineIndenter adds line points to every new indent.
func SpaceIndenter ¶
SpaceIndenter adds a space indent to the given prefix.
func SplitEscaped ¶
SplitEscaped splits a string on a separator.
It differs from strings.Split() in that the separator can exist in a field by escaping it with a \. eg.
SplitEscaped(`hello\,there,bob`, ',') == []string{"hello,there", "bob"}
func TreeIndenter ¶
TreeIndenter adds line points to every new indent and vertical lines to every layer.
Types ¶
type AfterApply ¶
type AfterApply interface { // This is not the correct signature - see README for details. AfterApply(args ...any) error }
AfterApply is a documentation-only interface describing hooks that run after values are set.
type Application ¶
type Application struct { *Node // Help flag, if the NoDefaultHelp() option is not specified. HelpFlag *Flag }
Application is the root of the Kong model.
type BeforeApply ¶
type BeforeApply interface { // This is not the correct signature - see README for details. BeforeApply(args ...any) error }
BeforeApply is a documentation-only interface describing hooks that run before values are set.
type BeforeResolve ¶
type BeforeResolve interface { // This is not the correct signature - see README for details. BeforeResolve(args ...any) error }
BeforeResolve is a documentation-only interface describing hooks that run before resolvers are applied.
type BoolMapper ¶
A BoolMapper is a Mapper to a value that is a boolean.
This is used solely for formatting help.
type BoolMapperExt ¶
BoolMapperExt allows a Mapper to dynamically determine if a value is a boolean.
type BoolMapperValue ¶
type BoolMapperValue interface { MapperValue IsBool() bool }
BoolMapperValue may be implemented by fields in order to provide custom mappings for boolean values.
type ChangeDirFlag ¶
type ChangeDirFlag string
ChangeDirFlag changes the current working directory to a path specified by a flag early in the parsing process, changing how other flags resolve relative paths.
Use this flag to provide a "git -C" like functionality.
It is not compatible with custom named decoders, e.g., existingdir.
func (ChangeDirFlag) Decode ¶
func (c ChangeDirFlag) Decode(ctx *DecodeContext) error
Decode is used to create a side effect of changing the current working directory.
type ConfigFlag ¶
type ConfigFlag string
ConfigFlag uses the configured (via kong.Configuration(loader)) configuration loader to load configuration from a file specified by a flag.
Use this as a flag value to support loading of custom configuration via a flag.
func (ConfigFlag) BeforeResolve ¶
func (c ConfigFlag) BeforeResolve(kong *Kong, ctx *Context, trace *Path) error
BeforeResolve adds a resolver.
type ConfigurationLoader ¶
ConfigurationLoader is a function that builds a resolver from a file.
type Context ¶
type Context struct { *Kong // A trace through parsed nodes. Path []*Path // Original command-line arguments. Args []string // Error that occurred during trace, if any. Error error // contains filtered or unexported fields }
Context contains the current parse context.
func Trace ¶
Trace path of "args" through the grammar tree.
The returned Context will include a Path of all commands, arguments, positionals and flags.
This just constructs a new trace. To fully apply the trace you must call Reset(), Resolve(), Validate() and Apply().
func (*Context) AddResolver ¶
AddResolver adds a context-specific resolver.
This is most useful in the BeforeResolve() hook.
func (*Context) ApplyDefaults ¶
ApplyDefaults if they are not already set.
func (*Context) BindTo ¶
BindTo adds a binding to the Context.
This will typically have to be called like so:
BindTo(impl, (*MyInterface)(nil))
func (*Context) BindToProvider ¶
BindToProvider allows binding of provider functions.
This is useful when the Run() function of different commands require different values that may not all be initialisable from the main() function.
func (*Context) FlagValue ¶
FlagValue returns the set value of a flag if it was encountered and exists, or its default value.
func (*Context) PrintUsage ¶
PrintUsage to Kong's stdout.
If summary is true, a summarised version of the help will be output.
func (*Context) Reset ¶
Reset recursively resets values to defaults (as specified in the grammar) or the zero value.
func (*Context) Resolve ¶
Resolve walks through the traced path, applying resolvers to any unset flags.
func (*Context) Run ¶
Run executes the Run() method on the selected command, which must exist.
Any passed values will be bindable to arguments of the target Run() method. Additionally, all parent nodes in the command structure will be bound.
func (*Context) RunNode ¶
RunNode calls the Run() method on an arbitrary node.
This is useful in conjunction with Visit(), for dynamically running commands.
Any passed values will be bindable to arguments of the target Run() method. Additionally, all parent nodes in the command structure will be bound.
type DecodeContext ¶
type DecodeContext struct { // Value being decoded into. Value *Value // Scan contains the input to scan into Target. Scan *Scanner }
DecodeContext is passed to a Mapper's Decode().
It contains the Value being decoded into and the Scanner to parse from.
func (*DecodeContext) WithScanner ¶
func (r *DecodeContext) WithScanner(scan *Scanner) *DecodeContext
WithScanner creates a clone of this context with a new Scanner.
type FileContentFlag ¶
type FileContentFlag []byte
FileContentFlag is a flag value that loads a file's contents into its value.
func (*FileContentFlag) Decode ¶
func (f *FileContentFlag) Decode(ctx *DecodeContext) error
type Flag ¶
type Flag struct { *Value Group *Group // Logical grouping when displaying. May also be used by configuration loaders to group options logically. Xor []string And []string PlaceHolder string Envs []string Aliases []string Short rune Hidden bool Negated bool }
A Flag represents a command-line flag.
func (*Flag) FormatPlaceHolder ¶
FormatPlaceHolder formats the placeholder string for a Flag.
type Group ¶
type Group struct { // Key is the `group` field tag value used to identify this group. Key string // Title is displayed above the grouped items. Title string // Description is optional and displayed under the Title when non empty. // It can be used to introduce the group's purpose to the user. Description string }
Group holds metadata about a command or flag group used when printing help.
type Groups ¶
Groups associates `group` field tags with group metadata.
This option is used to simplify Kong tags while providing rich group information such as title and optional description.
Each key in the "groups" map corresponds to the value of a `group` Kong tag, while the first line of the value will be the title, and subsequent lines if any will be the description of the group.
See also ExplicitGroups for a more structured alternative.
type HelpIndenter ¶
HelpIndenter is used to indent new layers in the help tree.
type HelpOptions ¶
type HelpOptions struct { // Don't print top-level usage summary. NoAppSummary bool // Write a one-line summary of the context. Summary bool // Write help in a more compact, but still fully-specified, form. Compact bool // Tree writes command chains in a tree structure instead of listing them separately. Tree bool // Place the flags after the commands listing. FlagsLast bool // Indenter modulates the given prefix for the next layer in the tree view. // The following exported templates can be used: kong.SpaceIndenter, kong.LineIndenter, kong.TreeIndenter // The kong.SpaceIndenter will be used by default. Indenter HelpIndenter // Don't show the help associated with subcommands NoExpandSubcommands bool // Clamp the help wrap width to a value smaller than the terminal width. // If this is set to a non-positive number, the terminal width is used; otherwise, // the min of this value or the terminal width is used. WrapUpperBound int }
HelpOptions for HelpPrinters.
func (HelpOptions) Apply ¶
func (h HelpOptions) Apply(k *Kong) error
Apply options to Kong as a configuration option.
func (*HelpOptions) CommandTree ¶
func (h *HelpOptions) CommandTree(node *Node, prefix string) (rows [][2]string)
CommandTree creates a tree with the given node name as root and its children's arguments and sub commands as leaves.
type HelpPrinter ¶
type HelpPrinter func(options HelpOptions, ctx *Context) error
HelpPrinter is used to print context-sensitive help.
type HelpProvider ¶
type HelpProvider interface { // This string is formatted by go/doc and thus has the same formatting rules. Help() string }
HelpProvider can be implemented by commands/args to provide detailed help.
type HelpValueFormatter ¶
HelpValueFormatter is used to format the help text of flags and positional arguments.
type Kong ¶
type Kong struct { // Grammar model. Model *Application // Termination function (defaults to os.Exit) Exit func(int) Stdout io.Writer Stderr io.Writer // contains filtered or unexported fields }
Kong is the main parser type.
func New ¶
New creates a new Kong parser on grammar.
See the README (https://github.com/alecthomas/kong) for usage instructions.
func (*Kong) FatalIfErrorf ¶
FatalIfErrorf terminates with an error message if err != nil.
func (*Kong) Fatalf ¶
Fatalf writes a message to Kong.Stderr with the application name prefixed then exits with a non-zero status.
func (*Kong) LoadConfig ¶
LoadConfig from path using the loader configured via Configuration(loader).
"path" will have ~ and any variables expanded.
func (*Kong) Parse ¶
Parse arguments into target.
The return Context can be used to further inspect the parsed command-line, to format help, to find the selected command, to run command Run() methods, and so on. See Context and README for more information.
Will return a ParseError if a *semantically* invalid command-line is encountered (as opposed to a syntactically invalid one, which will report a normal error).
type Mapper ¶
type Mapper interface { // Decode ctx.Value with ctx.Scanner into target. Decode(ctx *DecodeContext, target reflect.Value) error }
A Mapper represents how a field is mapped from command-line values to Go.
Mappers can be associated with concrete fields via pointer, reflect.Type, reflect.Kind, or via a "type" tag.
Additionally, if a type implements the MapperValue interface, it will be used.
type MapperFunc ¶
type MapperFunc func(ctx *DecodeContext, target reflect.Value) error
A MapperFunc is a single function that complies with the Mapper interface.
func (MapperFunc) Decode ¶
func (m MapperFunc) Decode(ctx *DecodeContext, target reflect.Value) error
type MapperValue ¶
type MapperValue interface {
Decode(ctx *DecodeContext) error
}
MapperValue may be implemented by fields in order to provide custom mapping. Mappers may additionally implement PlaceHolderProvider to provide custom placeholder text.
type NamedFileContentFlag ¶
NamedFileContentFlag is a flag value that loads a file's contents and filename into its value.
func (*NamedFileContentFlag) Decode ¶
func (f *NamedFileContentFlag) Decode(ctx *DecodeContext) error
type Next ¶
Next should be called by Visitor to proceed with the walk.
The walk will terminate if "err" is non-nil.
type Node ¶
type Node struct { Type NodeType Parent *Node Name string Help string // Short help displayed in summaries. Detail string // Detailed help displayed when describing command/arg alone. Group *Group Hidden bool Flags []*Flag Positional []*Positional Children []*Node DefaultCmd *Node Target reflect.Value // Pointer to the value in the grammar that this Node is associated with. Tag *Tag Aliases []string Passthrough bool // Set to true to stop flag parsing when encountered. Active bool // Denotes the node is part of an active branch in the CLI. Argument *Value // Populated when Type is ArgumentNode. }
Node is a branch in the CLI. ie. a command or positional argument.
func (*Node) AllFlags ¶
AllFlags returns flags from all ancestor branches encountered.
If "hide" is true hidden flags will be omitted.
func (*Node) ClosestGroup ¶
ClosestGroup finds the first non-nil group in this node and its ancestors.
func (*Node) Find ¶
Find a command/argument/flag by pointer to its field.
Returns nil if not found. Panics if ptr is not a pointer.
func (*Node) Leaves ¶
Leaves returns the leaf commands/arguments under Node.
If "hidden" is true hidden leaves will be omitted.
type Option ¶
An Option applies optional changes to the Kong application.
func Bind ¶
Bind binds values for hooks and Run() function arguments.
Any arguments passed will be available to the receiving hook functions, but may be omitted. Additionally, *Kong and the current *Context will also be made available.
There are two hook points:
BeforeApply(...) error AfterApply(...) error
Called before validation/assignment, and immediately after validation/assignment, respectively.
func BindToProvider ¶
BindToProvider allows binding of provider functions.
This is useful when the Run() function of different commands require different values that may not all be initialisable from the main() function.
func Configuration ¶
func Configuration(loader ConfigurationLoader, paths ...string) Option
Configuration provides Kong with support for loading defaults from a set of configuration files.
Paths will be opened in order, and "loader" will be used to provide a Resolver which is registered with Kong.
Note: The JSON function is a ConfigurationLoader.
~ and variable expansion will occur on the provided paths.
func ConfigureHelp ¶
func ConfigureHelp(options HelpOptions) Option
ConfigureHelp sets the HelpOptions to use for printing help.
func DefaultEnvars ¶
DefaultEnvars option inits environment names for flags. The name will not generate if tag "env" is "-". Predefined environment variables are skipped.
For example:
--some.value -> PREFIX_SOME_VALUE
func Description ¶
Description sets the application description.
func DynamicCommand ¶
DynamicCommand registers a dynamically constructed command with the root of the CLI.
This is useful for command-line structures that are extensible via user-provided plugins.
"tags" is a list of extra tag strings to parse, in the form <key>:"<value>".
func Exit ¶
Exit overrides the function used to terminate. This is useful for testing or interactive use.
func ExplicitGroups ¶
ExplicitGroups associates `group` field tags with their metadata.
It can be used to provide a title or header to a command or flag group.
func FlagNamer ¶
FlagNamer allows you to override the default kebab-case automated flag name generation.
func HelpFormatter
deprecated
func HelpFormatter(helpFormatter HelpValueFormatter) Option
HelpFormatter configures how the help text is formatted.
Deprecated: Use ValueFormatter() instead.
func IgnoreFields ¶
IgnoreFields will cause kong.New() to skip field names that match any of the provided regex patterns. This is useful if you are not able to add a kong="-" struct tag to a struct/element before the call to New.
Example: When referencing protoc generated structs, you will likely want to ignore/skip XXX_* fields.
func KindMapper ¶
KindMapper registers a mapper to a kind.
func NamedMapper ¶
NamedMapper registers a mapper to a name.
func PostBuild ¶
PostBuild provides read/write access to kong.Kong after initial construction of the model is complete but before parsing occurs.
This is useful for, e.g., adding short options to flags, updating help, etc.
func ShortHelp ¶
func ShortHelp(shortHelp HelpPrinter) Option
ShortHelp configures the short usage message.
It should be used together with kong.ShortUsageOnError() to display a custom short usage message on errors.
func ShortUsageOnError ¶
func ShortUsageOnError() Option
ShortUsageOnError configures Kong to display context-sensitive short usage if FatalIfErrorf is called with an error. The default short usage message can be overridden with kong.ShortHelp(...).
func TypeMapper ¶
TypeMapper registers a mapper to a type.
func UsageOnError ¶
func UsageOnError() Option
UsageOnError configures Kong to display context-sensitive usage if FatalIfErrorf is called with an error.
func ValueFormatter ¶
func ValueFormatter(helpFormatter HelpValueFormatter) Option
ValueFormatter configures how the help text is formatted.
func ValueMapper ¶
ValueMapper registers a mapper to a field value.
type OptionFunc ¶
OptionFunc is function that adheres to the Option interface.
func (OptionFunc) Apply ¶
func (o OptionFunc) Apply(k *Kong) error
type ParseError ¶
type ParseError struct { Context *Context // contains filtered or unexported fields }
ParseError is the error type returned by Kong.Parse().
It contains the parse Context that triggered the error.
func (*ParseError) Unwrap ¶
func (p *ParseError) Unwrap() error
Unwrap returns the original cause of the error.
type PassthroughProvider ¶
type PassthroughProvider interface { // This string is formatted by go/doc and thus has the same formatting rules. Passthrough([]string) }
PassthroughProvider can be implemented by commands/args to provide store passthrough.
type Path ¶
type Path struct { Parent *Node // One of these will be non-nil. App *Application Positional *Positional Flag *Flag Argument *Argument Command *Command // Flags added by this node. Flags []*Flag // True if this Path element was created as the result of a resolver. Resolved bool }
Path records the nodes and parsed values from the current command-line.
type PlaceHolderProvider ¶
PlaceHolderProvider can be implemented by mappers to provide custom placeholder text.
type Plugins ¶
type Plugins []any
Plugins are dynamically embedded command-line structures.
Each element in the Plugins list *must* be a pointer to a structure.
type Positional ¶
type Positional = Value
A Positional represents a non-branching command-line positional argument.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
A Registry contains a set of mappers and supporting lookup methods.
func (*Registry) ForNamedType ¶
ForNamedType finds a mapper for a type with a user-specified name.
Will return nil if a mapper can not be determined.
func (*Registry) ForNamedValue ¶
ForNamedValue finds a mapper for a value with a user-specified name.
Will return nil if a mapper can not be determined.
func (*Registry) ForType ¶
ForType finds a mapper from a type, by type, then kind.
Will return nil if a mapper can not be determined.
func (*Registry) RegisterDefaults ¶
RegisterDefaults registers Mappers for all builtin supported Go types and some common stdlib types.
func (*Registry) RegisterKind ¶
RegisterKind registers a Mapper for a reflect.Kind.
func (*Registry) RegisterName ¶
RegisterName registers a mapper to be used if the value mapper has a "type" tag matching name.
eg.
Mapper string `kong:"type='colour'` registry.RegisterName("colour", ...)
func (*Registry) RegisterType ¶
RegisterType registers a Mapper for a reflect.Type.
type Resolver ¶
type Resolver interface { // Validate configuration against Application. // // This can be used to validate that all provided configuration is valid within this application. Validate(app *Application) error // Resolve the value for a Flag. Resolve(context *Context, parent *Path, flag *Flag) (any, error) }
A Resolver resolves a Flag value from an external source.
type ResolverFunc ¶
ResolverFunc is a convenience type for non-validating Resolvers.
func (ResolverFunc) Validate ¶
func (r ResolverFunc) Validate(app *Application) error
type Scanner ¶
type Scanner struct {
// contains filtered or unexported fields
}
Scanner is a stack-based scanner over command-line tokens.
Initially all tokens are untyped. As the parser consumes tokens it assigns types, splits tokens, and pushes them back onto the stream.
For example, the token "--foo=bar" will be split into the following by the parser:
[{FlagToken, "foo"}, {FlagValueToken, "bar"}]
func ScanAsType ¶
ScanAsType creates a new Scanner from args with the given type.
func ScanFromTokens ¶
ScanFromTokens creates a new Scanner from a slice of tokens.
func (*Scanner) PopValue ¶
PopValue pops a value token, or returns an error.
"context" is used to assist the user if the value can not be popped, eg. "expected <context> value but got <type>"
func (*Scanner) PopValueInto ¶
PopValueInto pops a value token into target or returns an error.
"context" is used to assist the user if the value can not be popped, eg. "expected <context> value but got <type>"
type SummaryProvider ¶
type SummaryProvider interface {
Summary() string
}
type Tag ¶
type Tag struct { Ignored bool // Field is ignored by Kong. ie. kong:"-" Cmd bool Arg bool Required bool Optional bool Name string Help string Type string TypeName string HasDefault bool Default string Format string PlaceHolder string Envs []string Short rune Hidden bool Sep rune MapSep rune Enum string Group string Xor []string And []string Vars Vars Prefix string // Optional prefix on anonymous structs. All sub-flags will have this prefix. EnvPrefix string Embed bool Aliases []string Negatable bool Passthrough bool // contains filtered or unexported fields }
Tag represents the parsed state of Kong tags in a struct field tag.
func (*Tag) Get ¶
Get returns the value of the given tag.
Note that this will return the empty string if the tag is missing.
func (*Tag) GetAll ¶
GetAll returns all encountered values for a tag, in the case of multiple occurrences.
func (*Tag) GetSep ¶
GetSep parses the given tag as a rune separator, allowing for a default or none. The separator is returned, or -1 if "none" is specified. If the tag value is an invalid utf8 sequence, the default rune is returned as well as an error. If the tag value is more than one rune, the first rune is returned as well as an error.
type Token ¶
Token created by Scanner.
func (Token) InferredType ¶
InferredType tries to infer the type of a token.
type TokenType ¶
type TokenType int
TokenType is the type of a token.
const ( UntypedToken TokenType = iota EOLToken FlagToken // --<flag> FlagValueToken // =<value> ShortFlagToken // -<short>[<tail] ShortFlagTailToken // <tail> PositionalArgumentToken // <arg> )
Token types.
type Value ¶
type Value struct { Flag *Flag // Nil if positional argument. Name string Help string OrigHelp string // Original help string, without interpolated variables. HasDefault bool Default string DefaultValue reflect.Value Enum string Mapper Mapper Tag *Tag Target reflect.Value Required bool Set bool // Set to true when this value is set through some mechanism. Format string // Formatting directive, if applicable. Position int // Position (for positional arguments). Passthrough bool // Set to true to stop flag parsing when encountered. Active bool // Denotes the value is part of an active branch in the CLI. Hidden bool // Hidden help }
A Value is either a flag or a variable positional argument.
func (*Value) ApplyDefault ¶
ApplyDefault value to field if it is not already set.
func (*Value) IsCumulative ¶
IsCumulative returns true if the type can be accumulated into.
func (*Value) Reset ¶
Reset this value to its default, either the zero value or the parsed result of its envar, or its "default" tag.
Does not include resolvers.
func (*Value) ShortSummary ¶
ShortSummary returns a human-readable summary of the value, not including any placeholders/defaults.
type Vars ¶
Vars sets the variables to use for interpolation into help strings and default values.
See README for details.
type VarsContributor ¶
VarsContributor can be implemented by a Mapper to contribute Vars during interpolation.
type VersionFlag ¶
type VersionFlag bool
VersionFlag is a flag type that can be used to display a version number, stored in the "version" variable.
func (VersionFlag) BeforeReset ¶
func (v VersionFlag) BeforeReset(app *Kong, vars Vars) error
BeforeReset writes the version variable and terminates with a 0 exit status.