From b8b9d64012f07a48cf97394805a3368287ff41f2 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sat, 27 Dec 2025 18:26:05 -0500 Subject: Clarify godoc comments and provide more examples --- subcmd.go | 101 +++++++++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 70 insertions(+), 31 deletions(-) (limited to 'subcmd.go') diff --git a/subcmd.go b/subcmd.go index 6edfac0..388cc79 100644 --- a/subcmd.go +++ b/subcmd.go @@ -31,7 +31,7 @@ type Command interface { // Synopsis returns a short one-line description of the command. Synopsis() string - // Usage returns a detailed usage message for the command. + // Usage returns a more detailed usage message for the command. Usage() string // SetFlags sets up command-specific flags on the provided FlagSet. @@ -56,7 +56,8 @@ type Registry struct { errorHandling flag.ErrorHandling } -// Option configures a Registry. +// Option configures a Registry. Options may be passed to +// [subcmd.NewRegistry] to customize it's behavior. type Option func(*Registry) // WithOutput sets both stdout and stderr to the same writer. @@ -68,6 +69,7 @@ func WithOutput(w io.Writer) Option { } // WithStdout sets the help/usage output writer. +// By default, [os.Stdout] is used. func WithStdout(w io.Writer) Option { return func(r *Registry) { r.stdout = w @@ -75,6 +77,7 @@ func WithStdout(w io.Writer) Option { } // WithStderr sets the error output writer. +// By default, [os.Stderr] is used. func WithStderr(w io.Writer) Option { return func(r *Registry) { r.stderr = w @@ -82,6 +85,7 @@ func WithStderr(w io.Writer) Option { } // WithErrorHandling sets how flag parsing errors are handled. +// By default, [flag.ExitOnError] is used. func WithErrorHandling(e flag.ErrorHandling) Option { return func(r *Registry) { r.errorHandling = e @@ -89,6 +93,15 @@ func WithErrorHandling(e flag.ErrorHandling) Option { } // NewRegistry creates a new command registry. +// +// Options can be passed in to customize various aspects +// of the newly created registry: +// +// var buf bytes.Buffer +// r := NewRegistry( +// WithOutput(&buf), +// WithErrorHandling(flags.ContinueOnError), +// ) func NewRegistry(opts ...Option) *Registry { r := &Registry{ commands: make(map[string]*commandGroup), @@ -105,13 +118,21 @@ func NewRegistry(opts ...Option) *Registry { return r } -// Flags returns the top-level FlagSet for adding program-wide flags. +// Flags returns the top-level [flag.FlagSet] for adding program-wide +// flags. +// +// e.g. +// +// verbose := subcmd.Flags().Bool("v", false, "verbose output") func (r *Registry) Flags() *flag.FlagSet { return r.flags } // Register registers a command with an optional group name. -// If a command with the same name already exists, it will be overwritten. +// +// If a command with the same name already exists, it will be +// overwritten. If you don't want to use a group, you can provide +// an empty string as the group to signify no group. func (r *Registry) Register(cmd Command, group string) { r.commands[cmd.Name()] = &commandGroup{ cmd: cmd, @@ -157,6 +178,9 @@ func (r *Registry) Execute(ctx context.Context, args ...any) ExitStatus { } // printUsage prints usage information when no subcommand is specified. +// +// It is intended to be the usage information for the top-level CLI, so +// it outputs the available subcommands. func (r *Registry) printUsage() { fmt.Fprintf(r.stdout, "Usage: %s \n\n", r.flags.Name()) @@ -172,7 +196,7 @@ func (r *Registry) printUsage() { } } -// Commands returns all registered commands grouped by their group name. +// Commands returns all registered subcommands grouped by their group name. func (r *Registry) Commands() map[string][]Command { result := make(map[string][]Command) @@ -190,7 +214,7 @@ func (r *Registry) Commands() map[string][]Command { return result } -// Command returns the command with the given name, or nil if not found. +// Command returns the subcommand with the given name, or nil if not found. func (r *Registry) Command(name string) Command { if cg, ok := r.commands[name]; ok { return cg.cmd @@ -201,32 +225,51 @@ func (r *Registry) Command(name string) Command { // Default registry used by package-level functions var defaultRegistry = NewRegistry() -// Register registers a command with the default registry. +// Register registers a command with the default package-level +// registry. func Register(cmd Command, group string) { defaultRegistry.Register(cmd, group) } -// Execute parses flags and executes a subcommand using the default registry. +// Execute parses flags and executes a subcommand using the default +// package-level registry. func Execute(ctx context.Context, args ...any) ExitStatus { return defaultRegistry.Execute(ctx, args...) } -// Flags returns the top-level FlagSet from the default registry. +// Flags returns the top-level FlagSet from the default package-level +// registry. func Flags() *flag.FlagSet { return defaultRegistry.Flags() } -// Commands returns all registered commands from the default registry. +// Commands returns all registered subcommands from the default package-level +// registry. func Commands() map[string][]Command { return defaultRegistry.Commands() } -// helpCommand implements the built-in help command. +/****************************** + * Out-of-the-box Subcommands + * - HelpCommand + * - ManHelpCommand + * - CommandsCommand + * - FlagsCommand + ******************************/ + type helpCommand struct { registry *Registry } -// HelpCommand returns a command that prints help information. +// HelpCommand provides a `help` subcommand that prints help +// information based on the [subcmd.Command.Name], [subcmd.Command.Usage], +// and [subcmd.Command.Synopsis] of each subcommand. +// +// - ` help` prints the root command's [subcmd.Command.Usage] and +// all the available registered subcommands names via [subcmd.Command.Name], +// using their [subcmd.Command.Synopsis] to give a brief overview of each +// subcommand. +// - ` help ` prints the subcommand's [subcmd.Command.Usage]. func HelpCommand() Command { return &helpCommand{registry: defaultRegistry} } @@ -239,9 +282,7 @@ func (h *helpCommand) Usage() string { Without arguments, prints a list of all available subcommands. ` } - func (h *helpCommand) SetFlags(f *flag.FlagSet) {} - func (h *helpCommand) Execute(ctx context.Context, f *flag.FlagSet, args ...any) ExitStatus { // If a specific command is requested, show its detailed help if f.NArg() > 0 { @@ -258,7 +299,6 @@ func (h *helpCommand) Execute(ctx context.Context, f *flag.FlagSet, args ...any) // Otherwise, show all commands grouped by group fmt.Fprintf(h.registry.stdout, "Available commands:\n\n") - grouped := h.registry.Commands() // Sort group names for consistent output @@ -285,16 +325,22 @@ func (h *helpCommand) Execute(ctx context.Context, f *flag.FlagSet, args ...any) return ExitSuccess } -// manHelpCommand implements a help command that opens man pages. type manHelpCommand struct { prefix string } -// ManHelpCommand returns a help command that opens man pages. +// ManHelpCommand provides a `help` subcommand that opens man pages. +// +// The prefix is used to construct man page names. +// - For the root man page triggered by ` help`, it will look for a man +// page with the provided prefix name. +// - For subcommands, the provided prefix is concatenated with the subcommand +// name by a hyphen (`-`). +// +// This implies that if you use this `help` subcommand implementation, you should +// provide a man page for the root command, and a man page for each subcommand. // -// The prefix is used to construct man page names: "prefix" for -// the main page, "prefix-subcommand" for subcommand pages. This -// is a common convention e.g. git(1), git-commit(1), ... +// If you're not providing man pages with your CLI, use [subcmd.HelpCommand] instead. func ManHelpCommand(prefix string) Command { return &manHelpCommand{prefix: prefix} } @@ -328,12 +374,12 @@ var execCommand = func(name string, args ...string) *exec.Cmd { return exec.Command(name, args...) } -// commandsCommand implements the built-in commands listing command. type commandsCommand struct { registry *Registry } -// CommandsCommand returns a command that lists all available commands. +// CommandsCommand provides a `commands` subcommand that lists all +// available subcommand names, one on each line. func CommandsCommand() Command { return &commandsCommand{registry: defaultRegistry} } @@ -345,30 +391,25 @@ func (c *commandsCommand) Usage() string { List all available command names, one per line. ` } - func (c *commandsCommand) SetFlags(f *flag.FlagSet) {} - func (c *commandsCommand) Execute(ctx context.Context, f *flag.FlagSet, args ...any) ExitStatus { - // Get all command names and sort them names := make([]string, 0, len(c.registry.commands)) for name := range c.registry.commands { names = append(names, name) } sort.Strings(names) - for _, name := range names { fmt.Fprintf(c.registry.stdout, "%s\n", name) } - return ExitSuccess } -// flagsCommand implements the built-in flags command. type flagsCommand struct { registry *Registry } -// FlagsCommand returns a command that lists global flags. +// FlagsCommand provides a `flags` subcommand that lists the global +// command flags. func FlagsCommand() Command { return &flagsCommand{registry: defaultRegistry} } @@ -380,9 +421,7 @@ func (f *flagsCommand) Usage() string { List all top-level flags with their descriptions. ` } - func (f *flagsCommand) SetFlags(fs *flag.FlagSet) {} - func (f *flagsCommand) Execute(ctx context.Context, fs *flag.FlagSet, args ...any) ExitStatus { var b strings.Builder f.registry.flags.VisitAll(func(fl *flag.Flag) { -- cgit v1.2.3