kong

package module
v1.5.1 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2024 License: MIT Imports: 23 Imported by: 2,128

README

Kong is a command-line parser for Go

CircleCI Go Report Card Slack chat

Version 1.0.0 Release

Kong has been stable for a long time, so it seemed appropriate to cut a 1.0 release.

There is one breaking change, #436, which should effect relatively few users.

Introduction

Kong aims to support arbitrarily complex command-line structures with as little developer effort as possible.

To achieve that, command-lines are expressed as Go types, with the structure and tags directing how the command line is mapped onto the struct.

For example, the following command-line:

shell rm [-f] [-r] <paths> ...
shell ls [<paths> ...]

Can be represented by the following command-line structure:

package main

import "github.com/alecthomas/kong"

var CLI struct {
  Rm struct {
    Force     bool `help:"Force removal."`
    Recursive bool `help:"Recursively remove files."`

    Paths []string `arg:"" name:"path" help:"Paths to remove." type:"path"`
  } `cmd:"" help:"Remove files."`

  Ls struct {
    Paths []string `arg:"" optional:"" name:"path" help:"Paths to list." type:"path"`
  } `cmd:"" help:"List paths."`
}

func main() {
  ctx := kong.Parse(&CLI)
  switch ctx.Command() {
  case "rm <path>":
  case "ls":
  default:
    panic(ctx.Command())
  }
}

Help

Help as a user of a Kong application

Every Kong application includes a --help flag that will display auto-generated help.

eg.

$ shell --help
usage: shell <command>

A shell-like example app.

Flags:
  --help   Show context-sensitive help.
  --debug  Debug mode.

Commands:
  rm <path> ...
    Remove files.

  ls [<path> ...]
    List paths.

If a command is provided, the help will show full detail on the command including all available flags.

eg.

$ shell --help rm
usage: shell rm <paths> ...

Remove files.

Arguments:
  <paths> ...  Paths to remove.

Flags:
      --debug        Debug mode.

  -f, --force        Force removal.
  -r, --recursive    Recursively remove files.
Defining help in Kong

Help is automatically generated from the command-line structure itself, including help:"" and other tags. Variables will also be interpolated into the help string.

Finally, any command, or argument type implementing the interface Help() string will have this function called to retrieve more detail to augment the help tag. This allows for much more descriptive text than can fit in Go tags. See _examples/shell/help

Showing the command's detailed help

A command's additional help text is not shown from top-level help, but can be displayed within contextual help:

Top level help

 $ go run ./_examples/shell/help --help
Usage: help <command>

An app demonstrating HelpProviders

Flags:
  -h, --help    Show context-sensitive help.
      --flag    Regular flag help

Commands:
  echo    Regular command help

Contextual

 $ go run ./_examples/shell/help echo --help
Usage: help echo <msg>

Regular command help

🚀 additional command help

Arguments:
  <msg>    Regular argument help

Flags:
  -h, --help    Show context-sensitive help.
      --flag    Regular flag help
Showing an argument's detailed help

Custom help will only be shown for positional arguments with named fields (see the README section on positional arguments for more details on what that means)

Contextual argument help

 $ go run ./_examples/shell/help msg --help
Usage: help echo <msg>

Regular argument help

📣 additional argument help

Flags:
  -h, --help    Show context-sensitive help.
      --flag    Regular flag help

Command handling

There are two ways to handle commands in Kong.

Switch on the command string

When you call kong.Parse() it will return a unique string representation of the command. Each command branch in the hierarchy will be a bare word and each branching argument or required positional argument will be the name surrounded by angle brackets. Here's an example:

There's an example of this pattern here.

eg.

package main

import "github.com/alecthomas/kong"

var CLI struct {
  Rm struct {
    Force     bool `help:"Force removal."`
    Recursive bool `help:"Recursively remove files."`

    Paths []string `arg:"" name:"path" help:"Paths to remove." type:"path"`
  } `cmd:"" help:"Remove files."`

  Ls struct {
    Paths []string `arg:"" optional:"" name:"path" help:"Paths to list." type:"path"`
  } `cmd:"" help:"List paths."`
}

func main() {
  ctx := kong.Parse(&CLI)
  switch ctx.Command() {
  case "rm <path>":
  case "ls":
  default:
    panic(ctx.Command())
  }
}

This has the advantage that it is convenient, but the downside that if you modify your CLI structure, the strings may change. This can be fragile.

Attach a Run(...) error method to each command

A more robust approach is to break each command out into their own structs:

  1. Break leaf commands out into separate structs.
  2. Attach a Run(...) error method to all leaf commands.
  3. Call kong.Kong.Parse() to obtain a kong.Context.
  4. Call kong.Context.Run(bindings...) to call the selected parsed command.

Once a command node is selected by Kong it will search from that node back to the root. Each encountered command node with a Run(...) error will be called in reverse order. This allows sub-trees to be re-used fairly conveniently.

In addition to values bound with the kong.Bind(...) option, any values passed through to kong.Context.Run(...) are also bindable to the target's Run() arguments.

Finally, hooks can also contribute bindings via kong.Context.Bind() and kong.Context.BindTo().

There's a full example emulating part of the Docker CLI here.

eg.

type Context struct {
  Debug bool
}

