{"id":13411143,"url":"https://github.com/alecthomas/kong","last_synced_at":"2025-05-13T20:02:26.070Z","repository":{"id":38421851,"uuid":"128887107","full_name":"alecthomas/kong","owner":"alecthomas","description":"Kong is a command-line parser for Go","archived":false,"fork":false,"pushed_at":"2025-05-05T03:35:55.000Z","size":902,"stargazers_count":2608,"open_issues_count":32,"forks_count":146,"subscribers_count":19,"default_branch":"master","last_synced_at":"2025-05-06T19:51:58.157Z","etag":null,"topics":["command-line","commands","flags","go","golang","parser","struct","tags"],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/alecthomas.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"COPYING","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":["alecthomas"]}},"created_at":"2018-04-10T06:50:32.000Z","updated_at":"2025-05-05T21:00:11.000Z","dependencies_parsed_at":"2023-11-13T07:24:17.401Z","dependency_job_id":"ca438d72-3919-4d7b-9f83-98dc453b1255","html_url":"https://github.com/alecthomas/kong","commit_stats":{"total_commits":409,"total_committers":76,"mean_commits":5.381578947368421,"dds":0.3863080684596577,"last_synced_commit":"565ae9b740578e038691242cb239aaa1206e698c"},"previous_names":[],"tags_count":67,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alecthomas%2Fkong","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alecthomas%2Fkong/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alecthomas%2Fkong/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alecthomas%2Fkong/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/alecthomas","download_url":"https://codeload.github.com/alecthomas/kong/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254020468,"owners_count":22000749,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["command-line","commands","flags","go","golang","parser","struct","tags"],"created_at":"2024-07-30T20:01:11.703Z","updated_at":"2025-05-13T20:02:25.995Z","avatar_url":"https://github.com/alecthomas.png","language":"Go","readme":"\u003c!-- markdownlint-disable MD013 MD033 --\u003e\n\u003cp align=\"center\"\u003e\u003cimg width=\"90%\" src=\"kong.png\" /\u003e\u003c/p\u003e\n\n# Kong is a command-line parser for Go\n\n[![](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\u0026style=flat\u0026label=slack\u0026color=green\u0026message=gophers)](https://gophers.slack.com/messages/CN9DS8YF3)\n\n- [Version 1.0.0 Release](#version-100-release)\n- [Introduction](#introduction)\n- [Help](#help)\n  - [Help as a user of a Kong application](#help-as-a-user-of-a-kong-application)\n  - [Defining help in Kong](#defining-help-in-kong)\n- [Command handling](#command-handling)\n  - [Switch on the command string](#switch-on-the-command-string)\n  - [Attach a `Run(...) error` method to each command](#attach-a-run-error-method-to-each-command)\n- [Hooks: BeforeReset(), BeforeResolve(), BeforeApply(), AfterApply()](#hooks-beforereset-beforeresolve-beforeapply-afterapply)\n- [The Bind() option](#the-bind-option)\n- [Flags](#flags)\n- [Commands and sub-commands](#commands-and-sub-commands)\n- [Branching positional arguments](#branching-positional-arguments)\n- [Positional arguments](#positional-arguments)\n- [Slices](#slices)\n- [Maps](#maps)\n- [Pointers](#pointers)\n- [Nested data structure](#nested-data-structure)\n- [Custom named decoders](#custom-named-decoders)\n- [Supported field types](#supported-field-types)\n- [Custom decoders (mappers)](#custom-decoders-mappers)\n- [Supported tags](#supported-tags)\n- [Plugins](#plugins)\n- [Dynamic Commands](#dynamic-commands)\n- [Variable interpolation](#variable-interpolation)\n- [Validation](#validation)\n- [Modifying Kong's behaviour](#modifying-kongs-behaviour)\n  - [`Name(help)` and `Description(help)` - set the application name description](#namehelp-and-descriptionhelp---set-the-application-name-description)\n  - [`Configuration(loader, paths...)` - load defaults from configuration files](#configurationloader-paths---load-defaults-from-configuration-files)\n  - [`Resolver(...)` - support for default values from external sources](#resolver---support-for-default-values-from-external-sources)\n  - [`*Mapper(...)` - customising how the command-line is mapped to Go values](#mapper---customising-how-the-command-line-is-mapped-to-go-values)\n  - [`ConfigureHelp(HelpOptions)` and `Help(HelpFunc)` - customising help](#configurehelphelpoptions-and-helphelpfunc---customising-help)\n  - [Injecting values into `Run()` methods](#injecting-values-into-run-methods)\n  - [Other options](#other-options)\n\n## Version 1.0.0 Release\n\nKong has been stable for a long time, so it seemed appropriate to cut a 1.0 release.\n\nThere is one breaking change, [#436](https://github.com/alecthomas/kong/pull/436), which should effect relatively few users.\n\n## Introduction\n\nKong aims to support arbitrarily complex command-line structures with as little developer effort as possible.\n\nTo achieve that, command-lines are expressed as Go types, with the structure and tags directing how the command line is mapped onto the struct.\n\nFor example, the following command-line:\n\n    shell rm [-f] [-r] \u003cpaths\u003e ...\n    shell ls [\u003cpaths\u003e ...]\n\nCan be represented by the following command-line structure:\n\n```go\npackage main\n\nimport \"github.com/alecthomas/kong\"\n\nvar CLI struct {\n  Rm struct {\n    Force     bool `help:\"Force removal.\"`\n    Recursive bool `help:\"Recursively remove files.\"`\n\n    Paths []string `arg:\"\" name:\"path\" help:\"Paths to remove.\" type:\"path\"`\n  } `cmd:\"\" help:\"Remove files.\"`\n\n  Ls struct {\n    Paths []string `arg:\"\" optional:\"\" name:\"path\" help:\"Paths to list.\" type:\"path\"`\n  } `cmd:\"\" help:\"List paths.\"`\n}\n\nfunc main() {\n  ctx := kong.Parse(\u0026CLI)\n  switch ctx.Command() {\n  case \"rm \u003cpath\u003e\":\n  case \"ls\":\n  default:\n    panic(ctx.Command())\n  }\n}\n```\n\n## Help\n\n### Help as a user of a Kong application\n\nEvery Kong application includes a `--help` flag that will display auto-generated help.\n\neg.\n\n    $ shell --help\n    usage: shell \u003ccommand\u003e\n\n    A shell-like example app.\n\n    Flags:\n      --help   Show context-sensitive help.\n      --debug  Debug mode.\n\n    Commands:\n      rm \u003cpath\u003e ...\n        Remove files.\n\n      ls [\u003cpath\u003e ...]\n        List paths.\n\nIf a command is provided, the help will show full detail on the command including all available flags.\n\neg.\n\n    $ shell --help rm\n    usage: shell rm \u003cpaths\u003e ...\n\n    Remove files.\n\n    Arguments:\n      \u003cpaths\u003e ...  Paths to remove.\n\n    Flags:\n          --debug        Debug mode.\n\n      -f, --force        Force removal.\n      -r, --recursive    Recursively remove files.\n\n### Defining help in Kong\n\nHelp is automatically generated from the command-line structure itself,\nincluding `help:\"\"` and other tags. [Variables](#variable-interpolation) will\nalso be interpolated into the help string.\n\nFinally, any command, or argument type implementing the interface\n`Help() string` will have this function called to retrieve more detail to\naugment the help tag. This allows for much more descriptive text than can\nfit in Go tags. [See \\_examples/shell/help](./_examples/shell/help)\n\n#### Showing the _command_'s detailed help\n\nA command's additional help text is _not_ shown from top-level help, but can be displayed within contextual help:\n\n**Top level help**\n\n```bash\n $ go run ./_examples/shell/help --help\nUsage: help \u003ccommand\u003e\n\nAn app demonstrating HelpProviders\n\nFlags:\n  -h, --help    Show context-sensitive help.\n      --flag    Regular flag help\n\nCommands:\n  echo    Regular command help\n```\n\n**Contextual**\n\n```bash\n $ go run ./_examples/shell/help echo --help\nUsage: help echo \u003cmsg\u003e\n\nRegular command help\n\n🚀 additional command help\n\nArguments:\n  \u003cmsg\u003e    Regular argument help\n\nFlags:\n  -h, --help    Show context-sensitive help.\n      --flag    Regular flag help\n```\n\n#### Showing an _argument_'s detailed help\n\nCustom 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](#branching-positional-arguments))\n\n**Contextual argument help**\n\n```bash\n $ go run ./_examples/shell/help msg --help\nUsage: help echo \u003cmsg\u003e\n\nRegular argument help\n\n📣 additional argument help\n\nFlags:\n  -h, --help    Show context-sensitive help.\n      --flag    Regular flag help\n```\n\n## Command handling\n\nThere are two ways to handle commands in Kong.\n\n### Switch on the command string\n\nWhen 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:\n\nThere's an example of this pattern [here](https://github.com/alecthomas/kong/blob/master/_examples/shell/commandstring/main.go).\n\neg.\n\n```go\npackage main\n\nimport \"github.com/alecthomas/kong\"\n\nvar CLI struct {\n  Rm struct {\n    Force     bool `help:\"Force removal.\"`\n    Recursive bool `help:\"Recursively remove files.\"`\n\n    Paths []string `arg:\"\" name:\"path\" help:\"Paths to remove.\" type:\"path\"`\n  } `cmd:\"\" help:\"Remove files.\"`\n\n  Ls struct {\n    Paths []string `arg:\"\" optional:\"\" name:\"path\" help:\"Paths to list.\" type:\"path\"`\n  } `cmd:\"\" help:\"List paths.\"`\n}\n\nfunc main() {\n  ctx := kong.Parse(\u0026CLI)\n  switch ctx.Command() {\n  case \"rm \u003cpath\u003e\":\n  case \"ls\":\n  default:\n    panic(ctx.Command())\n  }\n}\n```\n\nThis 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.\n\n### Attach a `Run(...) error` method to each command\n\nA more robust approach is to break each command out into their own structs:\n\n1. Break leaf commands out into separate structs.\n2. Attach a `Run(...) error` method to all leaf commands.\n3. Call `kong.Kong.Parse()` to obtain a `kong.Context`.\n4. Call `kong.Context.Run(bindings...)` to call the selected parsed command.\n\nOnce a command node is selected by Kong it will search from that node back to the root. Each\nencountered command node with a `Run(...) error` will be called in reverse order. This allows\nsub-trees to be re-used fairly conveniently.\n\nIn addition to values bound with the `kong.Bind(...)` option, any values\npassed through to `kong.Context.Run(...)` are also bindable to the target's\n`Run()` arguments.\n\nFinally, hooks can also contribute bindings via `kong.Context.Bind()` and `kong.Context.BindTo()`.\n\nThere's a full example emulating part of the Docker CLI [here](https://github.com/alecthomas/kong/tree/master/_examples/docker).\n\neg.\n\n```go\ntype Context struct {\n  Debug bool\n}\n\ntype RmCmd struct {\n  Force     bool `help:\"Force removal.\"`\n  Recursive bool `help:\"Recursively remove files.\"`\n\n  Paths []string `arg:\"\" name:\"path\" help:\"Paths to remove.\" type:\"path\"`\n}\n\nfunc (r *RmCmd) Run(ctx *Context) error {\n  fmt.Println(\"rm\", r.Paths)\n  return nil\n}\n\ntype LsCmd struct {\n  Paths []string `arg:\"\" optional:\"\" name:\"path\" help:\"Paths to list.\" type:\"path\"`\n}\n\nfunc (l *LsCmd) Run(ctx *Context) error {\n  fmt.Println(\"ls\", l.Paths)\n  return nil\n}\n\nvar cli struct {\n  Debug bool `help:\"Enable debug mode.\"`\n\n  Rm RmCmd `cmd:\"\" help:\"Remove files.\"`\n  Ls LsCmd `cmd:\"\" help:\"List paths.\"`\n}\n\nfunc main() {\n  ctx := kong.Parse(\u0026cli)\n  // Call the Run() method of the selected parsed command.\n  err := ctx.Run(\u0026Context{Debug: cli.Debug})\n  ctx.FatalIfErrorf(err)\n}\n\n```\n\n## Hooks: BeforeReset(), BeforeResolve(), BeforeApply(), AfterApply()\n\nIf a node in the CLI, or any of its embedded fields, implements a `BeforeReset(...) error`, `BeforeResolve\n(...) error`, `BeforeApply(...) error` and/or `AfterApply(...) error` method, those will be called as Kong\nresets, resolves, validates, and assigns values to the node.\n\n| Hook            | Description                                                                                                 |\n| --------------- | ----------------------------------------------------------------------------------------------------------- |\n| `BeforeReset`   | Invoked before values are reset to their defaults (as defined by the grammar) or to zero values             |\n| `BeforeResolve` | Invoked before resolvers are applied to a node                                                              |\n| `BeforeApply`   | Invoked before the traced command line arguments are applied to the grammar                                 |\n| `AfterApply`    | Invoked after command line arguments are applied to the grammar **and validated**`                          |\n\nThe `--help` flag is implemented with a `BeforeReset` hook.\n\neg.\n\n```go\n// A flag with a hook that, if triggered, will set the debug loggers output to stdout.\ntype debugFlag bool\n\nfunc (d debugFlag) BeforeApply(logger *log.Logger) error {\n  logger.SetOutput(os.Stdout)\n  return nil\n}\n\nvar cli struct {\n  Debug debugFlag `help:\"Enable debug logging.\"`\n}\n\nfunc main() {\n  // Debug logger going to discard.\n  logger := log.New(io.Discard, \"\", log.LstdFlags)\n\n  ctx := kong.Parse(\u0026cli, kong.Bind(logger))\n\n  // ...\n}\n```\n\nIt's also possible to register these hooks with the functional options\n`kong.WithBeforeReset`, `kong.WithBeforeResolve`, `kong.WithBeforeApply`, and\n`kong.WithAfterApply`.\n\n##  The Bind() option\n\nArguments to hooks are provided via the `Run(...)` method or `Bind(...)` option. `*Kong`, `*Context`, `*Path` and parent commands are also bound and finally, hooks can also contribute bindings via `kong.Context.Bind()` and `kong.Context.BindTo()`.\n\neg:\n\n```go\ntype CLI struct {\n  Debug bool `help:\"Enable debug mode.\"`\n\n  Rm RmCmd `cmd:\"\" help:\"Remove files.\"`\n  Ls LsCmd `cmd:\"\" help:\"List paths.\"`\n}\n\ntype AuthorName string\n\n// ...\nfunc (l *LsCmd) Run(cli *CLI) error {\n// use cli.Debug here !!\n  return nil\n}\n\nfunc (r *RmCmD) Run(author AuthorName) error{\n// use binded author here\n  return nil\n}\n\nfunc main() {\n  var cli CLI\n  \n  ctx := kong.Parse(\u0026cli, Bind(AuthorName(\"penguin\")))\n  err := ctx.Run()\n```\n\n## Flags\n\nAny [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.\n\neg. The command-line `app [--flag=\"foo\"]` can be represented by the following.\n\n```go\ntype CLI struct {\n  Flag string\n}\n```\n\n## Commands and sub-commands\n\nSub-commands are specified by tagging a struct field with `cmd`. Kong supports arbitrarily nested commands.\n\neg. The following struct represents the CLI structure `command [--flag=\"str\"] sub-command`.\n\n```go\ntype CLI struct {\n  Command struct {\n    Flag string\n\n    SubCommand struct {\n    } `cmd`\n  } `cmd`\n}\n```\n\nIf 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.\n\n## Branching positional arguments\n\nIn addition to sub-commands, structs can also be configured as branching positional arguments.\n\nThis 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:\n\n    app rename \u003cname\u003e to \u003cname\u003e\n\nCan be represented with the following:\n\n```go\nvar CLI struct {\n  Rename struct {\n    Name struct {\n      Name string `arg` // \u003c-- NOTE: identical name to enclosing struct field.\n      To struct {\n        Name struct {\n          Name string `arg`\n        } `arg`\n      } `cmd`\n    } `arg`\n  } `cmd`\n}\n```\n\nThis looks a little verbose in this contrived example, but typically this will not be the case.\n\n## Positional arguments\n\nIf a field is tagged with `arg:\"\"` it will be treated as the final positional\nvalue to be parsed on the command line. By default positional arguments are\nrequired, but specifying `optional:\"\"` will alter this.\n\nIf a positional argument is a slice, all remaining arguments will be appended\nto that slice.\n\n## Slices\n\nSlice values are treated specially. First the input is split on the `sep:\"\u003crune\u003e\"` 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.\n\nTo represent the following command-line:\n\n    cmd ls \u003cfile\u003e \u003cfile\u003e ...\n\nYou would use the following:\n\n```go\nvar CLI struct {\n  Ls struct {\n    Files []string `arg:\"\" type:\"existingfile\"`\n  } `cmd`\n}\n```\n\n## Maps\n\nMaps 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 `=`.\n\nTo represent the following command-line:\n\n    cmd config set \u003ckey\u003e=\u003cvalue\u003e \u003ckey\u003e=\u003cvalue\u003e ...\n\nYou would use the following:\n\n```go\nvar CLI struct {\n  Config struct {\n    Set struct {\n      Config map[string]float64 `arg:\"\" type:\"file:\"`\n    } `cmd`\n  } `cmd`\n}\n```\n\nFor flags, multiple key+value pairs should be separated by `mapsep:\"rune\"` tag (defaults to `;`) eg. `--set=\"key1=value1;key2=value2\"`.\n\n## Pointers\n\nPointers work like the underlying type, except that you can differentiate between the presence of the zero value and no value being supplied.\n\nFor example:\n\n```go\nvar CLI struct {\n\tFoo *int\n}\n```\n\nWould 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.\n\n## Nested data structure\n\nKong support a nested data structure as well with `embed:\"\"`. You can combine `embed:\"\"` with `prefix:\"\"`:\n\n```go\nvar CLI struct {\n  Logging struct {\n    Level string `enum:\"debug,info,warn,error\" default:\"info\"`\n    Type string `enum:\"json,console\" default:\"console\"`\n  } `embed:\"\" prefix:\"logging.\"`\n}\n```\n\nThis configures Kong to accept flags `--logging.level` and `--logging.type`.\n\n## Custom named decoders\n\nKong includes a number of builtin custom type mappers. These can be used by\nspecifying the tag `type:\"\u003ctype\u003e\"`. They are registered with the option\nfunction `NamedMapper(name, mapper)`.\n\n| Name           | Description                                                                                                            |\n| -------------- | ---------------------------------------------------------------------------------------------------------------------- |\n| `path`         | A path. ~ expansion is applied. `-` is accepted for stdout, and will be passed unaltered.                              |\n| `existingfile` | An existing file. ~ expansion is applied. `-` is accepted for stdin, and will be passed unaltered.                     |\n| `existingdir`  | An existing directory. ~ expansion is applied.                                                                         |\n| `counter`      | Increment a numeric field. Useful for `-vvv`. Can accept `-s`, `--long` or `--long=N`.                                 |\n| `filecontent`  | Read the file at path into the field. ~ expansion is applied. `-` is accepted for stdin, and will be passed unaltered. |\n\nSlices and maps treat type tags specially. For slices, the `type:\"\"` tag\nspecifies the element type. For maps, the tag has the format\n`tag:\"[\u003ckey\u003e]:[\u003cvalue\u003e]\"` where either may be omitted.\n\n## Supported field types\n\n## Custom decoders (mappers)\n\nAny field implementing `encoding.TextUnmarshaler` or `json.Unmarshaler` will use those interfaces\nfor decoding values. Kong also includes builtin support for many common Go types:\n\n| Type            | Description                                                                                                 |\n| --------------- | ----------------------------------------------------------------------------------------------------------- |\n| `time.Duration` | Populated using `time.ParseDuration()`.                                                                     |\n| `time.Time`     | Populated using `time.Parse()`. Format defaults to RFC3339 but can be overridden with the `format:\"X\"` tag. |\n| `*os.File`      | Path to a file that will be opened, or `-` for `os.Stdin`. File must be closed by the user.                 |\n| `*url.URL`      | Populated with `url.Parse()`.                                                                               |\n\nFor more fine-grained control, if a field implements the\n[MapperValue](https://godoc.org/github.com/alecthomas/kong#MapperValue)\ninterface it will be used to decode arguments into the field.\n\n## Supported tags\n\nTags can be in two forms:\n\n1. Standard Go syntax, eg. `kong:\"required,name='foo'\"`.\n2. Bare tags, eg. `required:\"\" name:\"foo\"`\n\nBoth can coexist with standard Tag parsing.\n\n| Tag                  | Description                                                                                                                                                                                                                                                                                                                    |\n| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `cmd:\"\"`             | If present, struct is a command.                                                                                                                                                                                                                                                                                               |\n| `arg:\"\"`             | If present, field is an argument. Required by default.                                                                                                                                                                                                                                                                         |\n| `env:\"X,Y,...\"`      | Specify envars to use for default value. The envs are resolved in the declared order. The first value found is used.                                                                                                                                                                                                           |\n| `name:\"X\"`           | Long name, for overriding field name.                                                                                                                                                                                                                                                                                          |\n| `help:\"X\"`           | Help text.                                                                                                                                                                                                                                                                                                                     |\n| `type:\"X\"`           | Specify [named types](#custom-named-decoders) to use.                                                                                                                                                                                                                                                                          |\n| `placeholder:\"X\"`    | Placeholder input, if flag. e.g. `` `placeholder:\"\u003cthe-placeholder\u003e\"` `` will show `--flag-name=\u003cthe-placeholder\u003e` when displaying help.                                                                                                                                                                                       |\n| `default:\"X\"`        | Default value.                                                                                                                                                                                                                                                                                                                 |\n| `default:\"1\"`        | On a command, make it the default.                                                                                                                                                                                                                                                                                             |\n| `default:\"withargs\"` | On a command, make it the default and allow args/flags from that command                                                                                                                                                                                                                                                       |\n| `short:\"X\"`          | Short name, if flag.                                                                                                                                                                                                                                                                                                           |\n| `aliases:\"X,Y\"`      | One or more aliases (for cmd or flag).                                                                                                                                                                                                                                                                                         |\n| `required:\"\"`        | If present, flag/arg is required.                                                                                                                                                                                                                                                                                              |\n| `optional:\"\"`        | If present, flag/arg is optional.                                                                                                                                                                                                                                                                                              |\n| `hidden:\"\"`          | If present, command or flag is hidden.                                                                                                                                                                                                                                                                                         |\n| `negatable:\"\"`       | If present on a `bool` field, supports prefixing a flag with `--no-` to invert the default value                                                                                                                                                                                                                               |\n| `negatable:\"X\"`      | If present on a `bool` field, supports `--X` to invert the default value                                                                                                                                                                                                                                                       |\n| `format:\"X\"`         | Format for parsing input, if supported.                                                                                                                                                                                                                                                                                        |\n| `sep:\"X\"`            | Separator for sequences (defaults to \",\"). May be `none` to disable splitting.                                                                                                                                                                                                                                                 |\n| `mapsep:\"X\"`         | Separator for maps (defaults to \";\"). May be `none` to disable splitting.                                                                                                                                                                                                                                                      |\n| `enum:\"X,Y,...\"`     | Set of valid values allowed for this flag. An enum field must be `required` or have a valid `default`.                                                                                                                                                                                                                         |\n| `group:\"X\"`          | Logical group for a flag or command.                                                                                                                                                                                                                                                                                           |\n| `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.                                                                                                                            |\n| `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.                                                                                                                                                                         |\n| `prefix:\"X\"`         | Prefix for all sub-flags.                                                                                                                                                                                                                                                                                                      |\n| `envprefix:\"X\"`      | Envar prefix for all sub-flags.                                                                                                                                                                                                                                                                                                |\n| `xorprefix:\"X\"`      | Prefix for all sub-flags in XOR/AND groups.                                                                                                                                                                                                                                                                                  |\n| `set:\"K=V\"`          | Set a variable for expansion by child elements. Multiples can occur.                                                                                                                                                                                                                                                           |\n| `embed:\"\"`           | If present, this field's children will be embedded in the parent. Useful for composition.                                                                                                                                                                                                                                      |\n| `passthrough:\"\u003cmode\u003e\"`[^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. |\n| `-`                  | Ignore the field. Useful for adding non-CLI fields to a configuration struct. e.g `` `kong:\"-\"` ``                                                                                                                                                                                                                             |\n\n[^1]: `\u003cmode\u003e` can be `partial` or `all` (the default). `all` will pass through all arguments including flags, including\nflags. `partial` will validate flags until the first positional argument is encountered, then pass through all remaining\npositional arguments.\n\n## Plugins\n\nKong CLI's can be extended by embedding the `kong.Plugin` type and populating it with pointers to Kong annotated structs. For example:\n\n```go\nvar pluginOne struct {\n  PluginOneFlag string\n}\nvar pluginTwo struct {\n  PluginTwoFlag string\n}\nvar cli struct {\n  BaseFlag string\n  kong.Plugins\n}\ncli.Plugins = kong.Plugins{\u0026pluginOne, \u0026pluginTwo}\n```\n\nAdditionally if an interface type is embedded, it can also be populated with a Kong annotated struct.\n\n## Dynamic Commands\n\nWhile plugins give complete control over extending command-line interfaces, Kong\nalso supports dynamically adding commands via `kong.DynamicCommand()`.\n\n## Variable interpolation\n\nKong supports limited variable interpolation into help strings, placeholder strings,\nenum lists and default values.\n\nVariables are in the form:\n\n    ${\u003cname\u003e}\n    ${\u003cname\u003e=\u003cdefault\u003e}\n\nVariables are set with the `Vars{\"key\": \"value\", ...}` option. Undefined\nvariable references in the grammar without a default will result in an error at\nconstruction time.\n\nVariables can also be set via the `set:\"K=V\"` tag. In this case, those variables will be available for that\nnode and all children. This is useful for composition by allowing the same struct to be reused.\n\nWhen interpolating into flag or argument help strings, some extra variables\nare defined from the value itself:\n\n    ${default}\n    ${enum}\n\nFor flags with associated environment variables, the variable `${env}` can be\ninterpolated into the help string. In the absence of this variable in the\nhelp string, Kong will append `($$${env})` to the help string.\n\neg.\n\n```go\ntype cli struct {\n  Config string `type:\"path\" default:\"${config_file}\"`\n}\n\nfunc main() {\n  kong.Parse(\u0026cli,\n    kong.Vars{\n      \"config_file\": \"~/.app.conf\",\n    })\n}\n```\n\n## Validation\n\nKong does validation on the structure of a command-line, but also supports\nextensible validation. Any node in the tree may implement either of the following interfaces:\n\n```go\ntype Validatable interface {\n    Validate() error\n }\n```\n\n```go\ntype Validatable interface {\n    Validate(kctx *kong.Context) error\n }\n```\n\nIf one of these nodes is in the active command-line it will be called during\nnormal validation.\n\n## Modifying Kong's behaviour\n\nEach Kong parser can be configured via functional options passed to `New(cli any, options...Option)`.\n\nThe full set of options can be found [here](https://godoc.org/github.com/alecthomas/kong#Option).\n\n### `Name(help)` and `Description(help)` - set the application name description\n\nSet the application name and/or description.\n\nThe name of the application will default to the binary name, but can be overridden with `Name(name)`.\n\nAs with all help in Kong, text will be wrapped to the terminal.\n\n### `Configuration(loader, paths...)` - load defaults from configuration files\n\nThis 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.\n\neg.\n\n```go\nkong.Parse(\u0026cli, kong.Configuration(kong.JSON, \"/etc/myapp.json\", \"~/.myapp.json\"))\n```\n\n[See the tests](https://github.com/alecthomas/kong/blob/master/resolver_test.go#L206) for an example of how the JSON file is structured.\n\n#### List of Configuration Loaders\n\n- [YAML](https://github.com/alecthomas/kong-yaml)\n- [HCL](https://github.com/alecthomas/kong-hcl)\n- [TOML](https://github.com/alecthomas/kong-toml)\n- [JSON](https://github.com/alecthomas/kong)\n\n### `Resolver(...)` - support for default values from external sources\n\nResolvers 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.\n\nExample resolvers can be found in [resolver.go](https://github.com/alecthomas/kong/blob/master/resolver.go).\n\n### `*Mapper(...)` - customising how the command-line is mapped to Go values\n\nCommand-line arguments are mapped to Go values via the Mapper interface:\n\n```go\n// A Mapper represents how a field is mapped from command-line values to Go.\n//\n// Mappers can be associated with concrete fields via pointer, reflect.Type, reflect.Kind, or via a \"type\" tag.\n//\n// Additionally, if a type implements the MapperValue interface, it will be used.\ntype Mapper interface {\n\t// Decode ctx.Value with ctx.Scanner into target.\n\tDecode(ctx *DecodeContext, target reflect.Value) error\n}\n```\n\nAll 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:\n\n1. `NamedMapper(string, Mapper)` and using the tag key `type:\"\u003cname\u003e\"`.\n2. `KindMapper(reflect.Kind, Mapper)`.\n3. `TypeMapper(reflect.Type, Mapper)`.\n4. `ValueMapper(any, Mapper)`, passing in a pointer to a field of the grammar.\n\n### `ConfigureHelp(HelpOptions)` and `Help(HelpFunc)` - customising help\n\nThe default help output is usually sufficient, but if not there are two solutions.\n\n1. Use `ConfigureHelp(HelpOptions)` to configure how help is formatted (see [HelpOptions](https://godoc.org/github.com/alecthomas/kong#HelpOptions) for details).\n2. 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.\n3. Use `ValueFormatter(HelpValueFormatter)` if you want to just customize the help text that is accompanied by flags and arguments.\n4. Use `Groups([]Group)` if you want to customize group titles or add a header.\n\n### Injecting values into `Run()` methods\n\nThere are several ways to inject values into `Run()` methods:\n\n1. Use `Bind()` to bind values directly.\n2. Use `BindTo()` to bind values to an interface type.\n3. Use `BindToProvider()` to bind values to a function that provides the value.\n4. Implement `Provide\u003cType\u003e() error` methods on the command structure.\n\n### Other options\n\nThe full set of options can be found [here](https://godoc.org/github.com/alecthomas/kong#Option).\n","funding_links":["https://github.com/sponsors/alecthomas"],"categories":["配置","Configuration","开源类库","Repositories","Go","Open source library","golang","Uncategorized","[Go](https://go.dev/)"],"sub_categories":["标准CLI","Standard CLI","命令行","Command Line","Useful awesome list for Dotnet cli","Uncategorized","Advanced Console UIs"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falecthomas%2Fkong","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falecthomas%2Fkong","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falecthomas%2Fkong/lists"}