{"id":13397154,"url":"https://github.com/alecthomas/kingpin","last_synced_at":"2025-05-12T03:35:59.034Z","repository":{"id":17030321,"uuid":"19794451","full_name":"alecthomas/kingpin","owner":"alecthomas","description":"CONTRIBUTIONS ONLY: A Go (golang) command line and flag parser","archived":false,"fork":false,"pushed_at":"2025-04-02T06:13:55.000Z","size":562,"stargazers_count":3527,"open_issues_count":29,"forks_count":277,"subscribers_count":47,"default_branch":"master","last_synced_at":"2025-04-22T16:56:30.779Z","etag":null,"topics":["cli","command-line","go","kingpin"],"latest_commit_sha":null,"homepage":"","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":null,"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":"2014-05-14T20:09:04.000Z","updated_at":"2025-04-22T06:43:03.000Z","dependencies_parsed_at":"2024-05-14T12:45:08.465Z","dependency_job_id":"2746358b-081f-4722-845d-9371c7a2164a","html_url":"https://github.com/alecthomas/kingpin","commit_stats":{"total_commits":310,"total_committers":72,"mean_commits":4.305555555555555,"dds":0.3709677419354839,"last_synced_commit":"99e26ad9e43112d3b8a72b3ac2a6c730163d9113"},"previous_names":[],"tags_count":60,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alecthomas%2Fkingpin","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alecthomas%2Fkingpin/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alecthomas%2Fkingpin/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alecthomas%2Fkingpin/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/alecthomas","download_url":"https://codeload.github.com/alecthomas/kingpin/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251219600,"owners_count":21554444,"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":["cli","command-line","go","kingpin"],"created_at":"2024-07-30T18:01:11.860Z","updated_at":"2025-04-30T21:55:45.003Z","avatar_url":"https://github.com/alecthomas.png","language":"Go","readme":"# CONTRIBUTIONS ONLY\n\n**What does this mean?** I do not have time to fix issues myself. The only way fixes or new features will be added is by people submitting PRs. If you are interested in taking over maintenance and have a history of contributions to Kingpin, please let me know.\n\n**Current status.** Kingpin is largely feature stable. There hasn't been a need to add new features in a while, but there are some bugs that should be fixed.\n\n**Why?** I no longer use Kingpin personally (I now use [kong](https://github.com/alecthomas/kong)). Rather than leave the project in a limbo of people filing issues and wondering why they're not being worked on, I believe this notice will more clearly set expectations.\n\n# Kingpin - A Go (golang) command line and flag parser\n[![](https://godoc.org/github.com/alecthomas/kingpin?status.svg)](http://godoc.org/github.com/alecthomas/kingpin) [![CI](https://github.com/alecthomas/kingpin/actions/workflows/ci.yml/badge.svg)](https://github.com/alecthomas/kingpin/actions/workflows/ci.yml)\n\n\n\n\n\n\u003c!-- MarkdownTOC --\u003e\n\n- [Overview](#overview)\n- [Features](#features)\n- [User-visible changes between v1 and v2](#user-visible-changes-between-v1-and-v2)\n  - [Flags can be used at any point after their definition.](#flags-can-be-used-at-any-point-after-their-definition)\n  - [Short flags can be combined with their parameters](#short-flags-can-be-combined-with-their-parameters)\n- [API changes between v1 and v2](#api-changes-between-v1-and-v2)\n- [Versions](#versions)\n  - [V2 is the current stable version](#v2-is-the-current-stable-version)\n  - [V1 is the OLD stable version](#v1-is-the-old-stable-version)\n- [Change History](#change-history)\n- [Examples](#examples)\n  - [Simple Example](#simple-example)\n  - [Complex Example](#complex-example)\n- [Reference Documentation](#reference-documentation)\n  - [Displaying errors and usage information](#displaying-errors-and-usage-information)\n  - [Sub-commands](#sub-commands)\n  - [Custom Parsers](#custom-parsers)\n  - [Repeatable flags](#repeatable-flags)\n  - [Boolean Values](#boolean-values)\n  - [Default Values](#default-values)\n  - [Place-holders in Help](#place-holders-in-help)\n  - [Consuming all remaining arguments](#consuming-all-remaining-arguments)\n  - [Bash/ZSH Shell Completion](#bashzsh-shell-completion)\n  - [Supporting -h for help](#supporting--h-for-help)\n  - [Custom help](#custom-help)\n\n\u003c!-- /MarkdownTOC --\u003e\n\n## Overview\n\nKingpin is a [fluent-style](http://en.wikipedia.org/wiki/Fluent_interface),\ntype-safe command-line parser. It supports flags, nested commands, and\npositional arguments.\n\nInstall it with:\n\n    $ go get github.com/alecthomas/kingpin/v2\n\nIt looks like this:\n\n```go\nvar (\n  verbose = kingpin.Flag(\"verbose\", \"Verbose mode.\").Short('v').Bool()\n  name    = kingpin.Arg(\"name\", \"Name of user.\").Required().String()\n)\n\nfunc main() {\n  kingpin.Parse()\n  fmt.Printf(\"%v, %s\\n\", *verbose, *name)\n}\n```\n\nMore [examples](https://github.com/alecthomas/kingpin/tree/master/_examples) are available.\n\nSecond to parsing, providing the user with useful help is probably the most\nimportant thing a command-line parser does. Kingpin tries to provide detailed\ncontextual help if `--help` is encountered at any point in the command line\n(excluding after `--`).\n\n## Features\n\n- Help output that isn't as ugly as sin.\n- Fully [customisable help](#custom-help), via Go templates.\n- Parsed, type-safe flags (`kingpin.Flag(\"f\", \"help\").Int()`)\n- Parsed, type-safe positional arguments (`kingpin.Arg(\"a\", \"help\").Int()`).\n- Parsed, type-safe, arbitrarily deep commands (`kingpin.Command(\"c\", \"help\")`).\n- Support for required flags and required positional arguments (`kingpin.Flag(\"f\", \"\").Required().Int()`).\n- Support for arbitrarily nested default commands (`command.Default()`).\n- Callbacks per command, flag and argument (`kingpin.Command(\"c\", \"\").Action(myAction)`).\n- POSIX-style short flag combining (`-a -b` -\u003e `-ab`).\n- Short-flag+parameter combining (`-a parm` -\u003e `-aparm`).\n- Read command-line from files (`@\u003cfile\u003e`).\n- Automatically generate man pages (`--help-man`).\n\n## User-visible changes between v1 and v2\n\n### Flags can be used at any point after their definition.\n\nFlags can be specified at any point after their definition, not just\n*immediately after their associated command*. From the chat example below, the\nfollowing used to be required:\n\n```\n$ chat --server=chat.server.com:8080 post --image=~/Downloads/owls.jpg pics\n```\n\nBut the following will now work:\n\n```\n$ chat post --server=chat.server.com:8080 --image=~/Downloads/owls.jpg pics\n```\n\n### Short flags can be combined with their parameters\n\nPreviously, if a short flag was used, any argument to that flag would have to\nbe separated by a space. That is no longer the case.\n\n## API changes between v1 and v2\n\n- `ParseWithFileExpansion()` is gone. The new parser directly supports expanding `@\u003cfile\u003e`.\n- Added `FatalUsage()` and `FatalUsageContext()` for displaying an error + usage and terminating.\n- `Dispatch()` renamed to `Action()`.\n- Added `ParseContext()` for parsing a command line into its intermediate context form without executing.\n- Added `Terminate()` function to override the termination function.\n- Added `UsageForContextWithTemplate()` for printing usage via a custom template.\n- Added `UsageTemplate()` for overriding the default template to use. Two templates are included:\n    1. `DefaultUsageTemplate` - default template.\n    2. `CompactUsageTemplate` - compact command template for larger applications.\n\n## Versions\n\nThe current stable version is [github.com/alecthomas/kingpin/v2](https://github.com/alecthomas/kingpin/v2). The previous version, [gopkg.in/alecthomas/kingpin.v1](https://gopkg.in/alecthomas/kingpin.v1), is deprecated and in maintenance mode.\n\n### [V2](https://github.com/alecthomas/kingpin/v2) is the current stable version\n\nInstallation:\n\n```sh\n$ go get github.com/alecthomas/kingpin/v2\n```\n\n### [V1](https://gopkg.in/alecthomas/kingpin.v1) is the OLD stable version\n\nInstallation:\n\n```sh\n$ go get gopkg.in/alecthomas/kingpin.v1\n```\n\n## Change History\n\n- *2015-09-19* -- Stable v2.1.0 release.\n    - Added `command.Default()` to specify a default command to use if no other\n      command matches. This allows for convenient user shortcuts.\n    - Exposed `HelpFlag` and `VersionFlag` for further customisation.\n    - `Action()` and `PreAction()` added and both now support an arbitrary\n      number of callbacks.\n    - `kingpin.SeparateOptionalFlagsUsageTemplate`.\n    - `--help-long` and `--help-man` (hidden by default) flags.\n    - Flags are \"interspersed\" by default, but can be disabled with `app.Interspersed(false)`.\n    - Added flags for all simple builtin types (int8, uint16, etc.) and slice variants.\n    - Use `app.Writer(os.Writer)` to specify the default writer for all output functions.\n    - Dropped `os.Writer` prefix from all printf-like functions.\n\n- *2015-05-22* -- Stable v2.0.0 release.\n    - Initial stable release of v2.0.0.\n    - Fully supports interspersed flags, commands and arguments.\n    - Flags can be present at any point after their logical definition.\n    - Application.Parse() terminates if commands are present and a command is not parsed.\n    - Dispatch() -\u003e Action().\n    - Actions are dispatched after all values are populated.\n    - Override termination function (defaults to os.Exit).\n    - Override output stream (defaults to os.Stderr).\n    - Templatised usage help, with default and compact templates.\n    - Make error/usage functions more consistent.\n    - Support argument expansion from files by default (with @\u003cfile\u003e).\n    - Fully public data model is available via .Model().\n    - Parser has been completely refactored.\n    - Parsing and execution has been split into distinct stages.\n    - Use `go generate` to generate repeated flags.\n    - Support combined short-flag+argument: -fARG.\n\n- *2015-01-23* -- Stable v1.3.4 release.\n    - Support \"--\" for separating flags from positional arguments.\n    - Support loading flags from files (ParseWithFileExpansion()). Use @FILE as an argument.\n    - Add post-app and post-cmd validation hooks. This allows arbitrary validation to be added.\n    - A bunch of improvements to help usage and formatting.\n    - Support arbitrarily nested sub-commands.\n\n- *2014-07-08* -- Stable v1.2.0 release.\n    - Pass any value through to `Strings()` when final argument.\n      Allows for values that look like flags to be processed.\n    - Allow `--help` to be used with commands.\n    - Support `Hidden()` flags.\n    - Parser for [units.Base2Bytes](https://github.com/alecthomas/units)\n      type. Allows for flags like `--ram=512MB` or `--ram=1GB`.\n    - Add an `Enum()` value, allowing only one of a set of values\n      to be selected. eg. `Flag(...).Enum(\"debug\", \"info\", \"warning\")`.\n\n- *2014-06-27* -- Stable v1.1.0 release.\n    - Bug fixes.\n    - Always return an error (rather than panicing) when misconfigured.\n    - `OpenFile(flag, perm)` value type added, for finer control over opening files.\n    - Significantly improved usage formatting.\n\n- *2014-06-19* -- Stable v1.0.0 release.\n    - Support [cumulative positional](#consuming-all-remaining-arguments) arguments.\n    - Return error rather than panic when there are fatal errors not caught by\n      the type system. eg. when a default value is invalid.\n    - Use gokpg.in.\n\n- *2014-06-10* -- Place-holder streamlining.\n    - Renamed `MetaVar` to `PlaceHolder`.\n    - Removed `MetaVarFromDefault`. Kingpin now uses [heuristics](#place-holders-in-help)\n      to determine what to display.\n\n## Examples\n\n### Simple Example\n\nKingpin can be used for simple flag+arg applications like so:\n\n```\n$ ping --help\nusage: ping [\u003cflags\u003e] \u003cip\u003e [\u003ccount\u003e]\n\nFlags:\n  --debug            Enable debug mode.\n  --help             Show help.\n  -t, --timeout=5s   Timeout waiting for ping.\n\nArgs:\n  \u003cip\u003e        IP address to ping.\n  [\u003ccount\u003e]   Number of packets to send\n$ ping 1.2.3.4 5\nWould ping: 1.2.3.4 with timeout 5s and count 5\n```\n\nFrom the following source:\n\n```go\npackage main\n\nimport (\n  \"fmt\"\n\n  \"github.com/alecthomas/kingpin/v2\"\n)\n\nvar (\n  debug   = kingpin.Flag(\"debug\", \"Enable debug mode.\").Bool()\n  timeout = kingpin.Flag(\"timeout\", \"Timeout waiting for ping.\").Default(\"5s\").Envar(\"PING_TIMEOUT\").Short('t').Duration()\n  ip      = kingpin.Arg(\"ip\", \"IP address to ping.\").Required().IP()\n  count   = kingpin.Arg(\"count\", \"Number of packets to send\").Int()\n)\n\nfunc main() {\n  kingpin.Version(\"0.0.1\")\n  kingpin.Parse()\n  fmt.Printf(\"Would ping: %s with timeout %s and count %d\\n\", *ip, *timeout, *count)\n}\n```\n\n#### Reading arguments from a file\nKingpin supports reading arguments from a file.\nCreate a file with the corresponding arguments:\n```\necho -t=5\\n \u003e args\n```\nAnd now supply it:\n```\n$ ping @args\n```\n\n### Complex Example\n\nKingpin can also produce complex command-line applications with global flags,\nsubcommands, and per-subcommand flags, like this:\n\n```\n$ chat --help\nusage: chat [\u003cflags\u003e] \u003ccommand\u003e [\u003cflags\u003e] [\u003cargs\u003e ...]\n\nA command-line chat application.\n\nFlags:\n  --help              Show help.\n  --debug             Enable debug mode.\n  --server=127.0.0.1  Server address.\n\nCommands:\n  help [\u003ccommand\u003e]\n    Show help for a command.\n\n  register \u003cnick\u003e \u003cname\u003e\n    Register a new user.\n\n  post [\u003cflags\u003e] \u003cchannel\u003e [\u003ctext\u003e]\n    Post a message to a channel.\n\n$ chat help post\nusage: chat [\u003cflags\u003e] post [\u003cflags\u003e] \u003cchannel\u003e [\u003ctext\u003e]\n\nPost a message to a channel.\n\nFlags:\n  --image=IMAGE  Image to post.\n\nArgs:\n  \u003cchannel\u003e  Channel to post to.\n  [\u003ctext\u003e]   Text to post.\n\n$ chat post --image=~/Downloads/owls.jpg pics\n...\n```\n\nFrom this code:\n\n```go\npackage main\n\nimport (\n  \"os\"\n  \"strings\"\n  \"github.com/alecthomas/kingpin/v2\"\n)\n\nvar (\n  app      = kingpin.New(\"chat\", \"A command-line chat application.\")\n  debug    = app.Flag(\"debug\", \"Enable debug mode.\").Bool()\n  serverIP = app.Flag(\"server\", \"Server address.\").Default(\"127.0.0.1\").IP()\n\n  register     = app.Command(\"register\", \"Register a new user.\")\n  registerNick = register.Arg(\"nick\", \"Nickname for user.\").Required().String()\n  registerName = register.Arg(\"name\", \"Name of user.\").Required().String()\n\n  post        = app.Command(\"post\", \"Post a message to a channel.\")\n  postImage   = post.Flag(\"image\", \"Image to post.\").File()\n  postChannel = post.Arg(\"channel\", \"Channel to post to.\").Required().String()\n  postText    = post.Arg(\"text\", \"Text to post.\").Strings()\n)\n\nfunc main() {\n  switch kingpin.MustParse(app.Parse(os.Args[1:])) {\n  // Register user\n  case register.FullCommand():\n    println(*registerNick)\n\n  // Post message\n  case post.FullCommand():\n    if *postImage != nil {\n    }\n    text := strings.Join(*postText, \" \")\n    println(\"Post:\", text)\n  }\n}\n```\n\n## Reference Documentation\n\n### Displaying errors and usage information\n\nKingpin exports a set of functions to provide consistent errors and usage\ninformation to the user.\n\nError messages look something like this:\n\n    \u003capp\u003e: error: \u003cmessage\u003e\n\nThe functions on `Application` are:\n\nFunction | Purpose\n---------|--------------\n`Errorf(format, args)` | Display a printf formatted error to the user.\n`Fatalf(format, args)` | As with Errorf, but also call the termination handler.\n`FatalUsage(format, args)` | As with Fatalf, but also print contextual usage information.\n`FatalUsageContext(context, format, args)` | As with Fatalf, but also print contextual usage information from a `ParseContext`.\n`FatalIfError(err, format, args)` | Conditionally print an error prefixed with format+args, then call the termination handler\n\nThere are equivalent global functions in the kingpin namespace for the default\n`kingpin.CommandLine` instance.\n\n### Sub-commands\n\nKingpin supports nested sub-commands, with separate flag and positional\narguments per sub-command. Note that positional arguments may only occur after\nsub-commands.\n\nFor example:\n\n```go\nvar (\n  deleteCommand     = kingpin.Command(\"delete\", \"Delete an object.\")\n  deleteUserCommand = deleteCommand.Command(\"user\", \"Delete a user.\")\n  deleteUserUIDFlag = deleteUserCommand.Flag(\"uid\", \"Delete user by UID rather than username.\")\n  deleteUserUsername = deleteUserCommand.Arg(\"username\", \"Username to delete.\")\n  deletePostCommand = deleteCommand.Command(\"post\", \"Delete a post.\")\n)\n\nfunc main() {\n  switch kingpin.Parse() {\n  case deleteUserCommand.FullCommand():\n  case deletePostCommand.FullCommand():\n  }\n}\n```\n\n### Custom Parsers\n\nKingpin supports both flag and positional argument parsers for converting to\nGo types. For example, some included parsers are `Int()`, `Float()`,\n`Duration()` and `ExistingFile()` (see [parsers.go](./parsers.go) for a complete list of included parsers).\n\nParsers conform to Go's [`flag.Value`](http://godoc.org/flag#Value)\ninterface, so any existing implementations will work.\n\nFor example, a parser for accumulating HTTP header values might look like this:\n\n```go\ntype HTTPHeaderValue http.Header\n\nfunc (h *HTTPHeaderValue) Set(value string) error {\n  parts := strings.SplitN(value, \":\", 2)\n  if len(parts) != 2 {\n    return fmt.Errorf(\"expected HEADER:VALUE got '%s'\", value)\n  }\n  (*http.Header)(h).Add(parts[0], parts[1])\n  return nil\n}\n\nfunc (h *HTTPHeaderValue) String() string {\n  return \"\"\n}\n```\n\nAs a convenience, I would recommend something like this:\n\n```go\nfunc HTTPHeader(s Settings) (target *http.Header) {\n  target = \u0026http.Header{}\n  s.SetValue((*HTTPHeaderValue)(target))\n  return\n}\n```\n\nYou would use it like so:\n\n```go\nheaders = HTTPHeader(kingpin.Flag(\"header\", \"Add a HTTP header to the request.\").Short('H'))\n```\n\n### Repeatable flags\n\nDepending on the `Value` they hold, some flags may be repeated. The\n`IsCumulative() bool` function on `Value` tells if it's safe to call `Set()`\nmultiple times or if an error should be raised if several values are passed.\n\nThe built-in `Value`s returning slices and maps, as well as `Counter` are\nexamples of `Value`s that make a flag repeatable.\n\n### Boolean values\n\nBoolean values are uniquely managed by Kingpin. Each boolean flag will have a negative complement:\n`--\u003cname\u003e` and `--no-\u003cname\u003e`.\n\n### Default Values\n\nThe default value is the zero value for a type. This can be overridden with\nthe `Default(value...)` function on flags and arguments. This function accepts\none or several strings, which are parsed by the value itself, so they *must*\nbe compliant with the format expected.\n\n### Place-holders in Help\n\nThe place-holder value for a flag is the value used in the help to describe\nthe value of a non-boolean flag.\n\nThe value provided to PlaceHolder() is used if provided, then the value\nprovided by Default() if provided, then finally the capitalised flag name is\nused.\n\nHere are some examples of flags with various permutations:\n\n    --name=NAME           // Flag(...).String()\n    --name=\"Harry\"        // Flag(...).Default(\"Harry\").String()\n    --name=FULL-NAME      // Flag(...).PlaceHolder(\"FULL-NAME\").Default(\"Harry\").String()\n\n### Consuming all remaining arguments\n\nA common command-line idiom is to use all remaining arguments for some\npurpose. eg. The following command accepts an arbitrary number of\nIP addresses as positional arguments:\n\n    ./cmd ping 10.1.1.1 192.168.1.1\n\nSuch arguments are similar to [repeatable flags](#repeatable-flags), but for\narguments. Therefore they use the same `IsCumulative() bool` function on the\nunderlying `Value`, so the built-in `Value`s for which the `Set()` function\ncan be called several times will consume multiple arguments.\n\nTo implement the above example with a custom `Value`, we might do something\nlike this:\n\n```go\ntype ipList []net.IP\n\nfunc (i *ipList) Set(value string) error {\n  if ip := net.ParseIP(value); ip == nil {\n    return fmt.Errorf(\"'%s' is not an IP address\", value)\n  } else {\n    *i = append(*i, ip)\n    return nil\n  }\n}\n\nfunc (i *ipList) String() string {\n  return \"\"\n}\n\nfunc (i *ipList) IsCumulative() bool {\n  return true\n}\n\nfunc IPList(s Settings) (target *[]net.IP) {\n  target = new([]net.IP)\n  s.SetValue((*ipList)(target))\n  return\n}\n```\n\nAnd use it like so:\n\n```go\nips := IPList(kingpin.Arg(\"ips\", \"IP addresses to ping.\"))\n```\n\n### Bash/ZSH Shell Completion\n\nBy default, all flags and commands/subcommands generate completions\ninternally.\n\nOut of the box, CLI tools using kingpin should be able to take advantage\nof completion hinting for flags and commands. By specifying\n`--completion-bash` as the first argument, your CLI tool will show\npossible subcommands. By ending your argv with `--`, hints for flags\nwill be shown.\n\nTo allow your end users to take advantage you must package a\n`/etc/bash_completion.d` script with your distribution (or the equivalent\nfor your target platform/shell). An alternative is to instruct your end\nuser to source a script from their `bash_profile` (or equivalent).\n\nFortunately Kingpin makes it easy to generate or source a script for use\nwith end users shells. `./yourtool --completion-script-bash` and\n`./yourtool --completion-script-zsh` will generate these scripts for you.\n\n**Installation by Package**\n\nFor the best user experience, you should bundle your pre-created\ncompletion script with your CLI tool and install it inside\n`/etc/bash_completion.d` (or equivalent). A good suggestion is to add\nthis as an automated step to your build pipeline, in the implementation\nis improved for bug fixed.\n\n**Installation by `bash_profile`**\n\nAlternatively, instruct your users to add an additional statement to\ntheir `bash_profile` (or equivalent):\n\n```\neval \"$(your-cli-tool --completion-script-bash)\"\n```\n\nOr for ZSH\n\n```\neval \"$(your-cli-tool --completion-script-zsh)\"\n```\n\n#### Additional API\nTo provide more flexibility, a completion option API has been\nexposed for flags to allow user defined completion options, to extend\ncompletions further than just EnumVar/Enum.\n\n\n**Provide Static Options**\n\nWhen using an `Enum` or `EnumVar`, users are limited to only the options\ngiven. Maybe we wish to hint possible options to the user, but also\nallow them to provide their own custom option. `HintOptions` gives\nthis functionality to flags.\n\n```\napp := kingpin.New(\"completion\", \"My application with bash completion.\")\napp.Flag(\"port\", \"Provide a port to connect to\").\n    Required().\n    HintOptions(\"80\", \"443\", \"8080\").\n    IntVar(\u0026c.port)\n```\n\n**Provide Dynamic Options**\nConsider the case that you needed to read a local database or a file to\nprovide suggestions. You can dynamically generate the options\n\n```\nfunc listHosts() []string {\n  // Provide a dynamic list of hosts from a hosts file or otherwise\n  // for bash completion. In this example we simply return static slice.\n\n  // You could use this functionality to reach into a hosts file to provide\n  // completion for a list of known hosts.\n  return []string{\"sshhost.example\", \"webhost.example\", \"ftphost.example\"}\n}\n\napp := kingpin.New(\"completion\", \"My application with bash completion.\")\napp.Flag(\"flag-1\", \"\").HintAction(listHosts).String()\n```\n\n**EnumVar/Enum**\nWhen using `Enum` or `EnumVar`, any provided options will be automatically\nused for bash autocompletion. However, if you wish to provide a subset or\ndifferent options, you can use `HintOptions` or `HintAction` which will override\nthe default completion options for `Enum`/`EnumVar`.\n\n\n**Examples**\nYou can see an in depth example of the completion API within\n`examples/completion/main.go`\n\n\n### Supporting -h for help\n\n`kingpin.CommandLine.HelpFlag.Short('h')`\n\nShort help is also available when creating a more complicated app:\n\n```go\nvar (\n\tapp = kingpin.New(\"chat\", \"A command-line chat application.\")\n  // ...\n)\n\nfunc main() {\n\tapp.HelpFlag.Short('h')\n\tswitch kingpin.MustParse(app.Parse(os.Args[1:])) {\n  // ...\n  }\n}\n```\n\n### Custom help\n\nKingpin v2 supports templatised help using the text/template library (actually, [a fork](https://github.com/alecthomas/template)).\n\nYou can specify the template to use with the [Application.UsageTemplate()](http://godoc.org/github.com/alecthomas/kingpin/v2#Application.UsageTemplate) function.\n\nThere are four included templates: `kingpin.DefaultUsageTemplate` is the default,\n`kingpin.CompactUsageTemplate` provides a more compact representation for more complex command-line structures,\n`kingpin.SeparateOptionalFlagsUsageTemplate` looks like the default template, but splits required\nand optional command flags into separate lists, and `kingpin.ManPageTemplate` is used to generate man pages.\n\nSee the above templates for examples of usage, and the the function [UsageForContextWithTemplate()](https://github.com/alecthomas/kingpin/blob/master/usage.go#L198) method for details on the context.\n\n#### Default help template\n\n```\n$ go run ./examples/curl/curl.go --help\nusage: curl [\u003cflags\u003e] \u003ccommand\u003e [\u003cargs\u003e ...]\n\nAn example implementation of curl.\n\nFlags:\n  --help            Show help.\n  -t, --timeout=5s  Set connection timeout.\n  -H, --headers=HEADER=VALUE\n                    Add HTTP headers to the request.\n\nCommands:\n  help [\u003ccommand\u003e...]\n    Show help.\n\n  get url \u003curl\u003e\n    Retrieve a URL.\n\n  get file \u003cfile\u003e\n    Retrieve a file.\n\n  post [\u003cflags\u003e] \u003curl\u003e\n    POST a resource.\n```\n\n#### Compact help template\n\n```\n$ go run ./examples/curl/curl.go --help\nusage: curl [\u003cflags\u003e] \u003ccommand\u003e [\u003cargs\u003e ...]\n\nAn example implementation of curl.\n\nFlags:\n  --help            Show help.\n  -t, --timeout=5s  Set connection timeout.\n  -H, --headers=HEADER=VALUE\n                    Add HTTP headers to the request.\n\nCommands:\n  help [\u003ccommand\u003e...]\n  get [\u003cflags\u003e]\n    url \u003curl\u003e\n    file \u003cfile\u003e\n  post [\u003cflags\u003e] \u003curl\u003e\n```\n","funding_links":["https://github.com/sponsors/alecthomas"],"categories":["Go","命令行工具","Misc","Command Line","命令行","Uncategorized","\u003cspan id=\"命令行-command-line\"\u003e命令行 Command Line\u003c/span\u003e","命令行工具### 标准 CLI`用于创建一个标准命令行应用程序的库`","Repositories","Build Automation","Go 🐹"],"sub_categories":["标准 CLI","Standard CLI","标准CLI","Uncategorized","標準命令行交互","标准命令行交互"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falecthomas%2Fkingpin","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falecthomas%2Fkingpin","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falecthomas%2Fkingpin/lists"}