Documentation
¶
Overview ¶
Package cli builds command-line programs on top of the standard library flag package. It adds nested subcommands, flags anywhere, inherited flags, generated help, and type-safe flag access.
root := &cli.Command{
Name: "echo",
Flags: cli.FlagsFunc(func(f *flag.FlagSet) {
f.Bool("capitalize", false, "capitalize the input")
}),
Exec: func(ctx context.Context, s *cli.State) error {
text := strings.Join(s.Args, " ")
if s.GetFlag[bool]("capitalize") {
text = strings.ToUpper(text)
}
fmt.Fprintln(s.Stdout, text)
return nil
},
}
if err := cli.ParseAndRun(ctx, root, os.Args[1:], nil); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
Index ¶
- func FlagsFunc(fn func(f *flag.FlagSet)) (fset *flag.FlagSet)
- func Parse(root *Command, args []string) error
- func ParseAndRun(ctx context.Context, root *Command, args []string, options *RunOptions) error
- func Run(ctx context.Context, root *Command, options *RunOptions) error
- func UsageErrorf(format string, args ...any) error
- type Command
- type FlagConfig
- type FlagName
- type RunOptions
- type State
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FlagsFunc ¶
FlagsFunc builds a flag.FlagSet inline using flag.ContinueOnError.
Flags: cli.FlagsFunc(func(f *flag.FlagSet) {
f.Bool("verbose", false, "enable verbose output")
}),
func Parse ¶
Parse selects a command and parses its flags without running it. It returns flag.ErrHelp for -h or --help; ParseAndRun handles that case automatically.
func ParseAndRun ¶
ParseAndRun parses args and runs the selected command. It prints help and returns nil for -h or --help.
if err := cli.ParseAndRun(ctx, root, os.Args[1:], nil); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
func Run ¶
func Run(ctx context.Context, root *Command, options *RunOptions) error
Run executes the command selected by Parse. Usage errors print help to stderr; other errors are returned as-is. A nil ctx uses context.Background.
func UsageErrorf ¶ added in v0.7.0
UsageErrorf returns an error for invalid command arguments or flag combinations. Run prints the command's help before returning the underlying error.
if len(s.Args) == 0 {
return cli.UsageErrorf("must supply a name")
}
Types ¶
type Command ¶
type Command struct {
// Name identifies the command. It must start with a letter and contain only letters, digits,
// dashes, or underscores.
Name string
// Usage overrides the generated usage line. Angle brackets usually mark required arguments,
// square brackets optional arguments, and an ellipsis repeated arguments.
//
// Usage: "echo [flags] <text>..."
Usage string
// Summary is the one-line description used in command lists and, when Description is empty, in
// the command's help.
Summary string
// Description is the command's longer help text. Its first line is used in command lists when
// Summary is empty.
Description string
// Help overrides the generated help for --help and [UsageErrorf] errors on this command.
Help func(*Command) string
// Flags holds this command's [flag.FlagSet]. Subcommands inherit these flags unless they are
// marked [FlagConfig.Local].
Flags *flag.FlagSet
// FlagConfigs adds behavior to flags already defined in Flags. Each config must name a flag in
// Flags.
FlagConfigs []FlagConfig
// SubCommands are the commands available below this command. A command that only groups
// subcommands may leave Exec nil.
SubCommands []*Command
// Exec runs the selected command. Return [UsageErrorf] for invalid arguments or flag
// combinations so [Run] prints the command's help.
Exec func(ctx context.Context, s *State) error
// contains filtered or unexported fields
}
Command describes a command in a CLI.
type FlagConfig ¶ added in v0.7.0
type FlagConfig struct {
// Name is the flag's registered name.
Name string
// Short is a one-letter alias, such as "v" for --verbose.
Short string
// Required makes [Parse] fail unless the user explicitly sets the flag.
Required bool
// Local prevents subcommands from inheriting the flag.
Local bool
}
FlagConfig adds behavior to a flag already defined in Command.Flags.
type FlagName ¶ added in v0.8.0
FlagName ties a flag name to the type returned by State.GetFlag.
type RunOptions ¶
type RunOptions struct {
// Nil fields default to the corresponding os stream.
Stdin io.Reader
Stdout, Stderr io.Writer
}
RunOptions replaces the standard streams used by Run and ParseAndRun.
type State ¶
type State struct {
// Args holds positional arguments. Anything after "--" is included as-is.
Args []string
// Stdin, Stdout, and Stderr are the command's streams.
Stdin io.Reader
Stdout, Stderr io.Writer
// Cmd is the selected command.
Cmd *Command
// contains filtered or unexported fields
}
State contains the parsed inputs passed to Command.Exec.
func (*State) GetFlag ¶ added in v0.8.0
GetFlag returns a flag value as T, searching the selected command before its parents. Unknown names and type mismatches are programming errors: GetFlag panics, and Run returns the error.
verbose := s.GetFlag[bool]("verbose")
const count FlagName[int] = "count"
n := s.GetFlag(count)
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
cmd/echo
command
|
|
|
cmd/task
command
|
|
|
Package flagtype provides common flag.Value implementations.
|
Package flagtype provides common flag.Value implementations. |
|
Package graceful runs long-lived processes with signal handling and timeouts.
|
Package graceful runs long-lived processes with signal handling and timeouts. |
|
internal
|
|
|
helpdoc
Package helpdoc builds the default command help document.
|
Package helpdoc builds the default command help document. |
|
usage
Package usage builds and renders command help.
|
Package usage builds and renders command help. |
|
pkg
|
|
|
Package xflag parses flags interspersed with positional arguments.
|
Package xflag parses flags interspersed with positional arguments. |