console

package module
v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 14 Imported by: 1 module, 7 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Go Reference CI Go Report Card

Console

Console is a handy package to build console commands in Go. It turns a set of commands into a command line application, with flags that come from the command line or from the environment, commands organized in groups and subgroups, and a help of its own for every level.

Features:

  • Flags identified by a long name (--flag), a short name (-f) and an environment variable — each one optional, and only the defined ones are enabled
  • Environment variables as a fallback, so commands never read os.Getenv themselves
  • GNU-style parsing: --flag value, --flag=value, -f value, -f=value, -fvalue, combined booleans (-af) and --
  • Commands organized in groups and subgroups, each with flags of its own: kubectl --username=admin pods --all list
  • A generated help for every group, subgroup and command, which you can override
  • Separate writers for the regular output and for the errors
  • Posix exit statuses
  • An optional lifecycle for the service providers of danceable/provider

Documentation

Required Go Versions

It requires Go v1.26 or newer versions.

Installation

To install this package, run the following command in your project directory.

go get github.com/danceable/console

Next, include it in your application:

import "github.com/danceable/console"
Introduction

A command is any type that implements the Command interface:

type Command interface {
    Name() string
    Description() string
    Usage() string
    Configure(*console.FlagSet)
    Run(context.Context) console.ExitStatus
}

Configure defines the flags of the command and Run does its work. The console parses the arguments, routes them to the command they name and returns the exit status the command returns.

Quick Start
func main() {
    ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill)
    defer cancel()

    c := console.NewConsole(
        path.Base(os.Args[0]),
        "the application.",
        os.Stdout,
        os.Stderr,
        provider.Default,
    )

    c.Register(blog.NewServeCommand())

    code := c.Run(ctx, os.Args)

    cancel()
    os.Exit(code)
}
Examples
Implementing a Command
type ServeCommand struct {
    port int
}

func (c *ServeCommand) Name() string        { return "serve" }
func (c *ServeCommand) Description() string { return "serves a http server." }
func (c *ServeCommand) Usage() string       { return "serve [flags]" }

func (c *ServeCommand) Configure(flagSet *console.FlagSet) {
    console.Var(
        flagSet,
        &c.port,
        console.Long("port"),
        "specifies which port server should listen to.",
        console.Short("p"),
        console.Env("SERVER_PORT"),
        console.Default(80),
    )
}

func (c *ServeCommand) Run(ctx context.Context) console.ExitStatus {
    if err := http.ListenAndServe(fmt.Sprintf(":%d", c.port), nil); err != nil {
        return console.ExitFailure
    }

    return console.ExitSuccess
}
Flags

A flag is identified by any combination of a long name, a short name and an environment variable name. Each of them is optional, but at least one of them has to be defined, and only the defined ones are enabled: a flag without a short name can't be provided as -f, and a flag which defines no environment variable never looks at the environment.

// provided as "--port 80", "--port=80", "-p 80", "-p=80" or "-p80",
// and loaded from SERVER_PORT when it is not provided at all.
console.Var(flagSet, &port, console.Long("port"), "the port to listen to.", console.Short("p"), console.Env("SERVER_PORT"), console.Default(80))

// long name only: "--username=admin".
console.Var(flagSet, &username, console.Long("username"), "the user to authenticate as.")

// environment variable only: it can't be provided on the command line at all.
console.Var(flagSet, &secret, console.Env("SIGNING_SECRET"), "the signing secret.")

A flag is defined by the name it leads with, which is why it is a parameter of Var rather than an option: a flag which names none of the three could never be provided. The other names it answers to are options, along with the value it defaults to.

The command line always wins over the environment. An environment variable which is empty or undefined is ignored, so the flag keeps its default value.

Syntax Description
--flag value Long name, the value is the next argument.
--flag=value Long name, inline value.
-f value Short name, the value is the next argument.
-f=value, -fvalue Short name, attached value.
--flag, -f A boolean flag, which takes no value.
--flag=false A boolean flag with an explicit value.
-af Combined boolean short names.
-- Ends the flag parsing.

Parsing stops right before the first non-flag argument (or --), and everything which follows is available through flagSet.Args(). That is what lets the arguments of a subgroup, of a command and of their own flags stay untouched.

Flag types

console.Var takes the type of the variable it binds a flag to, so there is one way to define a flag whatever it holds:

console.Var(flagSet, &port, console.Long("port"), "the port to listen to.", console.Default(80))
console.Var(flagSet, &timeout, console.Long("timeout"), "the request timeout.", console.Default(10*time.Second))

Each type is registered once with the parser which reads it, and every flag and every struct field of that type is then parsed by it. The Go types are registered by the package itself:

Type Shown as Reads
string string the argument as it is
bool (nothing, it takes no value) true, false, 1, 0, t, f
int, int8, int16, int32, int64 int 42, -42, 0x2a, 0b101010, 0o52
uint, uint8, uint16, uint32, uint64 uint the same, without a sign
float32, float64 float 1.5, -1.5, 1e3
time.Duration duration 300ms, 1.5h, 2h45m

A type of your own is registered the same way, which is all it takes for it to be usable as a flag and as a struct field:

console.Register(console.Type[net.IP]{
    Name:    "ip",
    Expects: "an IP address",
    Parse: func(argument string) (net.IP, error) {
        if ip := net.ParseIP(argument); ip != nil {
            return ip, nil
        }

        return nil, errors.New("invalid address")
    },
})

