Documentation
¶
Overview ¶
Package cli provides a lightweight library for building command-line applications using Go's standard library flag package. It extends flag functionality to support flags anywhere in command arguments.
Key features:
- Nested subcommands for organizing complex CLIs
- Flexible flag parsing, allowing flags anywhere in arguments
- Parent-to-child flag inheritance
- Type-safe flag access
- Automatic help text generation
- Command suggestions for misspelled inputs
Quick example:
root := &cli.Command{ Name: "echo", Usage: "echo [flags] <text>...", ShortHelp: "prints the provided text", Flags: cli.FlagsFunc(func(f *flag.FlagSet) { f.Bool("c", false, "capitalize the input") }), Exec: func(ctx context.Context, s *cli.State) error { output := strings.Join(s.Args, " ") if cli.GetFlag[bool](s, "c") { output = strings.ToUpper(output) } fmt.Fprintln(s.Stdout, output) return nil }, }
The package intentionally maintains a minimal API surface to serve as a building block for CLI applications while leveraging the standard library's flag package. This approach enables developers to build maintainable command-line tools quickly while focusing on application logic rather than framework complexity.
Index ¶
- func DefaultUsage(root *Command) string
- func FlagsFunc(fn func(f *flag.FlagSet)) *flag.FlagSet
- func GetFlag[T any](s *State, name string) T
- func Parse(root *Command, args []string) error
- func Run(ctx context.Context, root *Command, options *RunOptions) error
- type Command
- type FlagMetadata
- type RunOptions
- type State
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DefaultUsage ¶
DefaultUsage returns the default usage string for the command hierarchy. It is used when the command does not provide a custom usage function. The usage string includes the command's short help, usage pattern, available subcommands, and flags.
func FlagsFunc ¶
FlagsFunc is a helper function that creates a new flag.FlagSet and applies the given function to it. Intended for use in command definitions to simplify flag setup. Example usage:
cmd.Flags = cli.FlagsFunc(func(f *flag.FlagSet) { f.Bool("verbose", false, "enable verbose output") f.String("output", "", "output file") f.Int("count", 0, "number of items") })
func GetFlag ¶
GetFlag retrieves a flag value by name from the command hierarchy. It first checks the current command's flags, then walks up through parent commands.
If the flag doesn't exist or if the type doesn't match the requested type T an error will be raised in the Run function. This is an internal error and should never happen in normal usage. This ensures flag-related programming errors are caught early during development.
verbose := GetFlag[bool](state, "verbose") count := GetFlag[int](state, "count") path := GetFlag[string](state, "path")
func Parse ¶
Parse traverses the command hierarchy and parses arguments. It returns an error if parsing fails at any point.
This function is the main entry point for parsing command-line arguments and should be called with the root command and the arguments to parse, typically os.Args[1:]. Once parsing is complete, the root command is ready to be executed with the Run function.
func Run ¶
func Run(ctx context.Context, root *Command, options *RunOptions) error
Run executes the current command. It returns an error if the command has not been parsed or if the command has no execution function.
The options parameter may be nil, in which case default values are used. See RunOptions for more details.
Types ¶
type Command ¶
type Command struct { // Name is always a single word representing the command's name. It is used to identify the // command in the command hierarchy and in help text. Name string // Usage provides the command's full usage pattern. // // Example: "cli todo list [flags]" Usage string // ShortHelp is a brief description of the command's purpose. It is displayed in the help text // when the command is shown. ShortHelp string // UsageFunc is an optional function that can be used to generate a custom usage string for the // command. It receives the current command and should return a string with the full usage // pattern. UsageFunc func(*Command) string // Flags holds the command-specific flag definitions. Each command maintains its own flag set // for parsing arguments. Flags *flag.FlagSet // FlagsMetadata is an optional list of flag information to extend the FlagSet with additional // metadata. This is useful for tracking required flags. FlagsMetadata []FlagMetadata // SubCommands is a list of nested commands that exist under this command. SubCommands []*Command // Exec defines the command's execution logic. It receives the current application [State] and // returns an error if execution fails. This function is called when [Run] is invoked on the // command. Exec func(ctx context.Context, s *State) error // contains filtered or unexported fields }
Command represents a CLI command or subcommand within the application's command hierarchy.
type FlagMetadata ¶
type FlagMetadata struct { // Name is the flag's name. Must match the flag name in the flag set. Name string // Required indicates whether the flag is required. Required bool }
FlagMetadata holds additional metadata for a flag, such as whether it is required.
type RunOptions ¶
type RunOptions struct { // Stdin, Stdout, and Stderr are the standard input, output, and error streams for the command. // If any of these are nil, the command will use the default streams ([os.Stdin], [os.Stdout], // and [os.Stderr], respectively). Stdin io.Reader Stdout, Stderr io.Writer }
RunOptions specifies options for running a command.
type State ¶
type State struct { // Args contains the remaining arguments after flag parsing. Args []string // Standard I/O streams. Stdin io.Reader Stdout, Stderr io.Writer // contains filtered or unexported fields }
State holds command information during Exec function execution, allowing child commands to access parent flags. Use GetFlag to get flag values across the command hierarchy.