• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

.circleci/H05-Mar-2020-

_examples/H05-Mar-2020-

.golangci.ymlH A D05-Mar-2020943

COPYINGH A D05-Mar-20201 KiB

README.mdH A D05-Mar-202018.4 KiB

build.goH A D05-Mar-20205.5 KiB

callbacks.goH A D05-Mar-20201.6 KiB

camelcase.goH A D05-Mar-20202.8 KiB

config_test.goH A D05-Mar-20201.1 KiB

context.goH A D05-Mar-202018.9 KiB

defaults.goH A D05-Mar-2020397

defaults_test.goH A D05-Mar-2020728

doc.goH A D05-Mar-2020919

error.goH A D05-Mar-2020291

global.goH A D05-Mar-2020310

global_test.goH A D05-Mar-2020506

go.modH A D05-Mar-2020219

go.sumH A D05-Mar-2020682

guesswidth.goH A D05-Mar-2020148

guesswidth_unix.goH A D05-Mar-2020807

help.goH A D05-Mar-20209.8 KiB

help_test.goH A D05-Mar-20205.9 KiB

hooks.goH A D05-Mar-2020717

interpolate.goH A D05-Mar-2020710

interpolate_test.goH A D05-Mar-2020321

kong.goH A D05-Mar-20209.1 KiB

kong_test.goH A D05-Mar-202019 KiB

levenshtein.goH A D05-Mar-2020778

mapper.goH A D05-Mar-202018.8 KiB

mapper_test.goH A D05-Mar-20206.4 KiB

model.goH A D05-Mar-202010.2 KiB

model_test.goH A D05-Mar-2020522

options.goH A D05-Mar-20206.8 KiB

options_test.goH A D05-Mar-20201.4 KiB

resolver.goH A D05-Mar-20201.4 KiB

resolver_test.goH A D05-Mar-20205.6 KiB

scanner.goH A D05-Mar-20205 KiB

scanner_test.goH A D05-Mar-2020638

tag.goH A D05-Mar-20204.9 KiB

tag_test.goH A D05-Mar-20203.4 KiB

util.goH A D05-Mar-20201 KiB

util_test.goH A D05-Mar-2020890

visit.goH A D05-Mar-20201.2 KiB

README.md