var bind net.IP
console.Var(flagSet, &bind, console.Long("bind"), "the address to bind to.", console.Default(net.IPv4zero))
Field Description
Parse The parser of the type, which is the only field it has to define. The parsing functions of the standard library (strconv.ParseBool, time.ParseDuration, net.ParseMAC) are already of that shape.
Name The name of the type in the help, as the int of --port int. A type which names itself with nothing is shown as a value.
Expects What the type accepts, as an integer. Every value the parser rejects is explained with it (can't be parsed as an integer), except the ones it rejects as out of range. A type which leaves it empty reports the error of its parser as it is.
Format The string form of a value, which the help shows the default as. Defaults to the one the fmt package gives it.
Implicit The value the flag takes when it is provided without one, the way a boolean is provided as --verbose. Such a flag never consumes the argument which follows it. A type which leaves it empty requires a value.

Registering a type twice replaces the first registration, which is how a Go type is given parsing rules of your own. A type is normally registered from an init function: a flag is bound to its type when it is defined, so a flag which is already defined keeps the parsing it was defined with.

A flag defaults to the value its variable already holds, which console.Default overrides:

port := 80
console.Var(flagSet, &port, console.Long("port"), "the port to listen to.")
console.Var(flagSet, &retries, console.Long("retries"), "the number of retries.", console.Default(3))

A default value reaches its flag the way an untyped constant reaches a variable it is assigned to, so console.Default(0) is the zero of whatever number the flag holds. One the flag could never hold, because it is of another class of types or because it would overflow or be truncated to reach it, panics when the flag is defined.

A flag whose default value is the zero value of its type is not presented with a default in the help, and a value the parser rejects leaves the variable untouched, so a flag provided with an invalid value keeps its default.

Flags from a struct

A whole set of flags is defined at once from a tagged struct, which keeps the configuration of an application in a single place:

type configs struct {
    AppEnv  string `usage:"the deployment environment." env:"APP_ENV"`
    NodeEnv string `usage:"a fallback for APP_ENV." env:"NODE_ENV"`

    PostgresHost     string `usage:"the host." env:"POSTGRES_HOST" long:"postgres-host" short:"H" default:"localhost"`
    PostgresPort     int    `usage:"the port." env:"POSTGRES_PORT" long:"postgres-port" short:"P" default:"5432"`
    PostgresPassword string `usage:"the password." env:"POSTGRES_PASSWORD" long:"postgres-password" default:"-"`
}

configuration := &configs{}

configure, err := console.StructFlags(configuration)
if err != nil {
    log.Fatal(err)
}

console.NewConsole("app", "controls the app.", os.Stdout, os.Stderr, provider.Default).Flags(configure)

StructFlags validates the struct and returns the configure function of a console, of a group or of a command, so a mistake in the tags surfaces when the console is built rather than when it reaches the level the flags belong to. flagSet.Struct(&configuration) binds a struct onto a flag set directly.

Every tag is optional and their order is irrelevant. A field which carries none of them is not a flag and is left alone, while a field which carries any of them has to be reachable, which means naming at least one of long, short and env:

Tag Description
usage:"..." The usage message of the flag.
long:"name" The long name, provided as --name.
short:"n" The short (single character) name, provided as -n.
env:"NAME" The environment variable the flag falls back to.
default:"..." The default value of the flag.

A field is of any registered type, which the Go types are out of the box, or of a type whose pointer implements Value and carries its own parsing.

Default values

The default value of a flag is the value its field already holds, even when it is the zero value of its type, so a struct is given its defaults by being populated before it is bound:

configuration := &configs{PostgresHost: "localhost", PostgresPort: 5432}

A default tag overrides that value, and default:"-" drops it: the field is reset to the zero value of its type whatever the struct holds, and the help shows no default for it. A default tag goes through the flag's own parser, so it is reported as an error when the type of the field cannot read it.

Nested and embedded structs

Nested and embedded structs are flattened into the same flag set, which lets the settings of a subsystem live in a struct of their own. No name is derived from the field a struct is nested in: a nested field names its flag the way a field of the outer struct does. A nil pointer to a struct is allocated to hold its flags.

type postgres struct {
    Host string `usage:"the host." long:"postgres-host" env:"POSTGRES_HOST"`
    Port int    `usage:"the port." long:"postgres-port" default:"5432"`
}

type configs struct {
    common                     // embedded, flattened in as well.
    Verbose  bool     `usage:"verbose output." long:"verbose" short:"v"`
    Postgres postgres // nested, its own fields become flags.
    Redis    *redis   // allocated when it is nil.
}

A struct which is nested is never a flag itself, so it carries no flag tag of its own. A type which parses itself, by implementing Value, is a flag rather than a struct to recurse into.

Errors

Binding is all or nothing: the struct is resolved and validated before the first flag is defined, so a rejected struct leaves both the flag set and the values of the struct untouched. The error is a *FieldError, which names the offending field and wraps the reason:

Error Returned for
ErrNotStruct A target which is not a non nil pointer to a struct.
ErrNoName A tagged field which names none of long, short and env.
ErrInvalidName A short name longer than a character, or a long name the parser could never match.
ErrDuplicateName A name two fields claim, or a name the flag set already holds.
ErrInvalidDefault A default tag the type of the field cannot be parsed from.
ErrUnsupportedType A tagged field of a type no flag can be defined for.
ErrUnexportedField A tagged field which cannot be addressed.
ErrNestedTags A nested or an embedded struct carrying flag tags of its own.
ErrRecursiveType A struct which nests itself.
var fieldError *console.FieldError
if errors.As(err, &fieldError) {
    log.Fatalf("the field %s cannot be a flag: %s", fieldError.Field, fieldError.Err)
}
Groups and subgroups

Commands are optionally organized in groups and subgroups. A group is not runnable by itself: it routes to the command (or to the subgroup) which is named right after it, and it can define flags of its own.

nodes := console.NewGroup("nodes", "manages the nodes of the pods.").
    Register(node.NewListCommand())

pods := console.NewGroup("pods", "manages the pods.").
    Flags(func(flagSet *console.FlagSet) {
        console.Var(flagSet, &all, console.Long("all"), "targets every namespace.", console.Short("a"))
    }).
    Register(pod.NewListCommand()).
    RegisterGroup(nodes)

c.Flags(func(flagSet *console.FlagSet) {
    console.Var(flagSet, &username, console.Long("username"), "the user to authenticate as.", console.Short("u"))
})
c.RegisterGroup(pods)

Which accepts:

kubectl --username=admin pods --all list
        └ console flags   └ group
                               └ group flags
                                      └ command

kubectl pods nodes list
        └ group
             └ subgroup
                   └ command

The flags of each level are parsed before the name of the next one, so a command can rely on the flags of the groups it belongs to being already loaded. A flag is only known by the level it is defined on: --all is a usage error before pods, and --username is one after it.

Help

Every group, subgroup and command answers --help (or -h) with a help of its own, listing its subgroups, its commands and its flags. Subgroups, commands and flags are all listed in alphabetical order, whatever the order they were defined in:

$ kubectl pods --help
manages the pods.

Usage:

  kubectl pods [flags] <command> [command arguments]

The command groups are:

  nodes       manages the nodes of the pods.

The commands are:

  list        lists the pods.

Flags:

  -a, --all   targets the pods of every namespace.
  -h, --help  shows this help message.

Use "kubectl pods <command> --help" for more information about a command.

WithUsage overrides the usage line of the generated help, and WithHelp replaces the whole help with a text of your own:

console.NewGroup("pods", "manages the pods.").
    WithUsage("kubectl pods [flags] <command>").
    WithHelp("a totally custom help.")
Writers

NewConsole takes two writers. A requested help is written to the first one (normally os.Stdout), while everything which goes along with a non successful exit status — a usage error, the help which follows it, a failing service — is written to the second one (normally os.Stderr):

$ kubectl --help | less        # the help is on the standard output
$ kubectl --bogus 2>/dev/null  # the usage error is on the standard error

Passing nil for either one falls back to os.Stdout and os.Stderr.

Service providers

A command which also implements the Service interface gets the service providers of danceable/provider registered, booted and terminated around its run:

type Service interface {
    Providers() []provider.Provider
}

Every provider is registered and booted before the command runs, and they are terminated gracefully once the command returns or the context is cancelled. A provider which fails to register or to boot stops the command, which exits with ExitFailure.

func (c *ServeCommand) Providers() []provider.Provider {
    return [
        NewMySQLProvider(),
        NewNATSProvider(),
    ]
}
Exit Statuses
Status Value Description
ExitSuccess 0 The command succeeded, or a help was requested.
ExitFailure 1 The command failed, or its service providers failed to boot.
ExitUsageError 2 The arguments don't name a command, or a flag is invalid.
Console Methods
Method Signature Description
NewConsole NewConsole(name, description string, writer, errWriter io.Writer, manager *provider.Manager) *Console Creates a console which writes its output to writer and its errors to errWriter.
Register Register(commands ...Command) *Console Registers commands.
RegisterGroup RegisterGroup(groups ...*Group) *Console Registers groups of commands.
Flags Flags(configure func(*FlagSet)) *Console Defines the global flags, provided before the name of the first group or command.
WithUsage WithUsage(usage string) *Console Overrides the usage line of the help.
WithHelp WithHelp(help string) *Console Overrides the whole help.
Run Run(ctx context.Context, arguments []string) ExitStatus Routes the arguments to a command and runs it.
Writer Writer() io.Writer The writer the regular output is written to.
ErrWriter ErrWriter() io.Writer The writer the errors are written to.
Group Methods
Method Signature Description
NewGroup NewGroup(name, description string) *Group Creates a group of commands.
Register Register(commands ...Command) *Group Registers commands in the group.
RegisterGroup RegisterGroup(groups ...*Group) *Group Registers subgroups in the group.
Flags Flags(configure func(*FlagSet)) *Group Defines the flags of the group, provided right after its name.
WithUsage WithUsage(usage string) *Group Overrides the usage line of the group's help.
WithHelp WithHelp(help string) *Group Overrides the whole help of the group.
Commands Commands() []string The names of the registered commands, in alphabetical order.
Groups Groups() []string The names of the registered subgroups, in alphabetical order.
Flag Names and Options

A FlagName is what a flag is defined by, and any of them may also be given as an option, to name a flag by more than one:

Name Description
Long(name) The long name of the flag, provided as --name.
Short(name) The short (single character) name of the flag, provided as -n.
Env(name) The environment variable the flag falls back to when it is not provided.
Option Description
Long, Short, Env The other names the flag answers to.
Default(value) The value the flag defaults to, which is otherwise the value its variable already holds.

Defining a flag with a nameless name, with a short name longer than a character, or with a name which is already taken, panics: those are wiring mistakes rather than user input errors.

FlagSet Methods
Method Signature Description
Var Var(value Value, name FlagName, usage string, options ...FlagOption) *Flag Defines a flag with a value of your own. A flag of a registered type is defined with the console.Var function, as Go has no generic methods.
Struct Struct(target any) error Defines one flag per tagged field of a struct.
Parse Parse(arguments []string) error Parses the flags, then loads the missing ones from the environment.
Args, Arg, NArg Args() []string The arguments which follow the flags.
Lookup Lookup(name string) *Flag The flag defined with the given long, short or environment variable name.
Flags Flags() []*Flag The defined flags, in definition order.
PrintDefaults PrintDefaults(w io.Writer) Writes the flags as they appear in a help, in alphabetical order.

A value of your own implements Value, which is what a flag holds whatever its type. Registering a flag type is the way to parse a Go type, and implementing Value is the way for a type to parse itself:

type Value interface {
    String() string
    Set(string) error
}

It may implement any of the optional methods a registered type describes with a field:

Method Description
Type() string Names the type of the value in the help.
ImplicitValue() (string, bool) The value the flag takes when it is provided without one, and whether it takes one at all.
IsBoolFlag() bool The boolean only form of ImplicitValue, which takes true.
Zero() string The string form of the zero value of the type, which the help doesn't mention as a default.
Interfaces
Interface Methods Description
Command Name(), Description(), Usage(), Configure(*FlagSet), Run(ctx) A single command of the console.
Service Providers() Optional interface for a command whose service providers are managed around its run.
Value String(), Set(string) The dynamic value stored in a flag.
Package Functions
Function Signature Description
NewConsole NewConsole(name, description string, writer, errWriter io.Writer, manager *provider.Manager) *Console A new console.
NewGroup NewGroup(name, description string) *Group A new group of commands.
NewFlagSet NewFlagSet(name string, errWriter io.Writer) *FlagSet A new set of flags.
Var Var[T any](flagSet *FlagSet, p *T, name FlagName, usage string, options ...FlagOption) *Flag Defines a flag of the type of the variable it stores its value in, named by the name it is provided by.
Default Default[T any](value T) FlagOption The value a flag defaults to.
Register Register[T any](flagType Type[T]) Registers how the flags of a Go type are parsed and presented.
StructFlags StructFlags(target any) (func(*FlagSet), error) The configure function of a tagged struct, validated up front.

License

MIT

Documentation

Overview

Package console builds command line applications out of commands, which are optionally organized in groups and subgroups.

Commands

A command implements the Command interface. It defines its flags in Configure and does its work in Run:

app := console.NewConsole(path.Base(os.Args[0]), "the application.", os.Stdout, os.Stderr, provider.Default)
app.Register(blog.NewServeCommand())

os.Exit(app.Run(ctx, os.Args))

A requested help is written to the first writer, while a usage error (and the help which follows it) is written to the second one.

A command which also implements Service gets its service providers registered, booted and terminated around its run.

Flags

A flag is identified by any combination of a long name (--flag), a short name (-f) and an environment variable name. Each of them is optional and only the defined ones are enabled, so a flag without a short name can't be provided as "-f" and a flag which defines no environment variable never looks at the environment:

func (c *ServeCommand) Configure(flagSet *console.FlagSet) {
	console.Var(flagSet, &c.port, console.Long("port"), "the port to listen to.", console.Short("p"), console.Env("SERVER_PORT"), console.Default(80))
}

A flag is defined by the name it leads with, which is a parameter of Var rather than an option: a flag which names none of the three could never be provided. The other names it answers to are options, along with the value it defaults to, which is otherwise the value its variable already holds.

Such a flag is provided as "--port 80", "--port=80", "-p 80", "-p=80" or "-p80". When it is not provided at all, its value is loaded from the SERVER_PORT environment variable, and when that one is empty or undefined, the flag keeps its default value.

Boolean flags take no value ("--all"), may be combined ("-af") and are the only flags which don't consume the argument which follows them. Everything after the first non-flag argument or after "--" is left untouched and is available through FlagSet.Args.

Flag types

A flag takes the type of the variable it is bound to, and that type is what says how its values are parsed, formatted and presented. The Go types are registered by the package itself: the strings, the booleans, the signed and unsigned integers, the floating point numbers and time.Duration.

A type of your own is registered with Register, which is all it takes for it to be usable as a flag and as a struct field:

console.Register(console.Type[net.IP]{
	Name:    "ip",
	Expects: "an IP address",
	Parse: func(argument string) (net.IP, error) {
		if ip := net.ParseIP(argument); ip != nil {
			return ip, nil
		}

		return nil, errors.New("invalid address")
	},
})

A type which parses itself, by implementing Value, is defined as a flag with FlagSet.Var instead.

Groups

Commands are optionally organized in groups and subgroups, each one having its own flags and its own help:

pods := console.NewGroup("pods", "manages the pods.").
	Flags(func(flagSet *console.FlagSet) {
		console.Var(flagSet, &all, console.Long("all"), "targets every namespace.", console.Short("a"))
	}).
	Register(pod.NewListCommand()).
	RegisterGroup(nodes)

console.Flags(func(flagSet *console.FlagSet) {
	console.Var(flagSet, &username, console.Long("username"), "the user to authenticate as.", console.Short("u"))
})
console.RegisterGroup(pods)

Which accepts:

app --username=admin pods --all list
    └ console flags  └ group
                          └ group flags
                                 └ command

The flags of each level are parsed before the name of the next one, so a command can rely on the flags of the groups it belongs to being already loaded. A flag is only known by the level it is defined on: "--all" is a usage error before "pods" and "--username" is one after it.

Every group answers "--help" (or "-h") with its own help, listing its subgroups, its commands and its flags. Group.WithUsage overrides the usage line of the generated help and Group.WithHelp replaces the whole help with a text of your own.

Example
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/danceable/provider"

	"github.com/danceable/console"
)

