console

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2026 License: MIT Imports: 10 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) {
    flagSet.IntVar(
        &c.port,
        80,
        "specifies which port server should listen to.",
        console.Long("port"),
        console.Short("p"),
        console.Env("SERVER_PORT"),
    )
}

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.
flagSet.IntVar(&port, 80, "the port to listen to.", console.Long("port"), console.Short("p"), console.Env("SERVER_PORT"))

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

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

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.

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) {
        flagSet.BoolVar(&all, false, "targets every namespace.", console.Long("all"), console.Short("a"))
    }).
    Register(pod.NewListCommand()).
    RegisterGroup(nodes)

c.Flags(func(flagSet *console.FlagSet) {
    flagSet.StringVar(&username, "", "the user to authenticate as.", console.Long("username"), 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:

$ 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
    Boot(ctx context.Context, container provider.Container) error
}

Boot is called once every provider has been booted, which is where the command resolves its dependencies, and the providers are terminated gracefully once the command returns or the context is cancelled.

func (c *ServeCommand) Providers() []provider.Provider {
    return providers.BlogProviders()
}

func (c *ServeCommand) Boot(ctx context.Context, container provider.Container) error {
    return container.Resolve(&c.handler)
}
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 Options
Option 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.

Defining a flag with none of them, 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
StringVar StringVar(p *string, value string, usage string, options ...FlagOption) *Flag Defines a string flag.
BoolVar BoolVar(p *bool, value bool, usage string, options ...FlagOption) *Flag Defines a boolean flag, which takes no value.
IntVar, Int64Var IntVar(p *int, value int, usage string, options ...FlagOption) *Flag Defines a signed integer flag.
UintVar, Uint64Var UintVar(p *uint, value uint, usage string, options ...FlagOption) *Flag Defines an unsigned integer flag.
Float64Var Float64Var(p *float64, value float64, usage string, options ...FlagOption) *Flag Defines a floating point flag.
DurationVar DurationVar(p *time.Duration, value time.Duration, usage string, options ...FlagOption) *Flag Defines a time.Duration flag.
Var Var(value Value, usage string, options ...FlagOption) *Flag Defines a flag with a value of your own.
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.

A flag of your own implements Value, and may implement IsBoolFlag() bool to take no value and Type() string to name its type in the help:

type Value interface {
    String() string
    Set(string) error
}
Interfaces
Interface Methods Description
Command Name(), Description(), Usage(), Configure(*FlagSet), Run(ctx) A single command of the console.
Service Providers(), Boot(ctx, container) Optional interface for a command whose service providers are managed around its run.
Value String(), Set(string) The dynamic value stored in a flag.

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:

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.

Index

Examples

Constants

This section is empty.

Variables

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.

Functions

This section is empty.

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 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 (*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 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

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

func (f *FlagSet) BoolVar(p *bool, value bool, usage string, options ...FlagOption) *Flag

BoolVar defines a boolean flag which stores its value in p.

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

func (f *FlagSet) Float64Var(p *float64, value float64, usage string, options ...FlagOption) *Flag

Float64Var defines a float64 flag which stores its value in p.

func (*FlagSet) Int64Var

func (f *FlagSet) Int64Var(p *int64, value int64, usage string, options ...FlagOption) *Flag

Int64Var defines an int64 flag which stores its value in p.

func (*FlagSet) IntVar

func (f *FlagSet) IntVar(p *int, value int, usage string, options ...FlagOption) *Flag

IntVar defines an int flag which stores its value in p.

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.

func (*FlagSet) SetErrWriter

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

SetErrWriter sets the writer the parsing errors are written to.

func (*FlagSet) StringVar

func (f *FlagSet) StringVar(p *string, value string, usage string, options ...FlagOption) *Flag

StringVar defines a string flag which stores its value in p.

func (*FlagSet) Uint64Var

func (f *FlagSet) Uint64Var(p *uint64, value uint64, usage string, options ...FlagOption) *Flag

Uint64Var defines a uint64 flag which stores its value in p.

func (*FlagSet) UintVar

func (f *FlagSet) UintVar(p *uint, value uint, usage string, options ...FlagOption) *Flag

UintVar defines a uint flag which stores its value in p.

func (*FlagSet) Var

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

Var defines a flag with the given value and usage. At least one of the Long, Short or Env options must be provided.

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 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.

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