MCPcopy
hub / github.com/alecthomas/kong

github.com/alecthomas/kong @v1.15.0 sqlite

repository ↗ · DeepWiki ↗ · release v1.15.0 ↗
926 symbols 3,039 edges 50 files 264 documented · 29%
README

Kong is a command-line parser for Go

CircleCI Go Report Card Slack chat

Version 1.0.0 Release

Kong has been stable for a long time, so it seemed appropriate to cut a 1.0 release.

There is one breaking change, #436, which should effect relatively few users.

Introduction

Kong aims to support arbitrarily complex command-line structures with as little developer effort as possible.

To achieve that, command-lines are expressed as Go types, with the structure and tags directing how the command line is mapped onto the struct.

For example, the following command-line:

shell rm [-f] [-r] <paths> ...
shell ls [<paths> ...]

Can be represented by the following command-line structure:

package main

import "github.com/alecthomas/kong"

var CLI struct {
  Rm struct {
    Force     bool `help:"Force removal."`
    Recursive bool `help:"Recursively remove files."`

    Paths []string `arg:"" name:"path" help:"Paths to remove." type:"path"`
  } `cmd:"" help:"Remove files."`

  Ls struct {
    Paths []string `arg:"" optional:"" name:"path" help:"Paths to list." type:"path"`
  } `cmd:"" help:"List paths."`
}

func main() {
  ctx := kong.Parse(&CLI)
  switch ctx.Command() {
  case "rm <path>":
  case "ls":
  default:
    panic(ctx.Command())
  }
}

Help

Help as a user of a Kong application

Every Kong application includes a --help flag that will display auto-generated help.

eg.

$ shell --help
usage: shell <command>

A shell-like example app.

Flags:
  --help   Show context-sensitive help.
  --debug  Debug mode.

Commands:
  rm <path> ...
    Remove files.

  ls [<path> ...]
    List paths.

If a command is provided, the help will show full detail on the command including all available flags.

eg.

$ shell --help rm
usage: shell rm <paths> ...

Remove files.

Arguments:
  <paths> ...  Paths to remove.

Flags:
      --debug        Debug mode.

  -f, --force        Force removal.
  -r, --recursive    Recursively remove files.

Defining help in Kong

Help is automatically generated from the command-line structure itself, including help:"" and other tags. Variables will also be interpolated into the help string.

Finally, any command, or argument type implementing the interface Help() string will have this function called to retrieve more detail to augment the help tag. This allows for much more descriptive text than can fit in Go tags. See _examples/shell/help

Showing the command's detailed help

A command's additional help text is not shown from top-level help, but can be displayed within contextual help:

Top level help

 $ go run ./_examples/shell/help --help
Usage: help <command>

An app demonstrating HelpProviders

Flags:
  -h, --help    Show context-sensitive help.
      --flag    Regular flag help

Commands:
  echo    Regular command help

Contextual

 $ go run ./_examples/shell/help echo --help
Usage: help echo <msg>

Regular command help

🚀 additional command help

Arguments:
  <msg>    Regular argument help

Flags:
  -h, --help    Show context-sensitive help.
      --flag    Regular flag help

Showing an argument's detailed help

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

Contextual argument help

 $ go run ./_examples/shell/help msg --help
Usage: help echo <msg>

Regular argument help

📣 additional argument help

Flags:
  -h, --help    Show context-sensitive help.
      --flag    Regular flag help

Command handling

There are two ways to handle commands in Kong.

Switch on the command string

When you call kong.Parse() it will return a unique string representation of the command. Each command branch in the hierarchy will be a bare word and each branching argument or required positional argument will be the name surrounded by angle brackets. Here's an example:

There's an example of this pattern here.

eg.

package main

import "github.com/alecthomas/kong"

var CLI struct {
  Rm struct {
    Force     bool `help:"Force removal."`
    Recursive bool `help:"Recursively remove files."`

    Paths []string `arg:"" name:"path" help:"Paths to remove." type:"path"`
  } `cmd:"" help:"Remove files."`

  Ls struct {
    Paths []string `arg:"" optional:"" name:"path" help:"Paths to list." type:"path"`
  } `cmd:"" help:"List paths."`
}

func main() {
  ctx := kong.Parse(&CLI)
  switch ctx.Command() {
  case "rm <path>":
  case "ls":
  default:
    panic(ctx.Command())
  }
}

This has the advantage that it is convenient, but the downside that if you modify your CLI structure, the strings may change. This can be fragile.

Attach a Run(...) error method to each command

A more robust approach is to break each command out into their own structs:

  1. Break leaf commands out into separate structs.
  2. Attach a Run(...) error method to all leaf commands.
  3. Call kong.Kong.Parse() to obtain a kong.Context.
  4. Call kong.Context.Run(bindings...) to call the selected parsed command.

Once a command node is selected by Kong it will search from that node back to the root. Each encountered command node with a Run(...) error will be called in reverse order. This allows sub-trees to be re-used fairly conveniently.

In addition to values bound with the kong.Bind(...) option, any values passed through to kong.Context.Run(...) are also bindable to the target's Run() arguments.

Finally, hooks can also contribute bindings via kong.Context.Bind() and kong.Context.BindTo().

There's a full example emulating part of the Docker CLI here.

eg.

type Context struct {
  Debug bool
}

type RmCmd struct {
  Force     bool `help:"Force removal."`
  Recursive bool `help:"Recursively remove files."`

  Paths []string `arg:"" name:"path" help:"Paths to remove." type:"path"`
}

func (r *RmCmd) Run(ctx *Context) error {
  fmt.Println("rm", r.Paths)
  return nil
}

type LsCmd struct {
  Paths []string `arg:"" optional:"" name:"path" help:"Paths to list." type:"path"`
}

func (l *LsCmd) Run(ctx *Context) error {
  fmt.Println("ls", l.Paths)
  return nil
}

var cli struct {
  Debug bool `help:"Enable debug mode."`

  Rm RmCmd `cmd:"" help:"Remove files."`
  Ls LsCmd `cmd:"" help:"List paths."`
}

func main() {
  ctx := kong.Parse(&cli)
  // Call the Run() method of the selected parsed command.
  err := ctx.Run(&Context{Debug: cli.Debug})
  ctx.FatalIfErrorf(err)
}

Hooks: BeforeReset(), BeforeResolve(), BeforeApply(), AfterApply()

If a node in the CLI, or any of its embedded fields, implements a BeforeReset(...) error, BeforeResolve (...) error, BeforeApply(...) error and/or AfterApply(...) error method, those will be called as Kong resets, resolves, validates, and assigns values to the node.

Hook Description
BeforeReset Invoked before values are reset to their defaults (as defined by the grammar) or to zero values
BeforeResolve Invoked before resolvers are applied to a node
BeforeApply Invoked before the traced command line arguments are applied to the grammar
AfterApply Invoked after command line arguments are applied to the grammar and validated`

The --help flag is implemented with a BeforeReset hook.

eg.

// A flag with a hook that, if triggered, will set the debug loggers output to stdout.
type debugFlag bool

func (d debugFlag) BeforeApply(logger *log.Logger) error {
  logger.SetOutput(os.Stdout)
  return nil
}

var cli struct {
  Debug debugFlag `help:"Enable debug logging."`
}

func main() {
  // Debug logger going to discard.
  logger := log.New(io.Discard, "", log.LstdFlags)

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

  // ...
}

It's also possible to register these hooks with the functional options kong.WithBeforeReset, kong.WithBeforeResolve, kong.WithBeforeApply, and kong.WithAfterApply.

The Bind() option

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

eg:

type CLI struct {
  Debug bool `help:"Enable debug mode."`

  Rm RmCmd `cmd:"" help:"Remove files."`
  Ls LsCmd `cmd:"" help:"List paths."`
}

type AuthorName string

// ...
func (l *LsCmd) Run(cli *CLI) error {
// use cli.Debug here !!
  return nil
}

func (r *RmCmD) Run(author AuthorName) error{
// use binded author here
  return nil
}

func main() {
  var cli CLI

  ctx := kong.Parse(&cli, Bind(AuthorName("penguin")))
  err := ctx.Run()

Flags

Any mapped field in the command structure not tagged with cmd or arg will be a flag. Flags are optional by default.

eg. The command-line app [--flag="foo"] can be represented by the following.

type CLI struct {
  Flag string
}

Commands and sub-commands

Sub-commands are specified by tagging a struct field with cmd. Kong supports arbitrarily nested commands.

eg. The following struct represents the CLI structure command [--flag="str"] sub-command.

type CLI struct {
  Command struct {
    Flag string

    SubCommand struct {
    } `cmd`
  } `cmd`
}

If a sub-command is tagged with default:"1" it will be selected if there are no further arguments. 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.

Branching positional arguments

In addition to sub-commands, structs can also be configured as branching positional arguments.

This is achieved by tagging an unmapped nested struct field with arg, then including a positional argument field inside that struct with the same name. For example, the following command structure:

app rename <name> to <name>

Can be represented with the following:

var CLI struct {
  Rename struct {
    Name struct {
      Name string `arg` // <-- NOTE: identical name to enclosing struct field.
      To struct {
        Name struct {
          Name string `arg`
        } `arg`
      } `cmd`
    } `arg`
  } `cmd`
}

Thi

Extension points exported contracts — how you extend this code

AfterApply (Interface)
AfterApply is a documentation-only interface describing hooks that run after values are set. [8 implementers]
hooks.go
MapperValue (Interface)
MapperValue may be implemented by fields in order to provide custom mapping. Mappers may additionally implement PlaceHol [13 …
mapper.go
HelpProvider (Interface)
HelpProvider can be implemented by commands/args to provide detailed help. [4 implementers]
help.go
Option (Interface)
An Option applies optional changes to the Kong application. [4 implementers]
options.go
Signature (Interface)
Signature allows flags, args and commands to supply a default set of tags, that can be overridden by the field itself. [4 …
tag.go
Visitable (Interface)
A Visitable component in the model. [2 implementers]
model.go
Resolver (Interface)
A Resolver resolves a Flag value from an external source. [2 implementers]
resolver.go
ExitCoder (Interface)
ExitCoder is an interface that may be implemented by an error value to provide an integer exit code. The method ExitCode [1 …
exit.go

Core symbols most depended-on inside this repo

Parse
called by 325
kong.go
Errorf
called by 109
kong.go
String
called by 82
tag.go
New
called by 69
kong.go
Exit
called by 37
options.go
Writers
called by 36
options.go
Summary
called by 26
model.go
Pop
called by 25
scanner.go

Shape

Function 428
Method 281
Struct 156
TypeAlias 27
Interface 23
FuncType 11

Languages

Go100%

Modules by API surface

kong_test.go225 symbols
_examples/docker/commands.go82 symbols
mapper.go63 symbols
mapper_test.go59 symbols
context.go59 symbols
options.go52 symbols
help.go43 symbols
model.go38 symbols
resolver_test.go27 symbols
scanner.go26 symbols
options_test.go25 symbols
kong.go23 symbols

Dependencies from manifests, versioned

github.com/alecthomas/assert/v2v2.11.0 · 1×
github.com/alecthomas/colourv0.1.0 · 1×
github.com/alecthomas/reprv0.5.2 · 1×
github.com/anmitsu/go-shlexv0.0.0-2020051411343 · 1×
github.com/chzyer/logexv1.2.1 · 1×
github.com/chzyer/readlinev1.5.1 · 1×
github.com/chzyer/testv1.0.0 · 1×
github.com/creack/ptyv1.1.7 · 1×
github.com/flynn/go-shlexv0.0.0-2015051514535 · 1×

For agents

$ claude mcp add kong \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact