All Projects → alecthomas → Kong

alecthomas / Kong

Licence: mit
Kong is a command-line parser for Go

Programming Languages

go
31211 projects - #10 most used programming language
golang
3204 projects

Projects that are alternatives of or similar to Kong

Mri
Quickly scan for CLI flags and arguments
Stars: ✭ 394 (-18.09%)
Mutual labels:  command-line, parser, flags
Argumentum
C++ command line parsing library
Stars: ✭ 92 (-80.87%)
Mutual labels:  command-line, parser
Fast Xml Parser
Validate XML, Parse XML to JS/JSON and vise versa, or parse XML to Nimn rapidly without C/C++ based libraries and no callback
Stars: ✭ 1,021 (+112.27%)
Mutual labels:  command-line, parser
Typin
Declarative framework for interactive CLI applications
Stars: ✭ 126 (-73.8%)
Mutual labels:  command-line, parser
Jkt
Simple helper to parse JSON based on independent schema
Stars: ✭ 22 (-95.43%)
Mutual labels:  struct, parser
Git Labelmaker
🎏 Manage your GitHub labels from the command line!
Stars: ✭ 534 (+11.02%)
Mutual labels:  command-line, tags
Spectre.cli
An extremely opinionated command-line parser.
Stars: ✭ 121 (-74.84%)
Mutual labels:  command-line, parser
Protoc Gen Gotag
Add custom struct tags to protobuf generated structs
Stars: ✭ 97 (-79.83%)
Mutual labels:  struct, tags
Command Line Api
Command line parsing, invocation, and rendering of terminal output.
Stars: ✭ 2,418 (+402.7%)
Mutual labels:  command-line, parser
fastHistory
A python tool connected to your terminal to store important commands, search them in a fast way and automatically paste them into your terminal
Stars: ✭ 24 (-95.01%)
Mutual labels:  tags, flags
argum
Parse incoming arguments in to structure
Stars: ✭ 18 (-96.26%)
Mutual labels:  struct, flags
Atldotnet
Fully managed, portable and easy-to-use C# library to read and edit audio data and metadata (tags) from various audio formats, playlists and CUE sheets
Stars: ✭ 180 (-62.58%)
Mutual labels:  parser, tags
Flap
Fortran command Line Arguments Parser for poor people
Stars: ✭ 109 (-77.34%)
Mutual labels:  command-line, parser
Entrypoint
Composable CLI Argument Parser for all modern .Net platforms.
Stars: ✭ 136 (-71.73%)
Mutual labels:  command-line, parser
Picocli
Picocli is a modern framework for building powerful, user-friendly, GraalVM-enabled command line apps with ease. It supports colors, autocompletion, subcommands, and more. In 1 source file so apps can include as source & avoid adding a dependency. Written in Java, usable from Groovy, Kotlin, Scala, etc.
Stars: ✭ 3,286 (+583.16%)
Mutual labels:  command-line, parser
Args
Toolkit for building command line interfaces
Stars: ✭ 399 (-17.05%)
Mutual labels:  command-line, flags
Minigo
minigo🐥is a small Go compiler made from scratch. It can compile itself.
Stars: ✭ 456 (-5.2%)
Mutual labels:  parser
Instainsane
Multi-threaded Instagram Brute Forcer (100 attemps at once)
Stars: ✭ 475 (-1.25%)
Mutual labels:  command-line
Form
🚂 Decodes url.Values into Go value(s) and Encodes Go value(s) into url.Values. Dual Array and Full map support.
Stars: ✭ 454 (-5.61%)
Mutual labels:  parser
2048.c
Console version of the game "2048" for GNU/Linux
Stars: ✭ 453 (-5.82%)
Mutual labels:  command-line

Kong is a command-line parser for Go

CircleCI Go Report Card Slack chat

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, argument, or flag type implementing the interface Help() string will have this function called to retrieve the help string. This allows for much more descriptive text than can fit in Go tags.

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: BeforeResolve(), BeforeApply(), AfterApply() and the Bind() option

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

The --help flag is implemented with a BeforeApply 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(ioutil.Discard, "", log.LstdFlags)

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

  // ...
}

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.

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.

Terminating positional arguments

If a mapped type is tagged with arg it will be treated as the final positional values to be parsed on the command line.

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

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.

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.
env:"X" Specify envar to use for default value.
name:"X" Long name, for overriding field name.
help:"X" Help text.
type:"X" Specify named types to use.
placeholder:"X" Placeholder text.
default:"X" Default value.
default:"1" On a command, make it the default.
short:"X" Short name, if flag.
aliases:"X,Y" One or more aliases (for cmd).
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
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.
group:"X" Logical group for a flag or command.
xor:"X" Exclusive OR group for flags. Only one flag in the group can be used which is restricted within the same command.
prefix:"X" 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.
- Ignore the field. Useful for adding non-CLI fields to a configuration struct.

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.

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 the following interface:

type Validatable interface {
    Validate() 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.

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 knows how to map command-line input to Go.
type Mapper interface {
  // Decode scan into target.
  //
  // "ctx" contains context about the value being decoded that may be useful
  // to some mappers.
  Decode(ctx *MapperContext, scan *Scanner, 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 PrintHelp for an example.
  3. Use HelpFormatter(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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].