// listCommand lists the pods of a cluster.
type listCommand struct {
	all   *bool
	limit int
}

func (c *listCommand) Name() string        { return "list" }
func (c *listCommand) Description() string { return "lists the pods." }
func (c *listCommand) Usage() string       { return "kubectl pods list [flags]" }

func (c *listCommand) Configure(flagSet *console.FlagSet) {
	console.Var(
		flagSet,
		&c.limit,
		console.Long("limit"),
		"the maximum number of pods to show.",
		console.Short("l"),
		console.Env("KUBECTL_LIMIT"),
		console.Default(10),
	)
}

func (c *listCommand) Run(ctx context.Context) console.ExitStatus {
	fmt.Printf("listing at most %d pods (every namespace: %t)\n", c.limit, *c.all)

	return console.ExitSuccess
}

// kubectl builds a console which routes "kubectl pods list" to the list
// command, with a flag on the group and a flag on the command.
func kubectl(all *bool) *console.Console {
	pods := console.NewGroup("pods", "manages the pods.").
		Flags(func(flagSet *console.FlagSet) {
			console.Var(flagSet, all, console.Long("all"), "targets the pods of every namespace.", console.Short("a"))
		}).
		Register(&listCommand{all: all})

	c := console.NewConsole("kubectl", "controls the cluster manager.", os.Stdout, os.Stderr, provider.Default)
	c.RegisterGroup(pods)

	return c
}