1<!-- markdownlint-disable MD013 MD033 -->
2<p align="center"><img width="90%" src="kong.png" /></p>
3
4# Kong is a command-line parser for Go
5[![](https://godoc.org/github.com/alecthomas/kong?status.svg)](http://godoc.org/github.com/alecthomas/kong) [![CircleCI](https://img.shields.io/circleci/project/github/alecthomas/kong.svg)](https://circleci.com/gh/alecthomas/kong) [![Go Report Card](https://goreportcard.com/badge/github.com/alecthomas/kong)](https://goreportcard.com/report/github.com/alecthomas/kong) [![Slack chat](https://img.shields.io/static/v1?logo=slack&style=flat&label=slack&color=green&message=gophers)](https://gophers.slack.com/messages/CN9DS8YF3)
6
7[TOC levels=2-3 numbered]: # "#### Table of Contents"
8
9#### Table of Contents
101. [Introduction](#introduction)
111. [Help](#help)
121. [Command handling](#command-handling)
13   1. [Switch on the command string](#switch-on-the-command-string)
14   1. [Attach a `Run(...) error` method to each command](#attach-a-run-error-method-to-each-command)
151. [Hooks: BeforeResolve(), BeforeApply(), AfterApply() and the Bind() option](#hooks-beforeresolve-beforeapply-afterapply-and-the-bind-option)
161. [Flags](#flags)
171. [Commands and sub-commands](#commands-and-sub-commands)
181. [Branching positional arguments](#branching-positional-arguments)
191. [Terminating positional arguments](#terminating-positional-arguments)
201. [Slices](#slices)
211. [Maps](#maps)
221. [Custom named decoders](#custom-named-decoders)
231. [Custom decoders (mappers)](#custom-decoders-mappers)
241. [Supported tags](#supported-tags)
251. [Variable interpolation](#variable-interpolation)
261. [Modifying Kong's behaviour](#modifying-kongs-behaviour)
27   1. [`Name(help)` and `Description(help)` - set the application name description](#namehelp-and-descriptionhelp---set-the-application-name-description)
28   1. [`Configuration(loader, paths...)` - load defaults from configuration files](#configurationloader-paths---load-defaults-from-configuration-files)
29   1. [`Resolver(...)` - support for default values from external sources](#resolver---support-for-default-values-from-external-sources)
30   1. [`*Mapper(...)` - customising how the command-line is mapped to Go values](#mapper---customising-how-the-command-line-is-mapped-to-go-values)
31   1. [`ConfigureHelp(HelpOptions)` and `Help(HelpFunc)` - customising help](#configurehelphelpoptions-and-helphelpfunc---customising-help)
32   1. [`Bind(...)` - bind values for callback hooks and Run() methods](#bind---bind-values-for-callback-hooks-and-run-methods)
33   1. [Other options](#other-options)
34
35
36## Introduction
37
38Kong aims to support arbitrarily complex command-line structures with as little developer effort as possible.
39
40To achieve that, command-lines are expressed as Go types, with the structure and tags directing how the command line is mapped onto the struct.
41
42For example, the following command-line:
43
44    shell rm [-f] [-r] <paths> ...
45    shell ls [<paths> ...]
46
47Can be represented by the following command-line structure:
48
49```go
50package main
51
52import "github.com/alecthomas/kong"
53
54var CLI struct {
55  Rm struct {
56    Force     bool `help:"Force removal."`
57    Recursive bool `help:"Recursively remove files."`
58
59    Paths []string `arg name:"path" help:"Paths to remove." type:"path"`
60  } `cmd help:"Remove files."`
61
62  Ls struct {
63    Paths []string `arg optional name:"path" help:"Paths to list." type:"path"`
64  } `cmd help:"List paths."`
65}
66
67func main() {
68  ctx := kong.Parse(&CLI)
69  switch ctx.Command() {
70  case "rm <path>":
71  case "ls":
72  default:
73    panic(ctx.Command())
74  }
75}
76```
77
78## Help
79
80Help is automatically generated. With no other arguments provided, help will display a full summary of all available commands.
81
82eg.
83
84    $ shell --help
85    usage: shell <command>
86
87    A shell-like example app.
88
89    Flags:
90      --help   Show context-sensitive help.
91      --debug  Debug mode.
92
93    Commands:
94      rm <path> ...
95        Remove files.
96
97      ls [<path> ...]
98        List paths.
99
100If a command is provided, the help will show full detail on the command including all available flags.
101
102eg.
103
104    $ shell --help rm
105    usage: shell rm <paths> ...
106
107    Remove files.
108
109    Arguments:
110      <paths> ...  Paths to remove.
111
112    Flags:
113          --debug        Debug mode.
114
115      -f, --force        Force removal.
116      -r, --recursive    Recursively remove files.
117
118For flags with associated environment variables, the variable `${env}` can be
119interpolated into the help string. In the absence of this variable in the help,
120
121
122## Command handling
123
124There are two ways to handle commands in Kong.
125
126### Switch on the command string
127
128When 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:
129
130There's an example of this pattern [here](https://github.com/alecthomas/kong/blob/master/_examples/shell/main.go).
131
132eg.
133
134```go
135package main
136
137import "github.com/alecthomas/kong"
138
139var CLI struct {
140  Rm struct {
141    Force     bool `help:"Force removal."`
142    Recursive bool `help:"Recursively remove files."`
143
144    Paths []string `arg name:"path" help:"Paths to remove." type:"path"`
145  } `cmd help:"Remove files."`
146
147  Ls struct {
148    Paths []string `arg optional name:"path" help:"Paths to list." type:"path"`
149  } `cmd help:"List paths."`
150}
151
152func main() {
153  ctx := kong.Parse(&CLI)
154  switch ctx.Command() {
155  case "rm <path>":
156  case "ls":
157  default:
158    panic(ctx.Command())
159  }
160}
161```
162
163This 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.
164
165### Attach a `Run(...) error` method to each command
166
167A more robust approach is to break each command out into their own structs:
168
1691. Break leaf commands out into separate structs.
1702. Attach a `Run(...) error` method to all leaf commands.
1713. Call `kong.Kong.Parse()` to obtain a `kong.Context`.
1724. Call `kong.Context.Run(bindings...)` to call the selected parsed command.
173
174Once a command node is selected by Kong it will search from that node back to the root. Each
175encountered command node with a `Run(...) error` will be called in reverse order. This allows
176sub-trees to be re-used fairly conveniently.
177
178In addition to values bound with the `kong.Bind(...)` option, any values
179passed through to `kong.Context.Run(...)` are also bindable to the target's
180`Run()` arguments.
181
182Finally, hooks can also contribute bindings via `kong.Context.Bind()` and `kong.Context.BindTo()`.
183
184There's a full example emulating part of the Docker CLI [here](https://github.com/alecthomas/kong/tree/master/_examples/docker).
185
186eg.
187
188```go
189type Context struct {
190  Debug bool
191}
192
193type RmCmd struct {
194  Force     bool `help:"Force removal."`
195  Recursive bool `help:"Recursively remove files."`
196
197  Paths []string `arg name:"path" help:"Paths to remove." type:"path"`
198}
199
200func (r *RmCmd) Run(ctx *Context) error {
201  fmt.Println("rm", r.Paths)
202  return nil
203}
204
205type LsCmd struct {
206  Paths []string `arg optional name:"path" help:"Paths to list." type:"path"`
207}
208
209func (l *LsCmd) Run(ctx *Context) error {
210  fmt.Println("ls", l.Paths)
211  return nil
212}
213
214var cli struct {
215  Debug bool `help:"Enable debug mode."`
216
217  Rm RmCmd `cmd help:"Remove files."`
218  Ls LsCmd `cmd help:"List paths."`
219}
220
221func main() {
222  ctx := kong.Parse(&cli)
223  // Call the Run() method of the selected parsed command.
224  err := ctx.Run(&Context{Debug: cli.Debug})
225  ctx.FatalIfErrorf(err)
226}
227
228```
229
230## Hooks: BeforeResolve(), BeforeApply(), AfterApply() and the Bind() option
231
232If 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.
233
234The `--help` flag is implemented with a `BeforeApply` hook.
235
236Arguments 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()`.
237
238eg.
239
240```go
241// A flag with a hook that, if triggered, will set the debug loggers output to stdout.
242type debugFlag bool
243
244func (d debugFlag) BeforeApply(logger *log.Logger) error {
245  logger.SetOutput(os.Stdout)
246  return nil
247}
248
249var cli struct {
250  Debug debugFlag `help:"Enable debug logging."`
251}
252
253func main() {
254  // Debug logger going to discard.
255  logger := log.New(ioutil.Discard, "", log.LstdFlags)
256
257  ctx := kong.Parse(&cli, kong.Bind(logger))
258
259  // ...
260}
261```
262
263## Flags
264
265Any [mapped](#mapper---customising-how-the-command-line-is-mapped-to-go-values) field in the command structure *not* tagged with `cmd` or `arg` will be a flag. Flags are optional by default.
266
267eg. The command-line `app [--flag="foo"]` can be represented by the following.
268
269```go
270type CLI struct {
271  Flag string
272}
273```
274
275## Commands and sub-commands
276
277Sub-commands are specified by tagging a struct field with `cmd`. Kong supports arbitrarily nested commands.
278
279eg. The following struct represents the CLI structure `command [--flag="str"] sub-command`.
280
281```go
282type CLI struct {
283  Command struct {
284    Flag string
285
286    SubCommand struct {
287    } `cmd`
288  } `cmd`
289}
290```
291
292If a sub-command is tagged with `default:"1"` it will be selected if there are no further arguments.
293
294## Branching positional arguments
295
296In addition to sub-commands, structs can also be configured as branching positional arguments.
297
298This is achieved by tagging an [unmapped](#mapper---customising-how-the-command-line-is-mapped-to-go-values) nested struct field with `arg`, then including a positional argument field inside that struct _with the same name_. For example, the following command structure:
299
300    app rename <name> to <name>
301
302Can be represented with the following:
303
304```go
305var CLI struct {
306  Rename struct {
307    Name struct {
308      Name string `arg` // <-- NOTE: identical name to enclosing struct field.
309      To struct {
310        Name struct {
311          Name string `arg`
312        } `arg`
313      } `cmd`
314    } `arg`
315  } `cmd`
316}
317```
318
319This looks a little verbose in this contrived example, but typically this will not be the case.
320
321## Terminating positional arguments
322
323If a [mapped type](#mapper---customising-how-the-command-line-is-mapped-to-go-values) is tagged with `arg` it will be treated as the final positional values to be parsed on the command line.
324
325If a positional argument is a slice, all remaining arguments will be appended to that slice.
326
327## Slices
328
329Slice 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.
330
331To represent the following command-line:
332
333    cmd ls <file> <file> ...
334
335You would use the following:
336
337```go
338var CLI struct {
339  Ls struct {
340    Files []string `arg type:"existingfile"`
341  } `cmd`
342}
343```
344
345## Maps
346
347Maps 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 `=`.
348
349To represent the following command-line:
350
351    cmd config set <key>=<value> <key>=<value> ...
352
353You would use the following:
354
355```go
356var CLI struct {
357  Config struct {
358    Set struct {
359      Config map[string]float64 `arg type:"file:"`
360    } `cmd`
361  } `cmd`
362}
363```
364
365For flags, multiple key+value pairs should be separated by `mapsep:"rune"` tag (defaults to `;`) eg. `--set="key1=value1;key2=value2"`.
366
367## Custom named decoders
368
369Kong includes a number of builtin custom type mappers. These can be used by
370specifying the tag `type:"<type>"`. They are registered with the option
371function `NamedMapper(name, mapper)`.
372
373| Name              | Description                                       |
374|-------------------|---------------------------------------------------|
375| `path`            | A path. ~ expansion is applied.                   |
376| `existingfile`    | An existing file. ~ expansion is applied.         |
377| `existingdir`     | An existing directory. ~ expansion is applied.    |
378| `counter`         | Increment a numeric field. Useful for `-vvv`      |
379
380
381Slices and maps treat type tags specially. For slices, the `type:""` tag
382specifies the element type. For maps, the tag has the format
383`tag:"[<key>]:[<value>]"` where either may be omitted.
384
385
386## Custom decoders (mappers)
387
388Any field implementing `encoding.TextUnmarshaler` or `json.Unmarshaler` will use those interfaces
389for decoding values.
390
391For more fine-grained control, if a field implements the
392[MapperValue](https://godoc.org/github.com/alecthomas/kong#MapperValue)
393interface it will be used to decode arguments into the field.
394
395## Supported tags
396
397Tags can be in two forms:
398
3991. Standard Go syntax, eg. `kong:"required,name='foo'"`.
4002. Bare tags, eg. `required name:"foo"`
401
402Both can coexist with standard Tag parsing.
403
404Tag                    | Description
405-----------------------| -------------------------------------------
406`cmd`                  | If present, struct is a command.
407`arg`                  | If present, field is an argument.
408`env:"X"`              | Specify envar to use for default value.
409`name:"X"`             | Long name, for overriding field name.
410`help:"X"`             | Help text.
411`type:"X"`             | Specify [named types](#custom-named-decoders) to use.
412`placeholder:"X"`      | Placeholder text.
413`default:"X"`          | Default value.
414`default:"1"`          | On a command, make it the default.
415`short:"X"`            | Short name, if flag.
416`required`             | If present, flag/arg is required.
417`optional`             | If present, flag/arg is optional.
418`hidden`               | If present, command or flag is hidden.
419`format:"X"`           | Format for parsing input, if supported.
420`sep:"X"`              | Separator for sequences (defaults to ","). May be `none` to disable splitting.
421`mapsep:"X"`           | Separator for maps (defaults to ";"). May be `none` to disable splitting.
422`enum:"X,Y,..."`       | Set of valid values allowed for this flag.
423`group:"X"`            | Logical group for a flag or command.
424`xor:"X"`              | Exclusive OR group for flags. Only one flag in the group can be used which is restricted within the same command.
425`prefix:"X"`           | Prefix for all sub-flags.
426`set:"K=V"`            | Set a variable for expansion by child elements. Multiples can occur.
427`embed`                | If present, this field's children will be embedded in the parent. Useful for composition.
428
429## Variable interpolation
430
431Kong supports limited variable interpolation into help strings, enum lists and
432default values.
433
434Variables are in the form:
435
436    ${<name>}
437    ${<name>=<default>}
438
439Variables are set with the `Vars{"key": "value", ...}` option. Undefined
440variable references in the grammar without a default will result in an error at
441construction time.
442
443Variables can also be set via the `set:"K=V"` tag. In this case, those variables will be available for that
444node and all children. This is useful for composition by allowing the same struct to be reused.
445
446When interpolating into flag or argument help strings, some extra variables
447are defined from the value itself:
448
449    ${default}
450    ${enum}
451
452eg.
453
454```go
455type cli struct {
456  Config string `type:"path" default:"${config_file}"`
457}
458
459func main() {
460  kong.Parse(&cli,
461    kong.Vars{
462      "config_file": "~/.app.conf",
463    })
464}
465```
466
467## Modifying Kong's behaviour
468
469Each Kong parser can be configured via functional options passed to `New(cli interface{}, options...Option)`.
470
471The full set of options can be found [here](https://godoc.org/github.com/alecthomas/kong#Option).
472
473### `Name(help)` and `Description(help)` - set the application name description
474
475Set the application name and/or description.
476
477The name of the application will default to the binary name, but can be overridden with `Name(name)`.
478
479As with all help in Kong, text will be wrapped to the terminal.
480
481### `Configuration(loader, paths...)` - load defaults from configuration files
482
483This 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.
484
485eg.
486
487```go
488kong.Parse(&cli, kong.Configuration(kong.JSON, "/etc/myapp.json", "~/.myapp.json"))
489```
490
491[See the tests](https://github.com/alecthomas/kong/blob/master/resolver_test.go#L103) for an example of how the JSON file is structured.
492
493### `Resolver(...)` - support for default values from external sources
494
495Resolvers 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.
496
497Example resolvers can be found in [resolver.go](https://github.com/alecthomas/kong/blob/master/resolver.go).
498
499### `*Mapper(...)` - customising how the command-line is mapped to Go values
500
501Command-line arguments are mapped to Go values via the Mapper interface:
502
503```go
504// A Mapper knows how to map command-line input to Go.
505type Mapper interface {
506  // Decode scan into target.
507  //
508  // "ctx" contains context about the value being decoded that may be useful
509  // to some mapperss.
510  Decode(ctx *MapperContext, scan *Scanner, target reflect.Value) error
511}
512```
513
514All 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:
515
5161. `NamedMapper(string, Mapper)` and using the tag key `type:"<name>"`.
5172. `KindMapper(reflect.Kind, Mapper)`.
5183. `TypeMapper(reflect.Type, Mapper)`.
5194. `ValueMapper(interface{}, Mapper)`, passing in a pointer to a field of the grammar.
520
521### `ConfigureHelp(HelpOptions)` and `Help(HelpFunc)` - customising help
522
523The default help output is usually sufficient, but if not there are two solutions.
524
5251. Use `ConfigureHelp(HelpOptions)` to configure how help is formatted (see [HelpOptions](https://godoc.org/github.com/alecthomas/kong#HelpOptions) for details).
5262. 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.
5273. Use `HelpFormatter(HelpValueFormatter)` if you want to just customize the help text that is accompanied by flags and arguments.
528
529### `Bind(...)` - bind values for callback hooks and Run() methods
530
531See the [section on hooks](#hooks-beforeresolve-beforeapply-afterapply-and-the-bind-option) for details.
532
533### Other options
534
535The full set of options can be found [here](https://godoc.org/github.com/alecthomas/kong#Option).
536