cli

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2026 License: Apache-2.0, MIT Imports: 14 Imported by: ? modules, 0 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.

Documentation

Overview

Package cli is a small command runner over the standard library's flag package: named commands with their own flags, help, and a JSON manifest of every command for tools that drive a program from outside.

Index

Constants

View Source
const ManifestFlag = "--fletch-commands"

ManifestFlag asks a Runner for its Manifest as JSON instead of running a command: `prog --fletch-commands --json`.

Variables

View Source
var ErrUsage = errors.New("usage")

ErrUsage is wrapped by the errors Run returns for a bad command line, after it has printed what was wrong.

Functions

func ColorEnabled

func ColorEnabled(w io.Writer) bool

ColorEnabled reports whether w should get ANSI styling: never when NO_COLOR is set to anything; always when CLICOLOR_FORCE is set to anything but "0" (a parent process that pipes a child's output into its own terminal sets it); otherwise only when w is a terminal and TERM is not "dumb".

func Exit

func Exit(code int) error

Exit returns an error that makes Main exit with code and print nothing.

func ExitCode

func ExitCode(err error) int

ExitCode maps an error from Run to a process exit code: 0 for nil, 2 for ErrUsage, the code of an ExitError, and 1 otherwise.

func IsTerminal

func IsTerminal(w io.Writer) bool

IsTerminal reports whether w is a character device, such as a terminal.

func ListenFree

func ListenFree(addr string) (net.Listener, error)

ListenFree listens on TCP addr, or on the next free port after it, or on any free port of its host, so a busy port never stops a dev server.

func LocalURL

func LocalURL(addr string) (url string, wildcard bool)

LocalURL turns a listen address such as ":8080", "0.0.0.0:8080", or "127.0.0.1:8080" into a URL a browser can open from this machine: http://localhost:8080. A specific non-loopback host is kept. wildcard reports an address that listens on every interface, which other machines can reach too (see NetworkURL).

func NetworkURL

func NetworkURL(addr string, ifaceAddrs func() ([]net.Addr, error)) string

NetworkURL is the URL of addr on this machine's first non-loopback IPv4 address, or "" when it has none. ifaceAddrs is net.InterfaceAddrs in production.

func StripANSI

func StripANSI(s string) string

StripANSI removes ANSI escape sequences from s.

func Table

func Table(w io.Writer, st Style, indent string, header []string, rows [][]string)

Table writes rows as columns two spaces apart, padded by visible width so cells that carry ANSI styling still line up. The last column is not padded. A non-nil header is written first, in bold.

func VisibleWidth

func VisibleWidth(s string) int

VisibleWidth is the number of runes of s outside ANSI escapes.

Types

type Command

type Command struct {
	// Name is what selects the command: lower-case letters, digits, '-',
	// '_', and ':', starting with a letter.
	Name    string
	Summary string
	// Usage is the synopsis after the program name, such as
	// "seed-demo [--reset] <count>". Default: Name.
	Usage string
	// Flags defines the command's flags on its FlagSet.
	Flags func(fs *flag.FlagSet)
	// Hidden commands run but are left out of help.
	Hidden bool
	// BuiltIn marks a command that the framework provides rather than the
	// app.
	BuiltIn bool
	Run     func(ctx context.Context, c *Context) error
}

Command is one subcommand.

type CommandSpec

type CommandSpec struct {
	Name    string     `json:"name"`
	Summary string     `json:"summary,omitempty"`
	Usage   string     `json:"usage"`
	Flags   []FlagSpec `json:"flags"`
	BuiltIn bool       `json:"builtin"`
	Hidden  bool       `json:"hidden,omitempty"`
}

CommandSpec describes one command.

func Spec

func Spec(c Command) CommandSpec

Spec describes c.

type Commander

type Commander interface {
	Command() Command
}

Commander is a type that provides a Command.

type Context

type Context struct {
	Name   string
	Flags  *flag.FlagSet
	Args   []string
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
}

Context is what a running command gets: its parsed flags, its positional arguments, and its standard streams.

func (*Context) Arg

func (c *Context) Arg(i int) string

Arg returns positional argument i, or "" when there is none.

func (*Context) Bool

func (c *Context) Bool(name string) bool

Bool returns a bool flag's value.

func (*Context) Duration

func (c *Context) Duration(name string) time.Duration

Duration returns a duration flag's value.

func (*Context) Int

func (c *Context) Int(name string) int

Int returns an int flag's value.

func (*Context) IsSet

func (c *Context) IsSet(name string) bool

IsSet reports whether the flag was given on the command line.

func (*Context) NArg

func (c *Context) NArg() int

NArg is the number of positional arguments.

func (*Context) String

func (c *Context) String(name string) string

String returns a string flag's value.

type ExitError

type ExitError struct {
	Code int
	Err  error
}

ExitError ends a command with a specific exit code.

func (*ExitError) Error

func (e *ExitError) Error() string

func (*ExitError) Unwrap

func (e *ExitError) Unwrap() error

type FlagSpec

type FlagSpec struct {
	Name    string `json:"name"`
	Usage   string `json:"usage,omitempty"`
	Default string `json:"default,omitempty"`
	// Type is bool, string, int, int64, uint, uint64, float64, duration, or
	// value for any other flag.Value.
	Type string `json:"type"`
}

FlagSpec describes one flag.

type Manifest

type Manifest struct {
	Program string `json:"program"`
	Summary string `json:"summary,omitempty"`
	// Default is the command that runs when no command is named.
	Default  string        `json:"default,omitempty"`
	Commands []CommandSpec `json:"commands"`
}

Manifest describes a Runner's commands. It is what ManifestFlag prints.

type Runner

type Runner struct {
	// Program is the name shown in help.
	Program string
	Summary string
	// Default runs when the command line is empty or starts with a flag,
	// with the whole command line as its arguments. Empty: print help.
	Default string
	Stdin   io.Reader
	Stdout  io.Writer
	Stderr  io.Writer
	// contains filtered or unexported fields
}

Runner dispatches a command line to its commands. The zero value is ready to use; nil streams are the process's own.

func (*Runner) Add

func (r *Runner) Add(cmds ...Command)

Add registers commands. A command with the name of one already added replaces it in place. Add panics on a name that is invalid or "help", or a command without Run.

func (*Runner) Commands

func (r *Runner) Commands() []Command

Commands returns the registered commands in the order they were added.

func (*Runner) Help

func (r *Runner) Help(w io.Writer)

Help prints the program's visible commands, built-in ones first. It is styled when w is a color terminal (see ColorEnabled).

func (*Runner) Lookup

func (r *Runner) Lookup(name string) (Command, bool)

Lookup finds a command by name.

func (*Runner) Main

func (r *Runner) Main(ctx context.Context, args []string) int

Main runs args, prints any error that Run has not already reported, and returns the exit code.

func (*Runner) Manifest

func (r *Runner) Manifest() Manifest

Manifest describes every registered command, hidden ones included.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, args []string) error

Run runs the command that args name. Besides the registered commands it answers help, -h, --help, help <command>, and ManifestFlag.

type Style

type Style struct{ On bool }

Style applies ANSI styling when it is on, and returns text unchanged when it is off. The zero Style is off.

func StyleFor

func StyleFor(w io.Writer) Style

StyleFor returns the Style for w (see ColorEnabled).

func (Style) Bold

func (s Style) Bold(text string) string

Bold makes text bold.

func (Style) Cyan

func (s Style) Cyan(text string) string

Cyan colors text cyan.

func (Style) Dim

func (s Style) Dim(text string) string

Dim makes text dim.

func (Style) Green

func (s Style) Green(text string) string

Green colors text green.

func (Style) Magenta

func (s Style) Magenta(text string) string

Magenta colors text magenta.

func (Style) Red

func (s Style) Red(text string) string

Red colors text red.

func (Style) Status

func (s Style) Status(code int) string

Status colors an HTTP status code: 2xx green, 3xx cyan, 4xx yellow, 5xx red.

func (Style) Yellow

func (s Style) Yellow(text string) string

Yellow colors text yellow.

Jump to

Keyboard shortcuts

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