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:
console := console.NewConsole(path.Base(os.Args[0]), "the application.", os.Stdout, os.Stderr, provider.Default) console.Register(blog.NewServeCommand()) os.Exit(console.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) {
flagSet.IntVar(&c.port, 80, "the port to listen to.", console.Long("port"), console.Short("p"), console.Env("SERVER_PORT"))
}
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.
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) {
flagSet.BoolVar(&all, false, "targets every namespace.", console.Long("all"), console.Short("a"))
}).
Register(pod.NewListCommand()).
RegisterGroup(nodes)
console.Flags(func(flagSet *console.FlagSet) {
flagSet.StringVar(&username, "", "the user to authenticate as.", console.Long("username"), 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) {
flagSet.IntVar(
&c.limit,
10,
"the maximum number of pods to show.",
console.Long("limit"),
console.Short("l"),
console.Env("KUBECTL_LIMIT"),
)
}
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) {
flagSet.BoolVar(all, false, "targets the pods of every namespace.", console.Long("all"), 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) {
flagSet.IntVar(
&c.limit,
10,
"the maximum number of pods to show.",
console.Long("limit"),
console.Short("l"),
console.Env("KUBECTL_LIMIT"),
)
}
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) {
flagSet.BoolVar(all, false, "targets the pods of every namespace.", console.Long("all"), 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
flagSet.StringVar(&s.context, defaultContext, "the context to work against.", console.Long("context"))
}
// 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 ¶
- Variables
- func StructFlags(target any) (func(*FlagSet), error)
- type Command
- type Console
- func (c *Console) ErrWriter() io.Writer
- func (c *Console) Flags(configure func(*FlagSet)) *Console
- func (c *Console) Register(commands ...Command) *Console
- func (c *Console) RegisterGroup(groups ...*Group) *Console
- func (c *Console) Run(ctx context.Context, arguments []string) ExitStatus
- func (c *Console) WithHelp(help string) *Console
- func (c *Console) WithUsage(usage string) *Console
- func (c *Console) Writer() io.Writer
- type ExitStatus
- type FieldError
- type Flag
- type FlagOption
- type FlagSet
- func (f *FlagSet) Arg(i int) string
- func (f *FlagSet) Args() []string
- func (f *FlagSet) BoolVar(p *bool, value bool, usage string, options ...FlagOption) *Flag
- func (f *FlagSet) DurationVar(p *time.Duration, value time.Duration, usage string, options ...FlagOption) *Flag
- func (f *FlagSet) ErrWriter() io.Writer
- func (f *FlagSet) Flags() []*Flag
- func (f *FlagSet) Float64Var(p *float64, value float64, usage string, options ...FlagOption) *Flag
- func (f *FlagSet) Int64Var(p *int64, value int64, usage string, options ...FlagOption) *Flag
- func (f *FlagSet) IntVar(p *int, value int, usage string, options ...FlagOption) *Flag
- func (f *FlagSet) Lookup(name string) *Flag
- func (f *FlagSet) NArg() int
- func (f *FlagSet) Name() string
- func (f *FlagSet) Parse(arguments []string) error
- func (f *FlagSet) PrintDefaults(w io.Writer)
- func (f *FlagSet) SetErrWriter(errWriter io.Writer)
- func (f *FlagSet) StringVar(p *string, value string, usage string, options ...FlagOption) *Flag
- func (f *FlagSet) Struct(target any) error
- func (f *FlagSet) Uint64Var(p *uint64, value uint64, usage string, options ...FlagOption) *Flag
- func (f *FlagSet) UintVar(p *uint, value uint, usage string, options ...FlagOption) *Flag
- func (f *FlagSet) Var(value Value, usage string, options ...FlagOption) *Flag
- type Group
- func (g *Group) Commands() []string
- func (g *Group) Description() string
- func (g *Group) Flags(configure func(*FlagSet)) *Group
- func (g *Group) Groups() []string
- func (g *Group) Name() string
- func (g *Group) Register(commands ...Command) *Group
- func (g *Group) RegisterGroup(groups ...*Group) *Group
- func (g *Group) Usage() string
- func (g *Group) WithHelp(help string) *Group
- func (g *Group) WithUsage(usage string) *Group
- type Service
- type Value
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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") // ErrUnsupportedType is returned for a tagged field of a type no flag can // be defined for. ErrUnsupportedType = errors.New("unsupported field type") // 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.
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.
Functions ¶
func StructFlags ¶ added in v1.1.0
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) Flags ¶
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) RegisterGroup ¶
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
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.
type FlagOption ¶
type FlagOption func(*Flag)
FlagOption defines an optional property of a flag.
func Env ¶
func Env(name string) FlagOption
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) FlagOption
Long defines the long name of a flag, which is provided as "--name".
func Short ¶
func Short(name string) FlagOption
Short defines the short (single character) name of a flag, which is provided as "-n".
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 ¶
NewFlagSet returns a new flag set which writes its errors to the given writer.
func (*FlagSet) Arg ¶
Arg returns the i'th non-flag argument, or an empty string when it doesn't exist.
func (*FlagSet) Args ¶
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) DurationVar ¶
func (f *FlagSet) DurationVar(p *time.Duration, value time.Duration, usage string, options ...FlagOption) *Flag
DurationVar defines a time.Duration flag which stores its value in p.
func (*FlagSet) Float64Var ¶
Float64Var defines a float64 flag which stores its value in p.
func (*FlagSet) Lookup ¶
Lookup returns the flag defined with the given long, short or environment variable name, or nil when no such flag is defined.
func (*FlagSet) Parse ¶
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 ¶
PrintDefaults prints the defined flags to the given writer.
func (*FlagSet) SetErrWriter ¶
SetErrWriter sets the writer the parsing errors are written to.
func (*FlagSet) Struct ¶ added in v1.1.0
Struct defines one flag per tagged field of target, which has to be a non nil pointer to a struct.
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.
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 (*Group) Commands ¶
Commands returns the names of the registered commands in alphabetical order.
func (*Group) Description ¶
Description returns a short string (less than one line) describing the group.
func (*Group) Flags ¶
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) RegisterGroup ¶
RegisterGroup registers subgroups in the group.
type Service ¶
type Service interface {
// Providers returns the service providers required by the command.
Providers() []provider.Provider
// Boot resolves the command's dependencies from the booted container.
Boot(ctx context.Context, container provider.Container) error
}
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. Boot is called once all providers have been booted, allowing the command to resolve its dependencies before Run.