cli

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

README

cli

An embeddable Go command-line component library: command trees, hooks, interactive input, and rich terminal rendering out of the box.

Auth Go Reference Go Version License Last Commit HitCount

Features

  • Command tree: the root command (App) and subcommands are the same type, with nested subcommands, aliases, and hidden commands
  • Out of the box: automatically registers --help/-h, --verbose, --quiet, --no-interaction; setting Version automatically enables --version/-v
  • Hooks: global/command-level Before / After hooks, plus CommandNotFound for custom unmatched-command handling
  • Rich flag types: string, integer, float, bool, duration, slices (repeatable/comma-separated), and generic custom types
  • Value source fallback: command line > environment variable > default value (Sources: cli.EnvVars("APP_LANG"))
  • Leveled logging: Info / Success / Warn / Error / Debug / Verbose, controlled by --verbose / --quiet
  • Rich table rendering: 6 styles (ASCII / Markdown / borderless / Unicode box, etc.), with sections, separators, and East Asian wide-character alignment
  • Interactive Q&A: free input, hidden input (password), confirmation, choice/multi-select, with validation, retries, and autocompletion
  • Tag-based colors: <info>...</info> or attribute styles like <fg=red;bg=blue>, stripped automatically on non-terminals
  • Easy to test: injectable Stdin; non-terminal environments degrade to defaults automatically, handy for pipes and unit tests

Installation

go get github.com/chihqiang/cli

Quick start

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/chihqiang/cli"
)