func main() {
	var all bool

	// the flags of each level are parsed before the name of the next one.
	kubectl(&all).Run(context.Background(), []string{"kubectl", "pods", "--all", "list", "-l", "5"})

}
Output:
listing at most 5 pods (every namespace: true)
Example (Help)
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/danceable/provider"

	"github.com/danceable/console"
)

// listCommand lists the pods of a cluster.
type listCommand struct {
	all   *bool
	limit int
}

func (c *listCommand) Name() string        { return "list" }
func (c *listCommand) Description() string { return "lists the pods." }
func (c *listCommand) Usage() string       { return "kubectl pods list [flags]" }

func (c *listCommand) Configure(flagSet *console.FlagSet) {
	console.Var(
		flagSet,
		&c.limit,
		console.Long("limit"),
		"the maximum number of pods to show.",
		console.Short("l"),
		console.Env("KUBECTL_LIMIT"),
		console.Default(10),
	)
}

func (c *listCommand) Run(ctx context.Context) console.ExitStatus {
	fmt.Printf("listing at most %d pods (every namespace: %t)\n", c.limit, *c.all)

	return console.ExitSuccess
}

// kubectl builds a console which routes "kubectl pods list" to the list
// command, with a flag on the group and a flag on the command.
func kubectl(all *bool) *console.Console {
	pods := console.NewGroup("pods", "manages the pods.").
		Flags(func(flagSet *console.FlagSet) {
			console.Var(flagSet, all, console.Long("all"), "targets the pods of every namespace.", console.Short("a"))
		}).
		Register(&listCommand{all: all})

	c := console.NewConsole("kubectl", "controls the cluster manager.", os.Stdout, os.Stderr, provider.Default)
	c.RegisterGroup(pods)

	return c
}

