kong – github.com/alecthomas/kong Index | Files | Directories

package kong

import "github.com/alecthomas/kong"

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

Functions

func DefaultHelpPrinter

func DefaultHelpPrinter(options HelpOptions, ctx *Context) error

DefaultHelpPrinter is the default HelpPrinter.

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

Types

type AfterApply

type AfterApply interface {
	// This is not the correct signature - see README for details.
	AfterApply(args ...interface{}) 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 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 ...interface{}) 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 ...interface{}) error
}

BeforeResolve is a documentation-only interface describing hooks that run before values are set.

type BoolMapper

type BoolMapper interface {
	IsBool() bool
}

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

This is used solely for formatting help.

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 ConfigurationFunc

type ConfigurationFunc func(r io.Reader) (ResolverFunc, error)

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

Call Resolve() after this, then finally Apply() to write parsed values into the target grammar.

func (*Context) AddResolver

func (c *Context) AddResolver(resolver ResolverFunc)

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

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

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 Error

type Error struct {
	// contains filtered or unexported fields
}

Error reported by Kong.

func (Error) Error

func (e Error) Error() string

type Flag

type Flag struct {
	*Value
	Group       string // Logical grouping when displaying. May also be used by configuration loaders to group options logically.
	PlaceHolder string
	Env         string
	Short       rune
	Hidden      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 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
}

HelpOptions for HelpPrinters.

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 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) (ResolverFunc, error)

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

"path" will have ~/ 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 this 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.

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      string
	Hidden     bool
	Flags      []*Flag
	Positional []*Positional
	Children   []*Node
	Target     reflect.Value // Pointer to the value in the grammar that this Node is associated with.
	Tag        *Tag

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

type OptionFunc

type OptionFunc func(k *Kong) error

OptionFunc is function that adheres to the Option interface.

func Bind

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

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{}) OptionFunc

BindTo allows binding of implementations to interfaces.

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

func ClearResolvers

func ClearResolvers() OptionFunc

ClearResolvers clears all existing resolvers.

func Configuration

func Configuration(loader ConfigurationFunc, paths ...string) OptionFunc

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 ResolverFunc which is registered with Kong.

Note: The JSON function is a ConfigurationFunc.

~ expansion will occur on the provided paths.

func ConfigureHelp

func ConfigureHelp(options HelpOptions) OptionFunc

ConfigureHelp sets the HelpOptions to use for printing help.

func Description

func Description(description string) OptionFunc

Description sets the application description.

func Exit

func Exit(exit func(int)) OptionFunc

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

func Help

func Help(help HelpPrinter) OptionFunc

Help printer to use.

func KindMapper

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

KindMapper registers a mapper to a kind.

func Name

func Name(name string) OptionFunc

Name overrides the application name.

func NamedMapper

func NamedMapper(name string, mapper Mapper) OptionFunc

NamedMapper registers a mapper to a name.

func NoDefaultHelp

func NoDefaultHelp() OptionFunc

NoDefaultHelp disables the default help flags.

func Resolver

func Resolver(resolvers ...ResolverFunc) OptionFunc

Resolver registers flag resolvers.

func TypeMapper

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

TypeMapper registers a mapper to a type.

func UsageOnError

func UsageOnError() OptionFunc

UsageOnError configures Kong to display context-sensitive usage if FatalIfErrorf is called with an error.

func ValueMapper

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

ValueMapper registers a mapper to a field value.

func Writers

func Writers(stdout, stderr io.Writer) OptionFunc

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

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

func (p *ParseError) Cause() error

Cause returns the original cause of the error.

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.

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 ResolverFunc

type ResolverFunc func(context *Context, parent *Path, flag *Flag) (string, error)

ResolverFunc resolves a Flag value from an external source.

func Envars

func Envars() ResolverFunc

Envars resolves flag values using the `env:"<name>"` tag. It ignores flags without this tag.

This resolver is installed by default.

func JSON

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

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

Hyphens in flag names are replaced with underscores.

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

PopValue token, or panic with 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 string) *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 string, 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
	Default     string
	Format      string
	PlaceHolder string
	Env         string
	Short       rune
	Hidden      bool
	Sep         rune
	Enum        string
	Group       string
	Vars        Vars
	Prefix      string // Optional prefix on anonymous structs. All sub-flags will have this prefix.
	// 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) Has

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

Has returns true if the tag contained the given key.

type Token

type Token struct {
	Value string
	Type  TokenType
}

Token created by Scanner.

func (Token) IsAny

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

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

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

func (i TokenType) String() string

type Value

type Value struct {
	Flag     *Flag // Nil if positional argument.
	Name     string
	Help     string
	Default  string
	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).
}

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

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

EnumMap returns a map 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) 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) 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 "default" tag.

Does not include resolvers.

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

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

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

Source Files

build.go callbacks.go camelcase.go context.go doc.go error.go global.go guesswidth.go help.go hooks.go interpolate.go kong.go levenshtein.go mapper.go model.go options.go resolver.go scanner.go tag.go tokentype_string.go util.go

Directories

PathSynopsis
_examples
_examples/dockernolint
_examples/servernolint: govet
_examples/shell
Version
v0.1.5
Published
Sep 19, 2018
Platform
js/wasm
Imports
17 packages
Last checked
now

Tools for package owners.