func main() {
	app := &cli.App{
		Name:    "hello",
		Usage:   "say hello to someone",
		Version: "1.0.0",
		Subcommands: []*cli.Command{
			{
				Name:    "greet",
				Aliases: []string{"g"},
				Usage:   "greet someone",
				Flags: []cli.Flag{
					&cli.BoolFlag{Name: "shout", Aliases: []string{"s"}, Usage: "shout the greeting"},
				},
				Action: func(ctx context.Context, in *cli.Input, out *cli.Output) error {
					name := "World"
					if in.Args().Present() {
						name = in.Args().First()
					}
					if in.Bool("shout") {
						out.Infof("HELLO, %s!", name)
					} else {
						out.Infof("Hello, %s!", name)
					}
					return nil
				},
			},
		},
	}

	if err := app.Run(context.Background(), os.Args); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

Sample output:

$ go run . greet            # Hello, World!
$ go run . greet Alice -s   # HELLO, ALICE!
$ go run . --help           # auto-generated help

Core concepts

App and Command

App is a type alias for the root command (type App = Command); both are the same type and can nest subcommands recursively:

Field Description
Name / Aliases Command name and aliases
Usage / UsageText / Description Help text; UsageText customizes the usage line
ArgsUsage Usage description for positional arguments
Hidden Hidden in help, but still directly invocable
Version Root command version; enables --version/-v
Flags / Subcommands Flag list and subcommands
Before / After Hooks before/after execution (defined on a subcommand they run with it; defined on the root they run once per invocation). Before may return an updated context used by Action / After
Action Command execution function func(ctx, *Input, *Output) error
CommandNotFound Handler for when a subcommand is not matched
VersionPrinter Custom version printing function
Stdin Injectable standard input (default os.Stdin)
Execution flow
graph LR
    A[Run ctx args] --> B[parse flags]
    B --> C{subcommand?}
    C -- yes --> D[subcommand Before/Action/After]
    C -- no --> E[this command's Action]
    E --> F[global After hook]
    D --> F
Input and Output
  • Input: the input side. in.Args() positional arguments, typed getters like in.String("name") / in.Bool("force") / in.Int("count"), in.IsSet("force") to check whether a flag was explicitly set, in.IsInteractive() to check whether interaction is allowed, and in.FindCommand("build") to recursively find a subcommand by name/alias (for calling command B from inside command A)
  • Output: the output side. Logging, table rendering, and interactive Q&A (details below)

Flags

Types
Flag Go type Notes
StringFlag string
IntFlag / Int64Flag / UintFlag integers
Float64Flag float64
BoolFlag bool does not consume the next token; only accepts --flag / --flag=true
DurationFlag time.Duration
StringSliceFlag / IntSliceFlag / Float64SliceFlag slices repeatable or comma-separated
GenericFlag flag.Value custom implementation, requires a non-nil Value

All flags support: Aliases (single-char alias -n), Required (required validation), Hidden, DefaultText, and Sources (value source).

Value priority
command line > environment variable (Sources) > default value (Value)
&cli.StringFlag{
	Name:    "lang",
	Usage:   "language",
	Value:   "en",
	Sources: cli.EnvVars("APP_LANG", "LANG"),
}
Parsing rules
  • --name value / --name=value / -n value / -n=value are all supported
  • Positional arguments and flags can be interleaved (commands with subcommands stop parsing flags after the first positional argument, for subcommand dispatch)
  • Everything after -- is treated as positional arguments

Logging

Method Level Description
Info / Infof normal suppressed by --quiet
Success / Successf normal suppressed by --quiet
Warn / Warnf warning written to stderr, not suppressed by --quiet
Error / Errorf error written to stderr, not suppressed by --quiet
Debug / Debugf debug requires --verbose
Verbose / Verbosef verbose requires --verbose
$ app --verbose ...   # prints Debug/Verbose
$ app --quiet ...     # only Warn/Error

Tables

// Simple table
out.Table([]string{"Name", "Score"}, [][]string{{"Alice", "90"}, {"Bob", "85"}})

// Custom table: styles, sections, separators, heterogeneous cells
t := cli.NewTable()
t.SetStyle("box") // default | compact | markdown | borderless | box | box-double
t.SetHeader([]string{"Item", "Qty", "Price"}, cli.AlignLeft)
t.AddSection("Fruits")
t.AddRowAny([]interface{}{"Apple", 3, 1.5}, false)
t.AddSeparator()
t.AddRowAny([]interface{}{"Coffee", 1, 2.0}, false)
out.RenderTable(t)

Alignment AlignLeft / AlignRight / AlignCenter is supported; column widths are computed automatically, correctly handling East Asian wide characters such as CJK.

Interactive Q&A

Method Description
AskString(question, default) string input
Ask(question, default) generic input, returns any default type
AskHidden(question) hidden input (password, no echo)
Confirm(question, default) yes/no confirmation
Choice(question, choices, default) single / multi select (SetMultiselect(true))

In non-interactive environments (pipe / --no-interaction) the Q&A automatically returns the default value; explicitly injecting app.Stdin forces interaction, handy for automated tests:

$ printf 'Zhang\n25\nsecret\ny\npy\n' | go run ./example/ask survey

Advanced capabilities: SetValidator validation, SetMaxAttempts retry count, SetNormalizer normalization, SetAutocompleterValues autocompletion candidates.

Colors

Output uses tag-based rendering; the underlying color generation is delegated to fatih/color (color codes are stripped on non-terminals):

out.Infof("user <info>%s</info> logged in <success>successfully</success>", name)
out.Errorf("error <fg=red;bg=white;op=bold>%v</fg=red;bg=white;op=bold>", err)

Builtin styles: error / info / comment / warning / success / question / highlight. Custom styles can be added with Formatter.SetStyle("name", "32").

Error handling

// Exit early with an exit code
if in.String("token") == "" {
	return cli.Exit(1, "missing token")
}

// Typed errors
var ue *cli.UsageError    // usage error (unknown option, missing required flag, etc.)
var nf *cli.NotFoundError // help topic/command does not exist

Builtin commands and flags

Builtin Description
--help / -h show help (root command or subcommand)
--version / -v print the version (only after Version is set)
help [command] builtin help subcommand
version builtin version subcommand
--verbose debug-level output
--quiet suppress normal output
--no-interaction disable interactive Q&A

Examples

The example/ directory contains complete runnable examples:

Directory Demonstrates
hello minimal intro: command, argument, flag
commands command organization & help: grouping, hidden commands, CommandNotFound
flags every flag type and value sources
ask interactive Q&A (including feeding answers via a pipe)
table multi-style table rendering
logging leveled logging and level control
invoke three ways to call command B from inside command A
context passing values through context across the command tree
go run ./example/hello greet Alice --shout
go run ./example/commands --help
go run ./example/flags --token abc --tags a --tags b
go run ./example/table box
go run ./example/ask survey
go run ./example/logging --verbose demo
go run ./example/invoke deploy --env prod
go run ./example/context --user alice run

Testing

go test ./...   # all unit tests

License

Apache-2.0

Documentation

Index

Constants

View Source
const (
	VerbosityQuiet  = 0 // Keep only warnings and errors
	VerbosityNormal = 1
	VerbosityDebug  = 4 // --verbose
)

Output verbosity levels.

View Source
const (
	AlignLeft   = 1
	AlignRight  = 0
	AlignCenter = 2
)

Table alignment modes.

Variables

This section is empty.

Functions

func Exit

func Exit(code int, args ...interface{}) error

Exit builds an error carrying an exit code; usable in an Action as `return cli.Exit(1)`.

Types

type ActionFunc

type ActionFunc func(context.Context, *Input, *Output) error

ActionFunc is the command execution function: context, input (args+flags), output (logging/table/ask).

type App

type App = Command

App is a type alias for the root command. Usage: `app := &cli.App{...}`.

type Args

type Args []string

Args holds the positional arguments of a command.

func (Args) First

func (a Args) First() string

First returns the first argument (empty string when none exist).

func (Args) Get

func (a Args) Get(i int) string

Get returns the i-th argument.

func (Args) Len

func (a Args) Len() int

Len returns the number of arguments.

func (Args) Present

func (a Args) Present() bool

Present reports whether there are any arguments.

func (Args) Slice

func (a Args) Slice() []string

Slice returns all arguments.

func (Args) Tail

func (a Args) Tail() []string

Tail returns the remaining arguments after the first.

type Ask

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

Ask handles interactive questions.

func NewAsk

func NewAsk(out *Output, raw interface{}) *Ask

NewAsk creates a questioner.

func (*Ask) Run

func (a *Ask) Run() (interface{}, error)

Run asks the question and returns the validated answer.

func (*Ask) SetReader

func (a *Ask) SetReader(r io.Reader) *Ask

SetReader overrides the input source (default os.Stdin), for testing and embedding. Once injected, this Ask uses its own independent buffered reader.

type BeforeFunc

type BeforeFunc func(context.Context, *Input, *Output) (context.Context, error)

BeforeFunc is a hook function run before Action. It may derive a new context and return it; the updated context is passed to Action/After and subsequent hooks.

type BoolFlag

type BoolFlag struct {
	Name        string
	Aliases     []string
	Usage       string
	Required    bool
	Hidden      bool
	DefaultText string
	Sources     ValueSource
	Value       bool
}

BoolFlag is a boolean switch flag.

func (BoolFlag) IsRequired

func (f BoolFlag) IsRequired() bool

func (BoolFlag) Names

func (f BoolFlag) Names() []string

func (BoolFlag) TakesValue

func (f BoolFlag) TakesValue() bool

type Choice

type Choice struct {
	*Question
	// contains filtered or unexported fields
}

Choice is a multiple-choice question.

func NewChoice

func NewChoice(question string, choices map[string]string, defaultVal interface{}) *Choice

NewChoice creates a multiple-choice question; choices is a key->label mapping.

func (*Choice) GetChoices

func (c *Choice) GetChoices() map[string]string

GetChoices returns the choices.

func (*Choice) GetPrompt

func (c *Choice) GetPrompt() string

GetPrompt returns the prompt.

func (*Choice) IsMultiselect

func (c *Choice) IsMultiselect() bool

IsMultiselect reports whether multi-select is enabled.

func (*Choice) SetErrorMessage

func (c *Choice) SetErrorMessage(msg string) *Choice

SetErrorMessage sets the validation error message.

func (*Choice) SetMultiselect

func (c *Choice) SetMultiselect(multiselect bool) *Choice

SetMultiselect toggles multi-select.

func (*Choice) SetPrompt

func (c *Choice) SetPrompt(prompt string) *Choice

SetPrompt sets the prompt.

type Command

type Command struct {
	// Metadata
	Name        string   // Command name; usually empty for the root command (App)
	Aliases     []string // Command aliases; the command can be invoked by any alias
	Usage       string   // One-line purpose description, shown in the help listing
	UsageText   string   // Custom usage line; generated by the library by default
	Description string   // Detailed command description, shown in help
	ArgsUsage   string   // Usage description for positional arguments (e.g. "<name> [flags]")
	Hidden      bool     // When true, hidden from help/listing but still directly invocable
	Version     string   // Version of the root command (App); enables --version/-v

	// Behavior
	Flags           []Flag              // Flags defined by this command
	Subcommands     []*Command          // List of subcommands
	Before          BeforeFunc          // Hook run before execution; may return an updated context
	After           HookFunc            // Hook run after execution (invoked after a subcommand runs)
	Action          ActionFunc          // Command execution function
	CommandNotFound CommandNotFoundFunc // Handler for when a command is not found
	VersionPrinter  VersionPrinterFunc  // Custom version printing function

	Stdin io.Reader // Injectable standard input (defaults to os.Stdin)
	// contains filtered or unexported fields
}

Command is the command struct. The root command is the App; both are the same type.

func New

func New() *Command

New creates an empty root command.

func (*Command) Run

func (c *Command) Run(ctx context.Context, args []string) error

Run executes the command. args should include the program name (pass os.Args directly): `app.Run(ctx, os.Args)`.

type CommandNotFoundFunc

type CommandNotFoundFunc func(context.Context, *Input, *Output, string)

CommandNotFoundFunc handles a command that was not found.

type Confirmation

type Confirmation struct {
	*Question
	// contains filtered or unexported fields
}

Confirmation is a yes/no question.

func NewConfirmation

func NewConfirmation(question string, defaultVal bool, trueAnswerRegex string) *Confirmation

NewConfirmation creates a confirmation question.

type DurationFlag

type DurationFlag struct {
	Name        string
	Aliases     []string
	Usage       string
	Required    bool
	Hidden      bool
	DefaultText string
	Sources     ValueSource
	Value       time.Duration
}

DurationFlag is a time duration flag.

func (DurationFlag) IsRequired

func (f DurationFlag) IsRequired() bool

func (DurationFlag) Names

func (f DurationFlag) Names() []string

func (DurationFlag) TakesValue

func (f DurationFlag) TakesValue() bool

type ExitError

type ExitError struct {
	Code int
	Err  error
}

ExitError carries an exit code and an error, for ending a command early with an exit code from an Action.

func (*ExitError) Error

func (e *ExitError) Error() string

func (*ExitError) ExitCode

func (e *ExitError) ExitCode() int

ExitCode returns the exit code.

func (*ExitError) Unwrap

func (e *ExitError) Unwrap() error

type Flag

type Flag interface {
	// Names returns the primary name plus aliases.
	Names() []string
	// TakesValue reports whether the flag takes a value (bool flags return false).
	TakesValue() bool
	// IsRequired reports whether the flag is required.
	IsRequired() bool
	// contains filtered or unexported methods
}

Flag is the interface for all flag types.

type Float64Flag

type Float64Flag struct {
	Name        string
	Aliases     []string
	Usage       string
	Required    bool
	Hidden      bool
	DefaultText string
	Sources     ValueSource
	Value       float64
}

Float64Flag is a floating-point flag.

func (Float64Flag) IsRequired

func (f Float64Flag) IsRequired() bool

func (Float64Flag) Names

func (f Float64Flag) Names() []string

func (Float64Flag) TakesValue

func (f Float64Flag) TakesValue() bool

type Float64SliceFlag

type Float64SliceFlag struct {
	Name        string
	Aliases     []string
	Usage       string
	Required    bool
	Hidden      bool
	DefaultText string
	Sources     ValueSource
	Value       []float64
}

Float64SliceFlag is a floating-point slice flag.

func (Float64SliceFlag) IsRequired

func (f Float64SliceFlag) IsRequired() bool

func (Float64SliceFlag) Names

func (f Float64SliceFlag) Names() []string

func (Float64SliceFlag) TakesValue

func (f Float64SliceFlag) TakesValue() bool

type Formatter

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

Formatter renders colors via <style>...</style> tags, delegating the underlying ANSI rendering to fatih/color (Symfony-style tag rendering; colors are not self-implemented).

func NewFormatter

func NewFormatter() *Formatter

NewFormatter creates a formatter with the default styles.

func (*Formatter) Escape

func (f *Formatter) Escape(text string) string

Escape escapes style tags in text.

func (*Formatter) Format

func (f *Formatter) Format(message string) string

Format processes a message, replacing style tags with ANSI codes (rendered via fatih/color).

func (*Formatter) GetStyle

func (f *Formatter) GetStyle(name string) (string, error)

GetStyle returns the SGR parameter string of a registered style.

func (*Formatter) HasStyle

func (f *Formatter) HasStyle(name string) bool

HasStyle reports whether the style exists.

func (*Formatter) IsDecorated

func (f *Formatter) IsDecorated() bool

IsDecorated reports whether styling is enabled.

func (*Formatter) SetDecorated

func (f *Formatter) SetDecorated(decorated bool)

SetDecorated enables/disables styling. When disabled, plain text is output (color codes stripped).

func (*Formatter) SetStyle

func (f *Formatter) SetStyle(name string, code string)

SetStyle registers a style by name (code is an SGR parameter string, e.g. "32", "1;31").

type GenericFlag

type GenericFlag struct {
	Name        string
	Aliases     []string
	Usage       string
	Required    bool
	Hidden      bool
	DefaultText string
	Sources     ValueSource
	Value       flag.Value
}

GenericFlag is a generic flag that allows a custom flag.Value implementation.

func (GenericFlag) IsRequired

func (f GenericFlag) IsRequired() bool

func (GenericFlag) Names

func (f GenericFlag) Names() []string

func (GenericFlag) TakesValue

func (f GenericFlag) TakesValue() bool

type HookFunc

type HookFunc func(context.Context, *Input, *Output) error

HookFunc is the After hook function with the same signature as Action.

type Input

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

Input carries the input side during command execution: the current command, positional arguments, and flag values. It is separated from Output to avoid merging input and output into a single object.

func (*Input) Args

func (in *Input) Args() Args

Args returns the current command's positional arguments.

func (*Input) Bool

func (in *Input) Bool(name string) bool

Bool returns the value of a bool flag.

func (*Input) Command

func (in *Input) Command() *Command

Command returns the currently executing command.

func (*Input) Duration

func (in *Input) Duration(name string) time.Duration

Duration returns the value of a duration flag.

func (*Input) FindCommand

func (in *Input) FindCommand(name string) *Command

FindCommand recursively finds a subcommand under the root command (App) by name or alias; returns nil when not found.

Often used to invoke command B from inside the Action of command A, for example:

if b := in.FindCommand("build"); b != nil {
    return b.Run(ctx, []string{"build", "--env", "prod"})
}

func (*Input) Float64

func (in *Input) Float64(name string) float64

Float64 returns the value of a floating-point flag.

func (*Input) Float64Slice

func (in *Input) Float64Slice(name string) []float64

Float64Slice returns the value of a floating-point slice flag.

func (*Input) Generic

func (in *Input) Generic(name string) interface{}

Generic returns the underlying value of a generic flag.

func (*Input) Int

func (in *Input) Int(name string) int

Int returns the value of an integer flag.

func (*Input) Int64

func (in *Input) Int64(name string) int64

Int64 returns the value of a 64-bit integer flag.

func (*Input) IntSlice

func (in *Input) IntSlice(name string) []int

IntSlice returns the value of an integer slice flag.

func (*Input) IsInteractive

func (in *Input) IsInteractive() bool

IsInteractive reports whether interactive Q&A is allowed; it is false with --no-interaction or when stdin is not a terminal.

func (*Input) IsSet

func (in *Input) IsSet(name string) bool

IsSet reports whether the flag was explicitly set (command line or environment variable).

func (*Input) NArg

func (in *Input) NArg() int

NArg returns the number of positional arguments.

func (*Input) Root

func (in *Input) Root() *Command

Root returns the root command (App).

func (*Input) String

func (in *Input) String(name string) string

String returns the string value of a flag.

func (*Input) StringSlice

func (in *Input) StringSlice(name string) []string

StringSlice returns the value of a string slice flag.

func (*Input) Uint

func (in *Input) Uint(name string) uint

Uint returns the value of an unsigned integer flag.

type Int64Flag

type Int64Flag struct {
	Name        string
	Aliases     []string
	Usage       string
	Required    bool
	Hidden      bool
	DefaultText string
	Sources     ValueSource
	Value       int64
}

Int64Flag is a 64-bit integer flag.

func (Int64Flag) IsRequired

func (f Int64Flag) IsRequired() bool

func (Int64Flag) Names

func (f Int64Flag) Names() []string

func (Int64Flag) TakesValue

func (f Int64Flag) TakesValue() bool

type IntFlag

type IntFlag struct {
	Name        string
	Aliases     []string
	Usage       string
	Required    bool
	Hidden      bool
	DefaultText string
	Sources     ValueSource
	Value       int
}

IntFlag is an integer flag.

func (IntFlag) IsRequired

func (f IntFlag) IsRequired() bool

func (IntFlag) Names

func (f IntFlag) Names() []string

func (IntFlag) TakesValue

func (f IntFlag) TakesValue() bool

type IntSliceFlag

type IntSliceFlag struct {
	Name        string
	Aliases     []string
	Usage       string
	Required    bool
	Hidden      bool
	DefaultText string
	Sources     ValueSource
	Value       []int
}

IntSliceFlag is an integer slice flag.

func (IntSliceFlag) IsRequired

func (f IntSliceFlag) IsRequired() bool

func (IntSliceFlag) Names

func (f IntSliceFlag) Names() []string

func (IntSliceFlag) TakesValue

func (f IntSliceFlag) TakesValue() bool

type NotFoundError

type NotFoundError struct {
	Command string
}

NotFoundError represents a command/help topic that does not exist.

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

type Output

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

Output handles common log output: Info / Success / Warn / Error / Debug / Verbose, plus table rendering and interactive Q&A. Color is enabled automatically on terminals.

func NewOutput

func NewOutput() *Output

NewOutput creates an output object writing to stdout/stderr. Color detection is delegated to fatih/color.

func (*Output) Ask

func (o *Output) Ask(question string, defaultVal interface{}) (interface{}, error)

Ask asks a free-form question and returns the validated answer.

func (*Output) AskHidden

func (o *Output) AskHidden(question string) (string, error)

AskHidden asks a hidden-input question (no echo).

func (*Output) AskString

func (o *Output) AskString(question, defaultVal string) (string, error)

AskString asks a string question.

func (*Output) Choice

func (o *Output) Choice(question string, choices map[string]string, defaultVal interface{}) (interface{}, error)

Choice asks a multiple-choice question; choices is a key->label mapping.

func (*Output) Confirm

func (o *Output) Confirm(question string, defaultVal bool) (bool, error)

Confirm asks a yes/no question.

func (*Output) Debug

func (o *Output) Debug(args ...interface{})

Debug prints a debug message (requires --verbose).

func (*Output) Debugf

func (o *Output) Debugf(format string, args ...interface{})

Debugf prints a formatted debug message.

func (*Output) Error

func (o *Output) Error(args ...interface{})

Error prints an error message (written to stderr, not suppressed by --quiet).

func (*Output) Errorf

func (o *Output) Errorf(format string, args ...interface{})

Errorf prints a formatted error message.

func (*Output) GetVerbosity

func (o *Output) GetVerbosity() int

GetVerbosity returns the output level.

func (*Output) Info

func (o *Output) Info(args ...interface{})

Info prints an informational message.

func (*Output) Infof

func (o *Output) Infof(format string, args ...interface{})

Infof prints a formatted informational message.

func (*Output) RenderTable

func (o *Output) RenderTable(t *Table) string

RenderTable renders and prints a custom Table (style/sections/separators supported) and returns the text.

func (*Output) SetVerbosity

func (o *Output) SetVerbosity(level int)

SetVerbosity sets the output level.

func (*Output) Success

func (o *Output) Success(args ...interface{})

Success prints a success message.

func (*Output) Successf

func (o *Output) Successf(format string, args ...interface{})

Successf prints a formatted success message.

func (*Output) Table

func (o *Output) Table(header []string, rows [][]string) string

Table renders and prints a table, returning the rendered text.

func (*Output) TableAny

func (o *Output) TableAny(header []string, rows [][]interface{}) string

TableAny renders and prints a table with arbitrary cell types (cells are stringified automatically).

func (*Output) Verbose

func (o *Output) Verbose(args ...interface{})

Verbose prints a verbose message (requires --verbose).

func (*Output) Verbosef

func (o *Output) Verbosef(format string, args ...interface{})

Verbosef prints a formatted verbose message.

func (*Output) Warn

func (o *Output) Warn(args ...interface{})

Warn prints a warning message (not suppressed by --quiet).

func (*Output) Warnf

func (o *Output) Warnf(format string, args ...interface{})

Warnf prints a formatted warning message.

type Question

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

Question represents an interactive question.

func NewQuestion

func NewQuestion(question string, defaultVal interface{}) *Question

NewQuestion creates a normal question.

func (*Question) GetAutocompleterValues

func (q *Question) GetAutocompleterValues() []string

GetAutocompleterValues returns the autocompletion candidates.

func (*Question) GetDefault

func (q *Question) GetDefault() interface{}

GetDefault returns the default answer.

func (*Question) GetMaxAttempts

func (q *Question) GetMaxAttempts() *int

GetMaxAttempts returns the maximum number of attempts.

func (*Question) GetNormalizer

func (q *Question) GetNormalizer() func(string) string

GetNormalizer returns the normalizer function.

func (*Question) GetQuestion

func (q *Question) GetQuestion() string

GetQuestion returns the question text.

func (*Question) GetValidator

func (q *Question) GetValidator() func(string) (interface{}, error)

GetValidator returns the validator.

func (*Question) IsHidden

func (q *Question) IsHidden() bool

IsHidden reports whether the answer is hidden.

func (*Question) SetAutocompleterValues

func (q *Question) SetAutocompleterValues(values []string) *Question

SetAutocompleterValues sets the autocompletion candidates.

func (*Question) SetHidden

func (q *Question) SetHidden(hidden bool) *Question

SetHidden enables hidden input.

func (*Question) SetMaxAttempts

func (q *Question) SetMaxAttempts(attempts int) *Question

SetMaxAttempts sets the maximum number of attempts.

func (*Question) SetNormalizer

func (q *Question) SetNormalizer(normalizer func(string) string) *Question

SetNormalizer sets the normalizer function.

func (*Question) SetValidator

func (q *Question) SetValidator(validator func(string) (interface{}, error)) *Question

SetValidator sets the validator.

type StringFlag

type StringFlag struct {
	Name        string
	Aliases     []string
	Usage       string
	Required    bool
	Hidden      bool
	DefaultText string
	Sources     ValueSource
	Value       string
}

StringFlag is a string flag.

func (StringFlag) IsRequired

func (f StringFlag) IsRequired() bool

func (StringFlag) Names

func (f StringFlag) Names() []string

func (StringFlag) TakesValue

func (f StringFlag) TakesValue() bool

type StringSliceFlag

type StringSliceFlag struct {
	Name        string
	Aliases     []string
	Usage       string
	Required    bool
	Hidden      bool
	DefaultText string
	Sources     ValueSource
	Value       []string
}

StringSliceFlag is a string slice flag (repeatable).

func (StringSliceFlag) IsRequired

func (f StringSliceFlag) IsRequired() bool

func (StringSliceFlag) Names

func (f StringSliceFlag) Names() []string

func (StringSliceFlag) TakesValue

func (f StringSliceFlag) TakesValue() bool

type Table

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

Table renders a table to the console.

func NewTable

func NewTable() *Table

NewTable creates a table.

func (*Table) AddRow

func (t *Table) AddRow(row []string, first bool) *Table

AddRow appends a row.

func (*Table) AddRowAny

func (t *Table) AddRowAny(row []interface{}, first bool) *Table

AddRowAny appends a row with heterogeneous cell types.

func (*Table) AddSection

func (t *Table) AddSection(title string) *Table

AddSection appends a full-width section title row.

func (*Table) AddSeparator

func (t *Table) AddSeparator() *Table

AddSeparator appends a horizontal separator line.

func (*Table) Render

func (t *Table) Render() string

Render returns the table text.

func (*Table) SetCellAlign

func (t *Table) SetCellAlign(align int) *Table

SetCellAlign sets the cell alignment.

func (*Table) SetHeader

func (t *Table) SetHeader(header []string, align int) *Table

SetHeader sets the table header.

func (*Table) SetRows

func (t *Table) SetRows(rows [][]string, align int) *Table

SetRows replaces the data rows.

func (*Table) SetStyle

func (t *Table) SetStyle(style string) *Table

SetStyle sets the render style.

type UintFlag

type UintFlag struct {
	Name        string
	Aliases     []string
	Usage       string
	Required    bool
	Hidden      bool
	DefaultText string
	Sources     ValueSource
	Value       uint
}

UintFlag is an unsigned integer flag.

func (UintFlag) IsRequired

func (f UintFlag) IsRequired() bool

func (UintFlag) Names

func (f UintFlag) Names() []string

func (UintFlag) TakesValue

func (f UintFlag) TakesValue() bool

type UsageError

type UsageError struct {
	Msg string
}

UsageError represents a command-line usage error (unknown option, missing required flag, etc.).

func (*UsageError) Error

func (e *UsageError) Error() string

type ValueSource

type ValueSource interface {
	// Lookup returns the value provided by this source; returns empty string and false when not found.
	Lookup() (string, bool)
	// String returns a human-readable description of the source, used in help text.
	String() string
}

ValueSource is the interface for flag value sources.

A flag may declare a value source (Sources); at runtime the first hit wins by priority: command line > Sources > default value (Value). The builtin implementation is EnvVars; custom implementations are also supported.

func EnvVars

func EnvVars(envs ...string) ValueSource

EnvVars builds a ValueSource that reads from environment variables; it is one implementation of ValueSource.

Usage: Sources: cli.EnvVars("APP_LANG", "LANG")

type VersionPrinterFunc

type VersionPrinterFunc func(context.Context, *Input, *Output)

VersionPrinterFunc customizes version printing. When unset, the default implementation is used.

Directories

Path Synopsis
example
ask command
ask —— demos interactive Q&A: free input, hidden input, confirmation, and choice.
ask —— demos interactive Q&A: free input, hidden input, confirmation, and choice.
commands command
commands —— demos command organization & the help system: grouping, hidden commands, custom usage, and not-found handling.
commands —— demos command organization & the help system: grouping, hidden commands, custom usage, and not-found handling.
context command
context —— demos passing values through context.Context across the command tree.
context —— demos passing values through context.Context across the command tree.
flags command
flags —— demos every flag type: string/int/float/bool/duration/slice/required/env.
flags —— demos every flag type: string/int/float/bool/duration/slice/required/env.
hello command
hello —— minimal intro: one App, one subcommand, one positional argument, one flag.
hello —— minimal intro: one App, one subcommand, one positional argument, one flag.
invoke command
invoke —— demos calling command B from inside command A.
invoke —— demos calling command B from inside command A.
logging command
logging —— demos log output and level control.
logging —— demos log output and level control.
table command
table —— demos table rendering: multiple styles, section titles, and separators.
table —— demos table rendering: multiple styles, section titles, and separators.

Jump to

Keyboard shortcuts

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