func main() {
	var all bool

	// every group answers "--help" with its own help.
	kubectl(&all).Run(context.Background(), []string{"kubectl", "pods", "--help"})

}
Output:
manages the pods.

Usage:

  kubectl pods [flags] <command> [command arguments]

The commands are:

  list        lists the pods.

Flags:

  -a, --all   targets the pods of every namespace.
  -h, --help  shows this help message.

Use "kubectl pods <command> --help" for more information about a command.
Example (ScopedFlags)
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/danceable/provider"

	"github.com/danceable/console"
)

// contextScope holds the value of a "--context" flag defined at one level of
// the console, together with the flag set it belongs to. Keeping the flag set
// is what lets a command tell an explicitly provided value apart from a
// default one, as the console builds a new flag set for every level and drops
// it once the level is parsed.
type contextScope struct {
	context string
	flagSet *console.FlagSet
}

// bind defines the "--context" flag of the level on the given flag set. Every
// level binds its own variable: two levels sharing one would overwrite each
// other, as a flag writes its default value when it is defined.
func (s *contextScope) bind(flagSet *console.FlagSet, defaultContext string) {
	s.flagSet = flagSet

	console.Var(flagSet, &s.context, console.Long("context"), "the context to work against.", console.Default(defaultContext))
}

// provided reports whether the flag was provided at this level.
func (s *contextScope) provided() bool {
	return s.flagSet != nil && s.flagSet.Lookup("context").Provided()
}

// given returns the value the level was provided with, or "-" when the level
// fell back to its default.
func (s *contextScope) given() string {
	if !s.provided() {
		return "-"
	}

	return s.context
}

// podsCommand resolves the context it runs against out of the three levels
// which define one.
type podsCommand struct {
	root  *contextScope
	group *contextScope
	own   *contextScope
}

func (c *podsCommand) Name() string        { return "pods" }
func (c *podsCommand) Description() string { return "gets the pods." }
func (c *podsCommand) Usage() string       { return "kubectl get pods [flags]" }

func (c *podsCommand) Configure(flagSet *console.FlagSet) {
	c.own.bind(flagSet, "minikube")
}

func (c *podsCommand) Run(ctx context.Context) console.ExitStatus {

	effective := c.root.context

	for _, scope := range []*contextScope{c.group, c.own} {
		if scope.provided() {
			effective = scope.context
		}
	}

	fmt.Printf("kubectl=%s get=%s pods=%s => %s\n", c.root.given(), c.group.given(), c.own.given(), effective)

	return console.ExitSuccess
}

// kubectlContexts builds a console where the root, the "get" group and the
// "pods" command each define their own "--context" flag.
func kubectlContexts() *console.Console {
	root, group, own := &contextScope{}, &contextScope{}, &contextScope{}

	get := console.NewGroup("get", "gets resources.").
		Flags(func(flagSet *console.FlagSet) { group.bind(flagSet, "staging") }).
		Register(&podsCommand{root: root, group: group, own: own})

	c := console.NewConsole("kubectl", "controls the cluster manager.", os.Stdout, os.Stderr, provider.Default)
	c.Flags(func(flagSet *console.FlagSet) { root.bind(flagSet, "default") })
	c.RegisterGroup(get)

	return c
}

func main() {
	// a flag set is built per level, so the same name may be defined at each
	// one of them without colliding: the three values live side by side.
	kubectlContexts().Run(context.Background(), []string{
		"kubectl", "--context=server-1", "get", "--context=staging", "pods", "--context=running",
	})

	// the levels which are not provided fall back to the closest one which was.
	kubectlContexts().Run(context.Background(), []string{
		"kubectl", "--context=server-1", "get", "pods",
	})

	// a group may be provided while the command it routes to is not.
	kubectlContexts().Run(context.Background(), []string{
		"kubectl", "get", "--context=staging", "pods",
	})

	// without any of them, the root's default applies.
	kubectlContexts().Run(context.Background(), []string{"kubectl", "get", "pods"})

}
Output:
kubectl=server-1 get=staging pods=running => running
kubectl=server-1 get=- pods=- => server-1
kubectl=- get=staging pods=- => staging
kubectl=- get=- pods=- => default

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotStruct is returned when the target is not a non nil pointer to a struct.
	ErrNotStruct = errors.New("console: the target must be a non nil pointer to a struct")

	// ErrNoName is returned for a tagged field which defines none of the
	// "long", "short" and "env" tags, leaving the flag unreachable.
	ErrNoName = errors.New("a tagged field needs at least one of the long, short and env tags")

	// ErrInvalidName is returned for a "long" or a "short" tag which names a
	// flag the parser could never match.
	ErrInvalidName = errors.New("invalid flag name")

	// ErrDuplicateName is returned when two fields, or a field and a flag which
	// is already defined, claim the same name.
	ErrDuplicateName = errors.New("duplicated flag name")

	// ErrUnexportedField is returned for a tagged field which cannot be addressed.
	ErrUnexportedField = errors.New("an unexported field cannot be bound to a flag")

	// ErrInvalidDefault is returned for a "default" tag the type of the field
	// cannot be parsed from.
	ErrInvalidDefault = errors.New("invalid default value")

	// ErrNestedTags is returned for a nested or an embedded struct which
	// carries flag tags of its own. Its fields are flattened into the flag
	// set, so the struct itself is never a flag.
	ErrNestedTags = errors.New("a nested struct is flattened into the flag set and cannot carry flag tags")

	// ErrRecursiveType is returned for a struct which nests itself.
	ErrRecursiveType = errors.New("recursive struct type")
)