type RmCmd struct {
  Force     bool `help:"Force removal."`
  Recursive bool `help:"Recursively remove files."`

  Paths []string `arg:"" name:"path" help:"Paths to remove." type:"path"`
}

func (r *RmCmd) Run(ctx *Context) error {
  fmt.Println("rm", r.Paths)
  return nil
}

type LsCmd struct {
  Paths []string `arg:"" optional:"" name:"path" help:"Paths to list." type:"path"`
}

func (l *LsCmd) Run(ctx *Context) error {
  fmt.Println("ls", l.Paths)
  return nil
}

var cli struct {
  Debug bool `help:"Enable debug mode."`

  Rm RmCmd `cmd:"" help:"Remove files."`
  Ls LsCmd `cmd:"" help:"List paths."`
}

func main() {
  ctx := kong.Parse(&cli)
  // Call the Run() method of the selected parsed command.
  err := ctx.Run(&Context{Debug: cli.Debug})
  ctx.FatalIfErrorf(err)
}

Hooks: BeforeReset(), BeforeResolve(), BeforeApply(), AfterApply() and the Bind() option

If a node in the grammar has a BeforeReset(...), BeforeResolve (...), BeforeApply(...) error and/or AfterApply(...) error method, those methods will be called before values are reset, before validation/assignment, and after validation/assignment, respectively.

The --help flag is implemented with a BeforeReset hook.

Arguments to hooks are provided via the Run(...) method or Bind(...) option. *Kong, *Context and *Path are also bound and finally, hooks can also contribute bindings via kong.Context.Bind() and kong.Context.BindTo().

eg.

// A flag with a hook that, if triggered, will set the debug loggers output to stdout.
type debugFlag bool

func (d debugFlag) BeforeApply(logger *log.Logger) error {
  logger.SetOutput(os.Stdout)
  return nil
}

var cli struct {
  Debug debugFlag `help:"Enable debug logging."`
}

func main() {
  // Debug logger going to discard.
  logger := log.New(io.Discard, "", log.LstdFlags)

  ctx := kong.Parse(&cli, kong.Bind(logger))

  // ...
}

Another example of using hooks is load the env-file:

package main

import (
  "fmt"
  "github.com/alecthomas/kong"
  "github.com/joho/godotenv"
)

type EnvFlag string

// BeforeResolve loads env file.
func (c EnvFlag) BeforeReset(ctx *kong.Context, trace *kong.Path) error {
  path := string(ctx.FlagValue(trace.Flag).(EnvFlag)) // nolint
  path = kong.ExpandPath(path)
  if err := godotenv.Load(path); err != nil {
    return err
  }
  return nil
}

var CLI struct {
  EnvFile EnvFlag
  Flag `env:"FLAG"`
}

func main() {
  _ = kong.Parse(&CLI)
  fmt.Println(CLI.Flag)
}

Flags

Any mapped field in the command structure not tagged with cmd or arg will be a flag. Flags are optional by default.

eg. The command-line app [--flag="foo"] can be represented by the following.

type CLI struct {
  Flag string
}

Commands and sub-commands

Sub-commands are specified by tagging a struct field with cmd. Kong supports arbitrarily nested commands.

eg. The following struct represents the CLI structure command [--flag="str"] sub-command.

type CLI struct {
  Command struct {
    Flag string

    SubCommand struct {
    } `cmd`
  } `cmd`
}

If a sub-command is tagged with default:"1" it will be selected if there are no further arguments. If a sub-command is tagged with default:"withargs" it will be selected even if there are further arguments or flags and those arguments or flags are valid for the sub-command. This allows the user to omit the sub-command name on the CLI if its arguments/flags are not ambiguous with the sibling commands or flags.

Branching positional arguments

In addition to sub-commands, structs can also be configured as branching positional arguments.

This is achieved by tagging an unmapped nested struct field with arg, then including a positional argument field inside that struct with the same name. For example, the following command structure:

app rename <name> to <name>

Can be represented with the following:

var CLI struct {
  Rename struct {
    Name struct {
      Name string `arg` // <-- NOTE: identical name to enclosing struct field.
      To struct {
        Name struct {
          Name string `arg`
        } `arg`
      } `cmd`
    } `arg`
  } `cmd`
}

This looks a little verbose in this contrived example, but typically this will not be the case.

Positional arguments

If a field is tagged with arg:"" it will be treated as the final positional value to be parsed on the command line. By default positional arguments are required, but specifying optional:"" will alter this.

If a positional argument is a slice, all remaining arguments will be appended to that slice.

Slices

Slice values are treated specially. First the input is split on the sep:"<rune>" tag (defaults to ,), then each element is parsed by the slice element type and appended to the slice. If the same value is encountered multiple times, elements continue to be appended.

To represent the following command-line:

cmd ls <file> <file> ...

You would use the following:

var CLI struct {
  Ls struct {
    Files []string `arg:"" type:"existingfile"`
  } `cmd`
}

Maps

Maps are similar to slices except that only one key/value pair can be assigned per value, and the sep tag denotes the assignment character and defaults to =.

To represent the following command-line:

cmd config set <key>=<value> <key>=<value> ...

You would use the following:

var CLI struct {
  Config struct {
    Set struct {
      Config map[string]float64 `arg:"" type:"file:"`
    } `cmd`
  } `cmd`
}

For flags, multiple key+value pairs should be separated by mapsep:"rune" tag (defaults to ;) eg. --set="key1=value1;key2=value2".

Pointers

Pointers work like the underlying type, except that you can differentiate between the presence of the zero value and no value being supplied.

For example:

var CLI struct {
	Foo *int
}

Would produce a nil value for Foo if no --foo argument is supplied, but would have a pointer to the value 0 if the argument --foo=0 was supplied.

Nested data structure

Kong support a nested data structure as well with embed:"". You can combine embed:"" with prefix:"":

var CLI struct {
  Logging struct {
    Level string `enum:"debug,info,warn,error" default:"info"`
    Type string `enum:"json,console" default:"console"`
  } `embed:"" prefix:"logging."`
}

This configures Kong to accept flags --logging.level and --logging.type.

Custom named decoders

Kong includes a number of builtin custom type mappers. These can be used by specifying the tag type:"<type>". They are registered with the option function NamedMapper(name, mapper).

Name Description
path A path. ~ expansion is applied. - is accepted for stdout, and will be passed unaltered.
existingfile An existing file. ~ expansion is applied. - is accepted for stdin, and will be passed unaltered.
existingdir An existing directory. ~ expansion is applied.
counter Increment a numeric field. Useful for -vvv. Can accept -s, --long or --long=N.
filecontent Read the file at path into the field. ~ expansion is applied. - is accepted for stdin, and will be passed unaltered.

Slices and maps treat type tags specially. For slices, the type:"" tag specifies the element type. For maps, the tag has the format tag:"[<key>]:[<value>]" where either may be omitted.

Supported field types

Custom decoders (mappers)

Any field implementing encoding.TextUnmarshaler or json.Unmarshaler will use those interfaces for decoding values. Kong also includes builtin support for many common Go types:

Type Description
time.Duration Populated using time.ParseDuration().
time.Time Populated using time.Parse(). Format defaults to RFC3339 but can be overridden with the format:"X" tag.
*os.File Path to a file that will be opened, or - for os.Stdin. File must be closed by the user.
*url.URL Populated with url.Parse().

For more fine-grained control, if a field implements the MapperValue interface it will be used to decode arguments into the field.

Supported tags

Tags can be in two forms:

  1. Standard Go syntax, eg. kong:"required,name='foo'".
  2. Bare tags, eg. required:"" name:"foo"

Both can coexist with standard Tag parsing.

Tag Description
cmd:"" If present, struct is a command.
arg:"" If present, field is an argument. Required by default.
env:"X,Y,..." Specify envars to use for default value. The envs are resolved in the declared order. The first value found is used.
name:"X" Long name, for overriding field name.
help:"X" Help text.
type:"X" Specify named types to use.
placeholder:"X" Placeholder input, if flag. e.g. `placeholder:"<the-placeholder>"` will show --flag-name=<the-placeholder> when displaying help.
default:"X" Default value.
default:"1" On a command, make it the default.
default:"withargs" On a command, make it the default and allow args/flags from that command
short:"X" Short name, if flag.
aliases:"X,Y" One or more aliases (for cmd or flag).
required:"" If present, flag/arg is required.
optional:"" If present, flag/arg is optional.
hidden:"" If present, command or flag is hidden.
negatable:"" If present on a bool field, supports prefixing a flag with --no- to invert the default value
negatable:"X" If present on a bool field, supports --X to invert the default value
format:"X" Format for parsing input, if supported.
sep:"X" Separator for sequences (defaults to ","). May be none to disable splitting.
mapsep:"X" Separator for maps (defaults to ";"). May be none to disable splitting.
enum:"X,Y,..." Set of valid values allowed for this flag. An enum field must be required or have a valid default.
group:"X" Logical group for a flag or command.
xor:"X,Y,..." Exclusive OR groups for flags. Only one flag in the group can be used which is restricted within the same command. When combined with required, at least one of the xor group will be required.
and:"X,Y,..." AND groups for flags. All flags in the group must be used in the same command. When combined with required, all flags in the group will be required.
prefix:"X" Prefix for all sub-flags.
envprefix:"X" Envar prefix for all sub-flags.
set:"K=V" Set a variable for expansion by child elements. Multiples can occur.
embed:"" If present, this field's children will be embedded in the parent. Useful for composition.
passthrough:"<mode>"[^1] If present on a positional argument, it stops flag parsing when encountered, as if -- was processed before. Useful for external command wrappers, like exec. On a command it requires that the command contains only one argument of type []string which is then filled with everything following the command, unparsed.
- Ignore the field. Useful for adding non-CLI fields to a configuration struct. e.g `kong:"-"`

[^1]: <mode> can be partial or all (the default). all will pass through all arguments including flags, including flags. partial will validate flags until the first positional argument is encountered, then pass through all remaining positional arguments.

Plugins

Kong CLI's can be extended by embedding the kong.Plugin type and populating it with pointers to Kong annotated structs. For example:

var pluginOne struct {
  PluginOneFlag string
}
var pluginTwo struct {
  PluginTwoFlag string
}
var cli struct {
  BaseFlag string
  kong.Plugins
}
cli.Plugins = kong.Plugins{&pluginOne, &pluginTwo}

Additionally if an interface type is embedded, it can also be populated with a Kong annotated struct.

Dynamic Commands

While plugins give complete control over extending command-line interfaces, Kong also supports dynamically adding commands via kong.DynamicCommand().

Variable interpolation

Kong supports limited variable interpolation into help strings, enum lists and default values.

Variables are in the form:

${<name>}
${<name>=<default>}

Variables are set with the Vars{"key": "value", ...} option. Undefined variable references in the grammar without a default will result in an error at construction time.

Variables can also be set via the set:"K=V" tag. In this case, those variables will be available for that node and all children. This is useful for composition by allowing the same struct to be reused.

When interpolating into flag or argument help strings, some extra variables are defined from the value itself:

${default}
${enum}

For flags with associated environment variables, the variable ${env} can be interpolated into the help string. In the absence of this variable in the help string, Kong will append ($$${env}) to the help string.

eg.

type cli struct {
  Config string `type:"path" default:"${config_file}"`
}

func main() {
  kong.Parse(&cli,
    kong.Vars{
      "config_file": "~/.app.conf",
    })
}

Validation

Kong does validation on the structure of a command-line, but also supports extensible validation. Any node in the tree may implement either of the following interfaces:

type Validatable interface {
    Validate() error
 }
type Validatable interface {
    Validate(kctx *kong.Context) error
 }

If one of these nodes is in the active command-line it will be called during normal validation.

Modifying Kong's behaviour

Each Kong parser can be configured via functional options passed to New(cli interface{}, options...Option).

The full set of options can be found here.

Name(help) and Description(help) - set the application name description

Set the application name and/or description.

The name of the application will default to the binary name, but can be overridden with Name(name).

As with all help in Kong, text will be wrapped to the terminal.

Configuration(loader, paths...) - load defaults from configuration files

This option provides Kong with support for loading defaults from a set of configuration files. Each file is opened, if possible, and the loader called to create a resolver for that file.

eg.

kong.Parse(&cli, kong.Configuration(kong.JSON, "/etc/myapp.json", "~/.myapp.json"))

See the tests for an example of how the JSON file is structured.

List of Configuration Loaders
Resolver(...) - support for default values from external sources

Resolvers are Kong's extension point for providing default values from external sources. As an example, support for environment variables via the env tag is provided by a resolver. There's also a builtin resolver for JSON configuration files.

Example resolvers can be found in resolver.go.

*Mapper(...) - customising how the command-line is mapped to Go values

Command-line arguments are mapped to Go values via the Mapper interface:

// 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 Mapper interface {
	// Decode ctx.Value with ctx.Scanner into target.
	Decode(ctx *DecodeContext, target reflect.Value) error
}

All builtin Go types (as well as a bunch of useful stdlib types like time.Time) have mappers registered by default. Mappers for custom types can be added using kong.??Mapper(...) options. Mappers are applied to fields in four ways:

  1. NamedMapper(string, Mapper) and using the tag key type:"<name>".
  2. KindMapper(reflect.Kind, Mapper).
  3. TypeMapper(reflect.Type, Mapper).
  4. ValueMapper(interface{}, Mapper), passing in a pointer to a field of the grammar.
ConfigureHelp(HelpOptions) and Help(HelpFunc) - customising help

The default help output is usually sufficient, but if not there are two solutions.

  1. Use ConfigureHelp(HelpOptions) to configure how help is formatted (see HelpOptions for details).
  2. Custom help can be wired into Kong via the Help(HelpFunc) option. The HelpFunc is passed a Context, which contains the parsed context for the current command-line. See the implementation of DefaultHelpPrinter for an example.
  3. Use ValueFormatter(HelpValueFormatter) if you want to just customize the help text that is accompanied by flags and arguments.
  4. Use Groups([]Group) if you want to customize group titles or add a header.
Bind(...) - bind values for callback hooks and Run() methods

See the section on hooks for details.

Other options

The full set of options can be found here.

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyDefaults added in v0.1.17

func ApplyDefaults(target interface{}, options ...Option) error

ApplyDefaults if they are not already set.

func DefaultHelpPrinter

func DefaultHelpPrinter(options HelpOptions, ctx *Context) error

DefaultHelpPrinter is the default HelpPrinter.

func DefaultHelpValueFormatter added in v0.2.3

func DefaultHelpValueFormatter(value *Value) string

DefaultHelpValueFormatter is the default HelpValueFormatter.

func DefaultShortHelpPrinter added in v0.2.16

func DefaultShortHelpPrinter(options HelpOptions, ctx *Context) error

DefaultShortHelpPrinter is the default HelpPrinter for short help on error.

func ExpandPath

func ExpandPath(path string) string

ExpandPath is a helper function to expand a relative or home-relative path to an absolute path.

eg. ~/.someconf -> /home/alec/.someconf

func HasInterpolatedVar added in v0.2.20

func HasInterpolatedVar(s string, v string) bool

HasInterpolatedVar returns true if the variable "v" is interpolated in "s".

func JoinEscaped

func JoinEscaped(s []string, sep rune) string

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

func LineIndenter(prefix string) string

LineIndenter adds line points to every new indent.

func SpaceIndenter

func SpaceIndenter(prefix string) string

SpaceIndenter adds a space indent to the given prefix.

func SplitEscaped

func SplitEscaped(s string, sep rune) (out []string)

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

func TreeIndenter(prefix string) string

TreeIndenter adds line points to every new indent and vertical lines to every layer.

func Visit

func Visit(node Visitable, visitor Visitor) error

Visit all nodes.

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 AfterRun added in v1.4.0

type AfterRun interface {
	// This is not the correct signature - see README for details.
	// AfterRun is called after Run() returns.
	AfterRun(args ...any) error
}

AfterRun is a documentation-only interface describing hooks that run after Run() returns.

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 Argument

type Argument = Node

Argument represents a branching positional argument.

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

type BoolMapper interface {
	Mapper
	IsBool() bool
}

A BoolMapper is a Mapper to a value that is a boolean.

This is used solely for formatting help.

type BoolMapperExt added in v0.8.0

type BoolMapperExt interface {
	Mapper
	IsBoolFromValue(v reflect.Value) bool
}

BoolMapperExt allows a Mapper to dynamically determine if a value is a boolean.

type BoolMapperValue added in v0.8.1

type BoolMapperValue interface {
	MapperValue
	IsBool() bool
}

BoolMapperValue may be implemented by fields in order to provide custom mappings for boolean values.

type ChangeDirFlag added in v0.3.0

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 added in v0.3.0

func (c ChangeDirFlag) Decode(ctx *DecodeContext) error

Decode is used to create a side effect of changing the current working directory.

type Command

type Command = Node

Command represents a command in the CLI.

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

type ConfigurationLoader func(r io.Reader) (Resolver, error)

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 Parse

func Parse(cli interface{}, options ...Option) *Context

Parse constructs a new parser and parses the default command-line.

func Trace

func Trace(k *Kong, args []string) (*Context, error)

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

func (c *Context) AddResolver(resolver Resolver)

AddResolver adds a context-specific resolver.

This is most useful in the BeforeResolve() hook.

func (*Context) Apply

func (c *Context) Apply() (string, error)

Apply traced context to the target grammar.

func (*Context) ApplyDefaults added in v0.1.17

func (c *Context) ApplyDefaults() error

ApplyDefaults if they are not already set.

func (*Context) Bind

func (c *Context) Bind(args ...interface{})

Bind adds bindings to the Context.

func (*Context) BindTo

func (c *Context) BindTo(impl, iface interface{})

BindTo adds a binding to the Context.

This will typically have to be called like so:

BindTo(impl, (*MyInterface)(nil))

func (*Context) BindToProvider added in v0.2.18

func (c *Context) BindToProvider(provider interface{}) error

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) Call added in v0.8.0

func (c *Context) Call(fn any, binds ...interface{}) (out []interface{}, err error)

Call an arbitrary function filling arguments with bound values.

func (*Context) Command

func (c *Context) Command() string

Command returns the full command path.

func (*Context) Empty

func (c *Context) Empty() bool

Empty returns true if there were no arguments provided.

func (*Context) FlagValue

func (c *Context) FlagValue(flag *Flag) interface{}

FlagValue returns the set value of a flag if it was encountered and exists, or its default value.

func (*Context) Flags

func (c *Context) Flags() (flags []*Flag)

Flags returns the accumulated available flags.

func (*Context) PrintUsage

func (c *Context) PrintUsage(summary bool) error

PrintUsage to Kong's stdout.

If summary is true, a summarised version of the help will be output.

func (*Context) Reset added in v0.1.17

func (c *Context) Reset() error

Reset recursively resets values to defaults (as specified in the grammar) or the zero value.

func (*Context) Resolve

func (c *Context) Resolve() error

Resolve walks through the traced path, applying resolvers to any unset flags.

func (*Context) Run

func (c *Context) Run(binds ...interface{}) (err error)

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 added in v0.2.6

func (c *Context) RunNode(node *Node, binds ...interface{}) (err error)

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.

func (*Context) Selected

func (c *Context) Selected() *Node

Selected command or argument.

func (*Context) Validate

func (c *Context) Validate() error

Validate the current context.

func (*Context) Value

func (c *Context) Value(path *Path) reflect.Value

Value returns the value for a particular path element.

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

func (f *Flag) FormatPlaceHolder() string

FormatPlaceHolder formats the placeholder string for a Flag.

func (*Flag) String

func (f *Flag) String() string

type Group added in v0.2.13

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 added in v0.2.13

type Groups map[string]string

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.

func (Groups) Apply added in v0.2.13

func (g Groups) Apply(k *Kong) error

type HelpIndenter

type HelpIndenter func(prefix string) string

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 added in v0.2.3

func (h HelpOptions) Apply(k *Kong) error

Apply options to Kong as a configuration option.

func (*HelpOptions) CommandTree added in v0.2.3

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 added in v0.2.3

type HelpValueFormatter func(value *Value) string

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 Must

func Must(ast interface{}, options ...Option) *Kong

Must creates a new Parser or panics if there is an error.

func New

func New(grammar interface{}, options ...Option) (*Kong, error)

New creates a new Kong parser on grammar.

See the README (https://github.com/alecthomas/kong) for usage instructions.

func (*Kong) Errorf

func (k *Kong) Errorf(format string, args ...interface{}) *Kong

Errorf writes a message to Kong.Stderr with the application name prefixed.

func (*Kong) FatalIfErrorf

func (k *Kong) FatalIfErrorf(err error, args ...interface{})

FatalIfErrorf terminates with an error message if err != nil.

func (*Kong) Fatalf

func (k *Kong) Fatalf(format string, args ...interface{})

Fatalf writes a message to Kong.Stderr with the application name prefixed then exits with a non-zero status.

func (*Kong) LoadConfig

func (k *Kong) LoadConfig(path string) (Resolver, error)

LoadConfig from path using the loader configured via Configuration(loader).

"path" will have ~ and any variables expanded.

func (*Kong) Parse

func (k *Kong) Parse(args []string) (ctx *Context, err error)

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

func (*Kong) Printf

func (k *Kong) Printf(format string, args ...interface{}) *Kong

Printf writes a message to Kong.Stdout with the application name prefixed.

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 added in v0.2.12

type NamedFileContentFlag struct {
	Filename string
	Contents []byte
}

NamedFileContentFlag is a flag value that loads a file's contents and filename into its value.

func (*NamedFileContentFlag) Decode added in v0.2.12

func (f *NamedFileContentFlag) Decode(ctx *DecodeContext) error

type Next

type Next func(err error) error

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

func (n *Node) AllFlags(hide bool) (out [][]*Flag)

AllFlags returns flags from all ancestor branches encountered.

If "hide" is true hidden flags will be omitted.

func (*Node) ClosestGroup added in v0.2.13

func (n *Node) ClosestGroup() *Group

ClosestGroup finds the first non-nil group in this node and its ancestors.

func (*Node) Depth

func (n *Node) Depth() int

Depth of the command from the application root.

func (*Node) Find

func (n *Node) Find(ptr interface{}) *Node

Find a command/argument/flag by pointer to its field.

Returns nil if not found. Panics if ptr is not a pointer.

func (*Node) FlagSummary

func (n *Node) FlagSummary(hide bool) string

FlagSummary for the node.

func (*Node) FullPath

func (n *Node) FullPath() string

FullPath is like Path() but includes the Application root node.

func (*Node) Leaf

func (n *Node) Leaf() bool

Leaf returns true if this Node is a leaf node.

func (*Node) Leaves

func (n *Node) Leaves(hide bool) (out []*Node)

Leaves returns the leaf commands/arguments under Node.

If "hidden" is true hidden leaves will be omitted.

func (*Node) Path

func (n *Node) Path() (out string)

Path through ancestors to this Node.

func (*Node) Summary

func (n *Node) Summary() string

Summary help string for the node (not including application name).

func (*Node) Vars

func (n *Node) Vars() Vars

Vars returns the combined Vars defined by all ancestors of this Node.

type NodeType

type NodeType int

NodeType is an enum representing the type of a Node.

const (
	ApplicationNode NodeType = iota
	CommandNode
	ArgumentNode
)

Node type enumerations.

type Option

type Option interface {
	Apply(k *Kong) error
}

An Option applies optional changes to the Kong application.

func AutoGroup added in v0.5.0

func AutoGroup(format func(parent Visitable, flag *Flag) *Group) Option

AutoGroup automatically assigns groups to flags.

func Bind

func Bind(args ...interface{}) Option

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 BindTo

func BindTo(impl, iface interface{}) Option

BindTo allows binding of implementations to interfaces.

BindTo(impl, (*iface)(nil))

func BindToProvider added in v0.2.3

func BindToProvider(provider interface{}) Option

BindToProvider binds an injected value to a provider function.

The provider function must have the signature:

func() (interface{}, error)

This is useful when the Run() function of different commands require different values that may not all be initialisable from the main() function.

func ClearResolvers

func ClearResolvers() Option

ClearResolvers clears all existing resolvers.

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 added in v0.2.18

func DefaultEnvars(prefix string) Option

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

func Description(description string) Option

Description sets the application description.

func DynamicCommand added in v0.2.17

func DynamicCommand(name, help, group string, cmd interface{}, tags ...string) Option

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 Embed added in v0.8.0

func Embed(strct any, tags ...string) Option

Embed a struct into the root of the CLI.

"strct" must be a pointer to a structure.

func Exit

func Exit(exit func(int)) Option

Exit overrides the function used to terminate. This is useful for testing or interactive use.

func ExplicitGroups added in v0.2.13

func ExplicitGroups(groups []Group) Option

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 added in v0.8.0

func FlagNamer(namer func(fieldName string) string) Option

FlagNamer allows you to override the default kebab-case automated flag name generation.

func Help

func Help(help HelpPrinter) Option

Help printer to use.

func HelpFormatter deprecated added in v0.2.3

func HelpFormatter(helpFormatter HelpValueFormatter) Option

HelpFormatter configures how the help text is formatted.

Deprecated: Use ValueFormatter() instead.

func IgnoreFields added in v0.2.18

func IgnoreFields(regexes ...string) Option

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

func KindMapper(kind reflect.Kind, mapper Mapper) Option

KindMapper registers a mapper to a kind.

func Name

func Name(name string) Option

Name overrides the application name.

func NamedMapper

func NamedMapper(name string, mapper Mapper) Option

NamedMapper registers a mapper to a name.

func NoDefaultHelp

func NoDefaultHelp() Option

NoDefaultHelp disables the default help flags.

func PostBuild added in v0.2.12

func PostBuild(fn func(*Kong) error) Option

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 Resolvers

func Resolvers(resolvers ...Resolver) Option

Resolvers registers flag resolvers.

func ShortHelp added in v0.2.16

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 added in v0.2.16

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

func TypeMapper(typ reflect.Type, mapper Mapper) Option

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 added in v0.2.20

func ValueFormatter(helpFormatter HelpValueFormatter) Option

ValueFormatter configures how the help text is formatted.

func ValueMapper

func ValueMapper(ptr interface{}, mapper Mapper) Option

ValueMapper registers a mapper to a field value.

func Writers

func Writers(stdout, stderr io.Writer) Option

Writers overrides the default writers. Useful for testing or interactive use.

type OptionFunc

type OptionFunc func(k *Kong) error

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 added in v0.6.0

func (p *ParseError) Unwrap() error

Unwrap returns the original cause of the error.

type PassthroughMode added in v1.5.0

type PassthroughMode int

PassthroughMode indicates how parameters are passed through when "passthrough" is set.

const (
	// PassThroughModeNone indicates passthrough mode is disabled.
	PassThroughModeNone PassthroughMode = iota
	// PassThroughModeAll indicates that all parameters, including flags, are passed through. It is the default.
	PassThroughModeAll
	// PassThroughModePartial will validate flags until the first positional argument is encountered, then pass through all remaining positional arguments.
	PassThroughModePartial
)

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.

func (*Path) Node

func (p *Path) Node() *Node

Node returns the Node associated with this Path, or nil if Path is a non-Node.

func (*Path) Visitable added in v0.2.12

func (p *Path) Visitable() Visitable

Visitable returns the Visitable for this path element.

type PlaceHolderProvider added in v0.2.17

type PlaceHolderProvider interface {
	PlaceHolder(flag *Flag) string
}

PlaceHolderProvider can be implemented by mappers to provide custom placeholder text.

type Plugins added in v0.2.12

type Plugins []interface{}

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 NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new (empty) Registry.

func (*Registry) ForNamedType

func (r *Registry) ForNamedType(name string, typ reflect.Type) Mapper

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

func (r *Registry) ForNamedValue(name string, value reflect.Value) Mapper

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

func (r *Registry) ForType(typ reflect.Type) Mapper

ForType finds a mapper from a type, by type, then kind.

Will return nil if a mapper can not be determined.

func (*Registry) ForValue

func (r *Registry) ForValue(value reflect.Value) Mapper

ForValue looks up the Mapper for a reflect.Value.

func (*Registry) RegisterDefaults

func (r *Registry) RegisterDefaults() *Registry

RegisterDefaults registers Mappers for all builtin supported Go types and some common stdlib types.

func (*Registry) RegisterKind

func (r *Registry) RegisterKind(kind reflect.Kind, mapper Mapper) *Registry

RegisterKind registers a Mapper for a reflect.Kind.

func (*Registry) RegisterName

func (r *Registry) RegisterName(name string, mapper Mapper) *Registry

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

func (r *Registry) RegisterType(typ reflect.Type, mapper Mapper) *Registry

RegisterType registers a Mapper for a reflect.Type.

func (*Registry) RegisterValue

func (r *Registry) RegisterValue(ptr interface{}, mapper Mapper) *Registry

RegisterValue registers a Mapper by pointer to the field value.

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) (interface{}, error)
}

A Resolver resolves a Flag value from an external source.

func JSON

func JSON(r io.Reader) (Resolver, error)

JSON returns a Resolver that retrieves values from a JSON source.

Flag names are used as JSON keys indirectly, by tring snake_case and camelCase variants.

type ResolverFunc

type ResolverFunc func(context *Context, parent *Path, flag *Flag) (interface{}, error)

ResolverFunc is a convenience type for non-validating Resolvers.

func (ResolverFunc) Resolve

func (r ResolverFunc) Resolve(context *Context, parent *Path, flag *Flag) (interface{}, error)

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 Scan

func Scan(args ...string) *Scanner

Scan creates a new Scanner from args with untyped tokens.

func ScanAsType added in v0.6.0

func ScanAsType(ttype TokenType, args ...string) *Scanner

ScanAsType creates a new Scanner from args with the given type.

func ScanFromTokens

func ScanFromTokens(tokens ...Token) *Scanner

ScanFromTokens creates a new Scanner from a slice of tokens.

func (*Scanner) Len

func (s *Scanner) Len() int

Len returns the number of input arguments.

func (*Scanner) Peek

func (s *Scanner) Peek() Token

Peek at the next Token or return an EOLToken.

func (*Scanner) Pop

func (s *Scanner) Pop() Token

Pop the front token off the Scanner.

func (*Scanner) PopUntil

func (s *Scanner) PopUntil(predicate func(Token) bool) (values []Token)

PopUntil predicate returns true.

func (*Scanner) PopValue

func (s *Scanner) PopValue(context string) (Token, error)

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 added in v0.1.17

func (s *Scanner) PopValueInto(context string, target interface{}) error

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>"

func (*Scanner) PopWhile

func (s *Scanner) PopWhile(predicate func(Token) bool) (values []Token)

PopWhile predicate returns true.

func (*Scanner) Push

func (s *Scanner) Push(arg interface{}) *Scanner

Push an untyped Token onto the front of the Scanner.

func (*Scanner) PushToken

func (s *Scanner) PushToken(token Token) *Scanner

PushToken pushes a preconstructed Token onto the front of the Scanner.

func (*Scanner) PushTyped

func (s *Scanner) PushTyped(arg interface{}, typ TokenType) *Scanner

PushTyped pushes a typed token onto the front of the Scanner.

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       string
	Passthrough     bool // Deprecated: use PassthroughMode instead.
	PassthroughMode PassthroughMode
	// contains filtered or unexported fields
}

Tag represents the parsed state of Kong tags in a struct field tag.

func (*Tag) Get

func (t *Tag) Get(k string) string

Get returns the value of the given tag.

Note that this will return the empty string if the tag is missing.

func (*Tag) GetAll

func (t *Tag) GetAll(k string) []string

GetAll returns all encountered values for a tag, in the case of multiple occurrences.

func (*Tag) GetBool

func (t *Tag) GetBool(k string) (bool, error)

GetBool returns true if the given tag looks like a boolean truth string.

func (*Tag) GetFloat

func (t *Tag) GetFloat(k string) (float64, error)

GetFloat parses the given tag as a float64.

func (*Tag) GetInt

func (t *Tag) GetInt(k string) (int64, error)

GetInt parses the given tag as an int64.

func (*Tag) GetRune

func (t *Tag) GetRune(k string) (rune, error)

GetRune parses the given tag as a rune.

func (*Tag) GetSep added in v0.2.10

func (t *Tag) GetSep(k string, dflt rune) (rune, error)

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.

func (*Tag) Has

func (t *Tag) Has(k string) bool

Has returns true if the tag contained the given key.

func (*Tag) String added in v0.8.0

func (t *Tag) String() string

type Token

type Token struct {
	Value interface{}
	Type  TokenType
}

Token created by Scanner.

func (Token) InferredType

func (t Token) InferredType() TokenType

InferredType tries to infer the type of a token.

func (Token) IsEOL

func (t Token) IsEOL() bool

IsEOL returns true if this Token is past the end of the line.

func (Token) IsValue

func (t Token) IsValue() bool

IsValue returns true if token is usable as a parseable value.

A parseable value is either a value typed token, or an untyped token NOT starting with a hyphen.

func (Token) String

func (t Token) String() string

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.

func (TokenType) IsAny added in v0.1.17

func (t TokenType) IsAny(types ...TokenType) bool

IsAny returns true if the token's type is any of those provided.

func (TokenType) String

func (t TokenType) String() string

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            // Deprecated: Use PassthroughMode instead. Set to true to stop flag parsing when encountered.
	PassthroughMode PassthroughMode //
	Active          bool            // Denotes the value is part of an active branch in the CLI.
}

A Value is either a flag or a variable positional argument.

func (*Value) Apply

func (v *Value) Apply(value reflect.Value)

Apply value to field.

func (*Value) ApplyDefault added in v0.1.17

func (v *Value) ApplyDefault() error

ApplyDefault value to field if it is not already set.

func (*Value) EnumMap

func (v *Value) EnumMap() map[string]bool

EnumMap returns a map of the enums in this value.

func (*Value) EnumSlice added in v0.5.0

func (v *Value) EnumSlice() []string

EnumSlice returns a slice of the enums in this value.

func (*Value) IsBool

func (v *Value) IsBool() bool

IsBool returns true if the underlying value is a boolean.

func (*Value) IsCounter added in v0.2.17

func (v *Value) IsCounter() bool

IsCounter returns true if the value is a counter.

func (*Value) IsCumulative

func (v *Value) IsCumulative() bool

IsCumulative returns true if the type can be accumulated into.

func (*Value) IsMap

func (v *Value) IsMap() bool

IsMap returns true if the value is a map.

func (*Value) IsSlice

func (v *Value) IsSlice() bool

IsSlice returns true if the value is a slice.

func (*Value) Parse

func (v *Value) Parse(scan *Scanner, target reflect.Value) (err error)

Parse tokens into value, parse, and validate, but do not write to the field.

func (*Value) Reset

func (v *Value) Reset() error

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 added in v0.1.17

func (v *Value) ShortSummary() string

ShortSummary returns a human-readable summary of the value, not including any placeholders/defaults.

func (*Value) Summary

func (v *Value) Summary() string

Summary returns a human-readable summary of the value.

type Vars

type Vars map[string]string

Vars sets the variables to use for interpolation into help strings and default values.

See README for details.

func (Vars) Apply

func (v Vars) Apply(k *Kong) error

Apply lets Vars act as an Option.

func (Vars) CloneWith

func (v Vars) CloneWith(vars Vars) Vars

CloneWith clones the current Vars and merges "vars" onto the clone.

type VarsContributor added in v0.2.18

type VarsContributor interface {
	Vars(ctx *Value) Vars
}

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 added in v0.7.0

func (v VersionFlag) BeforeReset(app *Kong, vars Vars) error

BeforeReset writes the version variable and terminates with a 0 exit status.

type Visitable

type Visitable interface {
	// contains filtered or unexported methods
}

A Visitable component in the model.

type Visitor

type Visitor func(node Visitable, next Next) error

Visitor can be used to walk all nodes in the model.

Directories

Path Synopsis
_examples
docker
nolint
nolint

Jump to

Keyboard shortcuts

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