The errors a struct which cannot be turned into flags is reported with. They are always wrapped in a FieldError, except ErrNotStruct which is about the target itself.

View Source
var ErrHelp = errors.New("console: help requested")

ErrHelp is the error returned when the help flag (-h or --help) is provided but no such flag is defined.

View Source
var ErrUnsupportedType = errors.New("unsupported type")

ErrUnsupportedType is returned for a variable of a type no flag can be defined for, which is a type that is neither registered nor parses itself.

Functions

func Register added in v1.3.0

func Register[T any](flagType Type[T])

Register registers the flag type of T, which every flag and every struct field of that type is then parsed by. The Go types are registered by the package itself, so registering is what a type of your own needs to be usable as a flag.

Registering a type twice replaces the first registration, which is how the parsing of a Go type is given rules of your own. A type is normally registered from an init function, before any flag is defined: a flag is bound to its type when it is defined, so a flag which is already defined keeps the parsing it was defined with.

It panics when the type defines no parser, as a definition error is a programming mistake rather than user input.

Example

Registering a type is what makes it usable as a flag: the parser is handed the argument, and the flag set writes what it returns into the variable the flag was defined with.

package main

import (
	"errors"
	"fmt"
	"os"
	"slices"

	"github.com/danceable/console"
)

// logLevel is a type of its own, whose flags are defined by registering how it
// is parsed rather than by writing a value for it.
type logLevel int

const (
	debugLevel logLevel = iota
	infoLevel
	errorLevel
)

// logLevels names the levels, in the order they are defined in.
var logLevels = []string{"debug", "info", "error"}

func (l logLevel) String() string { return logLevels[l] }

// parseLogLevel is the parser the level type is registered with.
func parseLogLevel(argument string) (logLevel, error) {
	if level := slices.Index(logLevels, argument); level >= 0 {
		return logLevel(level), nil
	}

	return 0, errors.New("unknown level")
}

func main() {
	console.Register(console.Type[logLevel]{
		Name:    "level",
		Expects: "a level (debug, info or error)",
		Parse:   parseLogLevel,
	})

	var level logLevel

	flagSet := console.NewFlagSet("app", os.Stdout)
	console.Var(flagSet, &level, console.Long("level"), "the level to log at.", console.Short("l"), console.Default(infoLevel))

	if err := flagSet.Parse([]string{"-l", "debug"}); err == nil {
		fmt.Println("logging at the", level, "level")
	}

	// a value the parser rejects is explained with what the type expects, and
	// leaves the flag with the value it already held.
	flagSet.Parse([]string{"--level=loud"})

	// the type names itself in the help, next to the default value of the flag.
	flagSet.PrintDefaults(os.Stdout)

}
Output:
logging at the debug level
invalid value "loud" for flag --level: can't be parsed as a level (debug, info or error)
  -l, --level level  the level to log at. (default info)
  -h, --help         shows this help message.

func StructFlags added in v1.1.0

func StructFlags(target any) (func(*FlagSet), error)

StructFlags builds the configure function of a struct, ready to be handed to Console.Flags, Group.Flags or a command's Configure method.

It validates the struct before returning, which surfaces a mistake in the tags at build time rather than when the console reaches the level the flags belong to. The returned function panics when the struct collides with a flag the set already defines, as any other duplicated definition does.

Types

type Command

type Command interface {
	// Name returns the command's name.
	Name() string

	// Description returns a short string (less than one line) describing the command.
	Description() string

	// Usage returns a long string explaining the command and giving usage information.
	Usage() string

	// Configure configures this command. The arguments which follow the flags
	// of the command are available through the flag set's Args method.
	Configure(*FlagSet)

	// Run attempts to run the command.
	Run(context.Context) ExitStatus
}

Command represents a single command.

type Console

type Console struct {
	// contains filtered or unexported fields
}

Console represents a set of commands, which are optionally organized in groups and subgroups.

func NewConsole

func NewConsole(name, description string, writer, errWriter io.Writer, manager *provider.Manager) *Console

NewConsole returns a new Console.

A requested help is written to writer, while everything which goes along with a non successful exit status (a usage error and the help which follows it, a failing service) is written to errWriter.

func (*Console) ErrWriter

func (c *Console) ErrWriter() io.Writer

ErrWriter returns the writer the errors are written to.

func (*Console) Flags

func (c *Console) Flags(configure func(*FlagSet)) *Console

Flags defines the global flags, which are provided before the name of the first group or command:

app --username=admin pods --all list

func (*Console) Register

func (c *Console) Register(commands ...Command) *Console

Register registers commands.

func (*Console) RegisterGroup

func (c *Console) RegisterGroup(groups ...*Group) *Console

RegisterGroup registers groups of commands.

func (*Console) Run

func (c *Console) Run(ctx context.Context, arguments []string) ExitStatus

Run attempts to invoke registered commands.

It walks through the groups the arguments point to, parsing the flags of each one of them on its way, until it reaches a command:

app --username=admin pods --all list --limit=10

func (*Console) WithHelp

func (c *Console) WithHelp(help string) *Console

WithHelp overrides the whole help of the console with the given text.

func (*Console) WithUsage

func (c *Console) WithUsage(usage string) *Console

WithUsage overrides the usage line which is shown in the console's help.

func (*Console) Writer

func (c *Console) Writer() io.Writer

Writer returns the writer the regular output is written to.

type ExitStatus

type ExitStatus = int

ExitStatus represents a Posix exit status that a command expects to be returned to the shell.

const (
	// ExitSuccess is the exit status for a successful command.
	ExitSuccess ExitStatus = 0

	// ExitFailure is the exit status for a failed command.
	ExitFailure ExitStatus = 1

	// ExitUsageError is the exit status for a usage error.
	ExitUsageError ExitStatus = 2
)

type FieldError added in v1.1.0

type FieldError struct {
	// Field is the name of the offending field.
	Field string

	// Err is the reason the field was rejected.
	Err error
}

FieldError reports the field of the target struct which cannot be turned into a flag, and why. It wraps one of the package's errors, so the reason is matched with errors.Is.

func (*FieldError) Error added in v1.1.0

func (e *FieldError) Error() string

func (*FieldError) Unwrap added in v1.1.0

func (e *FieldError) Unwrap() error

type Flag

type Flag struct {
	// contains filtered or unexported fields
}

Flag represents the state of a single flag.

A flag is identified by any combination of a long name (--flag), a short name (-f) and an environment variable name. Each of them is optional, but at least one of them has to be defined. Only the defined ones are enabled: a flag without a short name can't be provided as "-f", and a flag without an environment variable name never looks at the environment.

func Var added in v1.3.0

func Var[T any](flagSet *FlagSet, p *T, name FlagName, usage string, options ...FlagOption) *Flag

Var defines a flag of the type of the variable it stores its value in, which is where the parsed value is written:

var port int

console.Var(flagSet, &port, console.Long("port"), "the port to listen to.", console.Short("p"), console.Default(80))

A flag is defined by the name it is provided by, which is a Long name, a Short name or an Env variable. The other names it answers to are given as options, along with the value it defaults to.

The type of the variable has to be registered, which the Go types are by the package itself. Register is what a type of your own is made usable by, and a variable whose pointer implements Value carries its own parsing.

The flag defaults to the value the variable already holds, which a Default option overrides.

It panics when no flag can be defined for the type of the variable, as a definition error is a programming mistake rather than user input.

func (*Flag) DefValue

func (f *Flag) DefValue() string

DefValue returns the flag's default value as a string.

func (*Flag) Env

func (f *Flag) Env() string

Env returns the name of the environment variable the flag falls back to, if any.

func (*Flag) FromEnv

func (f *Flag) FromEnv() bool

FromEnv reports whether the flag's value was loaded from the environment.

func (*Flag) Long

func (f *Flag) Long() string

Long returns the flag's long name (without the leading "--"), if any.

func (*Flag) Provided

func (f *Flag) Provided() bool

Provided reports whether the flag was provided on the command line.

func (*Flag) Short

func (f *Flag) Short() string

Short returns the flag's short name (without the leading "-"), if any.

func (*Flag) Usage

func (f *Flag) Usage() string

Usage returns the flag's usage message.

func (*Flag) Value

func (f *Flag) Value() Value

Value returns the flag's value.

type FlagName added in v1.3.0

type FlagName interface {
	FlagOption
	// contains filtered or unexported methods
}

FlagName is a name a flag is reachable by: a long name, a short name or an environment variable. A flag which defines none of them can never be provided, which is why Var and FlagSet.Var take one apart from their options: the first name is what defines a flag, the other ones are optional.

func Env

func Env(name string) FlagName

Env defines the environment variable a flag falls back to when it is not provided on the command line. Empty environment variables are ignored.

func Long

func Long(name string) FlagName

Long defines the long name of a flag, which is provided as "--name".

func Short

func Short(name string) FlagName

Short defines the short (single character) name of a flag, which is provided as "-n".

type FlagOption

type FlagOption interface {
	// contains filtered or unexported methods
}

FlagOption defines an optional property of a flag, such as the value it defaults to or the other names it answers to.

func Default added in v1.3.0

func Default[T any](value T) FlagOption

Default defines the value a flag defaults to, which is otherwise the value its variable already holds:

console.Var(flagSet, &port, console.Long("port"), "the port to listen to.", console.Default(80))

The default value is written into the variable when the flag is defined, so the variable holds it until the flags are parsed, and the help presents it unless it is the zero value of its type.

A default value reaches a flag of another type the way an untyped constant reaches a variable, so Default(0) is the zero of whatever number the flag holds and Default(80) is a uint16 as readily as an int.

It panics when the default value cannot be the value of the flag, as a definition error is a programming mistake rather than user input. A flag which holds a value of your own takes no default: it keeps the one the value was built with.

type FlagSet

type FlagSet struct {
	// Usage is called when an error occurs while parsing flags. It is meant to
	// print the help of the command the flag set belongs to.
	Usage func()
	// contains filtered or unexported fields
}

FlagSet represents a set of defined flags.

func NewFlagSet

func NewFlagSet(name string, errWriter io.Writer) *FlagSet

NewFlagSet returns a new flag set which writes its errors to the given writer.

func (*FlagSet) Arg

func (f *FlagSet) Arg(i int) string

Arg returns the i'th non-flag argument, or an empty string when it doesn't exist.

func (*FlagSet) Args

func (f *FlagSet) Args() []string

Args returns the non-flag arguments. Flag parsing stops right before the first non-flag argument, which lets the arguments of subgroups, subcommands and their own flags stay untouched.

func (*FlagSet) ErrWriter

func (f *FlagSet) ErrWriter() io.Writer

ErrWriter returns the writer the parsing errors are written to.

func (*FlagSet) Flags

func (f *FlagSet) Flags() []*Flag

Flags returns the defined flags in definition order.

func (*FlagSet) Lookup

func (f *FlagSet) Lookup(name string) *Flag

Lookup returns the flag defined with the given long, short or environment variable name, or nil when no such flag is defined.

func (*FlagSet) NArg

func (f *FlagSet) NArg() int

NArg returns the number of non-flag arguments.

func (*FlagSet) Name

func (f *FlagSet) Name() string

Name returns the name of the flag set.

func (*FlagSet) Parse

func (f *FlagSet) Parse(arguments []string) error

Parse parses flags from the given arguments. Parsing stops at the first non-flag argument or at "--", and the remaining arguments are available through Args. Flags which are not provided fall back to their environment variable, when they define one.

func (*FlagSet) PrintDefaults

func (f *FlagSet) PrintDefaults(w io.Writer)

PrintDefaults prints the defined flags to the given writer, in alphabetical order of the name they are presented by.

func (*FlagSet) SetErrWriter

func (f *FlagSet) SetErrWriter(errWriter io.Writer)

SetErrWriter sets the writer the parsing errors are written to.

func (*FlagSet) Struct added in v1.1.0

func (f *FlagSet) Struct(target any) error

Struct defines one flag per tagged field of target, which has to be a non nil pointer to a struct.

A field is of any registered type, which the Go types are out of the box, or of a type whose pointer implements Value and carries its own parsing. Register is what a type of your own is made usable by.

The value a field already holds becomes the default value of its flag, so a struct is given its defaults by being populated before it is bound. A "default" tag overrides it, and a `default:"-"` tag drops it.

A nested or an embedded struct is flattened into the same flag set, so the fields of a struct which groups the settings of a subsystem name their flags the way the fields of the outer struct do. A nil pointer to a struct is allocated to hold its flags.

Nothing is defined when the struct cannot be bound: the fields are resolved and validated before the first flag is defined, so a failure leaves the flag set untouched and the struct keeps the values it came with.

func (*FlagSet) Var

func (f *FlagSet) Var(value Value, name FlagName, usage string, options ...FlagOption) *Flag

Var defines a flag with the given value, name and usage. The name is what the flag is provided by, and the other names it answers to are given as options:

flagSet.Var(&level, console.Long("level"), "the level to log at.", console.Short("l"), console.Env("LOG_LEVEL"))

type Formatter added in v1.3.0

type Formatter[T any] func(T) string

Formatter turns a T back into the string form it is shown as in the help.

type Group

type Group struct {
	// contains filtered or unexported fields
}

Group represents a set of commands and subgroups which are reachable through a common name, share the group's flags and have their own help.

A group is not runnable by itself, it only routes to the command (or to the subgroup) which is named right after it:

app --username=admin pods --all list
    └ app flags      └ group
                          └ group flags
                                 └ command

func NewGroup

func NewGroup(name, description string) *Group

NewGroup returns a new group of commands.

func (*Group) Commands

func (g *Group) Commands() []string

Commands returns the names of the registered commands in alphabetical order.

func (*Group) Description

func (g *Group) Description() string

Description returns a short string (less than one line) describing the group.

func (*Group) Flags

func (g *Group) Flags(configure func(*FlagSet)) *Group

Flags defines the flags of the group, which are provided right after the group's name and before the name of the subgroup or the command:

app pods --all list

The flags of a group are parsed before the ones of its subgroups and commands, so a command can rely on them being already loaded.

func (*Group) Groups

func (g *Group) Groups() []string

Groups returns the names of the registered subgroups in alphabetical order.

func (*Group) Name

func (g *Group) Name() string

Name returns the group's name, which is used to identify it.

func (*Group) Register

func (g *Group) Register(commands ...Command) *Group

Register registers commands in the group.

func (*Group) RegisterGroup

func (g *Group) RegisterGroup(groups ...*Group) *Group

RegisterGroup registers subgroups in the group.

func (*Group) Usage

func (g *Group) Usage() string

Usage returns the usage line of the group.

func (*Group) WithHelp

func (g *Group) WithHelp(help string) *Group

WithHelp overrides the whole help of the group with the given text. It lets a group document itself instead of relying on the generated help.

func (*Group) WithUsage

func (g *Group) WithUsage(usage string) *Group

WithUsage overrides the usage line which is shown in the group's help.

type Parser added in v1.3.0

type Parser[T any] func(string) (T, error)

Parser turns the string form of a flag's value into a T, and reports the values it cannot parse. Parsers compose with the standard library, whose parsing functions (strconv.ParseBool, time.ParseDuration, net.ParseMAC and their like) are already of that shape.

type Service

type Service interface {
	// Providers returns the service providers required by the command.
	Providers() []provider.Provider
}

Service is an optional interface that a Command can implement to provide service providers whose lifecycle (register, boot and terminate) is managed by the danceable service provider manager around the command's run.

type Type added in v1.3.0

type Type[T any] struct {
	// Name names the type in the help output, as the "int" of "--port int".
	// A type which names itself with nothing is presented as a "value".
	Name string

	// Expects describes what the type accepts, as "an integer" or "a duration".
	// It is what a rejected value is explained with:
	//
	//	invalid value "http" for flag --port: can't be parsed as an integer
	//
	// Every value the parser rejects is explained the same way, except the ones
	// it rejects as out of range, so the message stays about the type rather
	// than about the parser. A type which leaves it empty reports the error of
	// its parser instead.
	Expects string

	// Parse turns the string form of a value into a T. It is the only field a
	// type has to define, and a type which defines no parser cannot be
	// registered.
	Parse Parser[T]

	// Format turns a T back into its string form, which the help shows the
	// default value as. It defaults to the string form the fmt package gives
	// the value.
	Format Formatter[T]

	// Implicit is the value a flag of this type takes when it is provided
	// without one, the way a boolean is provided as "--verbose" rather than
	// "--verbose=true". Such a flag never consumes the argument which follows
	// it, and is presented by its name alone in the help.
	//
	// A type which leaves it empty requires a value.
	Implicit string
}

Type describes how the flags of a Go type are parsed and presented. It is registered once, with Register, and every flag and struct field of that type is bound to it:

console.Register(console.Type[net.IP]{
	Name:    "ip",
	Expects: "an IP address",
	Parse: func(argument string) (net.IP, error) {
		if ip := net.ParseIP(argument); ip != nil {
			return ip, nil
		}

		return nil, errors.New("invalid address")
	},
})

Only Parse is required. A type which needs no more than that is presented as a "value" in the help, formats itself the way the fmt package does, requires a value on the command line and reports the errors of its parser as they are.

type Value

type Value interface {
	// String returns the flag's value as a string.
	String() string

	// Set sets the flag's value from its string representation.
	Set(string) error
}

Value is the interface to the dynamic value stored in a flag.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL