// Package subcmd provides a simple subcommand framework built on top of // the standard library's flag package. package subcmd import ( "context" "flag" "fmt" "io" "os" "os/exec" "sort" "strings" ) // ExitStatus represents the exit status of a command. type ExitStatus int const ( // ExitSuccess indicates the command completed successfully. ExitSuccess ExitStatus = 0 // ExitFailure indicates the command failed. ExitFailure ExitStatus = 1 ) // Command is the interface that must be implemented by all subcommands. type Command interface { // Name returns the name of the command. Name() string // Synopsis returns a short one-line description of the command. Synopsis() string // Usage returns a more detailed usage message for the command. Usage() string // SetFlags sets up command-specific flags on the provided FlagSet. SetFlags(f *flag.FlagSet) // Execute runs the command with the given context, FlagSet, and optional arguments. Execute(ctx context.Context, f *flag.FlagSet, args ...any) ExitStatus } // commandGroup holds a command and its associated group. type commandGroup struct { cmd Command group string } // Registry manages subcommand registration and execution. type Registry struct { commands map[string]*commandGroup stdout io.Writer stderr io.Writer flags *flag.FlagSet errorHandling flag.ErrorHandling } // 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. func WithOutput(w io.Writer) Option { return func(r *Registry) { r.stdout = w r.stderr = w } } // 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 } } // 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 } } // 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 } } // 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), stdout: os.Stdout, stderr: os.Stderr, errorHandling: flag.ExitOnError, } for _, opt := range opts { opt(r) } r.flags = flag.NewFlagSet(os.Args[0], r.errorHandling) r.flags.SetOutput(r.stderr) r.flags.Usage = r.printUsage return r } // 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 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, group: group, } } // Execute parses top-level flags and executes the appropriate subcommand. func (r *Registry) Execute(ctx context.Context, args ...any) ExitStatus { if err := r.flags.Parse(os.Args[1:]); err != nil { if err == flag.ErrHelp { return ExitSuccess } return ExitFailure } if r.flags.NArg() < 1 { r.printUsage() return ExitFailure } cmdName := r.flags.Arg(0) cg, ok := r.commands[cmdName] if !ok { fmt.Fprintf(r.stderr, "Unknown subcommand: %s\n", cmdName) return ExitFailure } fs := flag.NewFlagSet(cmdName, r.errorHandling) fs.SetOutput(r.stderr) fs.Usage = func() { fmt.Fprint(r.stdout, cg.cmd.Usage()) } cg.cmd.SetFlags(fs) if err := fs.Parse(r.flags.Args()[1:]); err != nil { if err == flag.ErrHelp { return ExitSuccess } return ExitFailure } return cg.cmd.Execute(ctx, fs, args...) } // 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()) fmt.Fprintf(r.stdout, "Subcommands:\n") names := make([]string, 0, len(r.commands)) for name := range r.commands { names = append(names, name) } sort.Strings(names) for _, name := range names { cmd := r.commands[name].cmd fmt.Fprintf(r.stdout, "\t%-16s %s\n", name, cmd.Synopsis()) } } // Commands returns all registered subcommands grouped by their group name. func (r *Registry) Commands() map[string][]Command { result := make(map[string][]Command) for _, cg := range r.commands { result[cg.group] = append(result[cg.group], cg.cmd) } // Sort commands within each group by name for group := range result { sort.Slice(result[group], func(i, j int) bool { return result[group][i].Name() < result[group][j].Name() }) } return result } // 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 } return nil } // Default registry used by package-level functions var defaultRegistry = NewRegistry() // 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 // 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 package-level // registry. func Flags() *flag.FlagSet { return defaultRegistry.Flags() } // Commands returns all registered subcommands from the default package-level // registry. func Commands() map[string][]Command { return defaultRegistry.Commands() } /****************************** * Out-of-the-box Subcommands * - HelpCommand * - ManHelpCommand * - CommandsCommand * - FlagsCommand ******************************/ type helpCommand struct { registry *Registry } // 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} } func (h *helpCommand) Name() string { return "help" } func (h *helpCommand) Synopsis() string { return "describe subcommands and their syntax" } func (h *helpCommand) Usage() string { return `help []: With an argument, prints detailed information about the specified subcommand. 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 { cmdName := f.Arg(0) cmd := h.registry.Command(cmdName) if cmd == nil { fmt.Fprintf(h.registry.stderr, "Unknown command: %s\n", cmdName) return ExitFailure } fmt.Fprintf(h.registry.stdout, "%s\n", cmd.Usage()) return ExitSuccess } // 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 groups := make([]string, 0, len(grouped)) for group := range grouped { groups = append(groups, group) } sort.Strings(groups) for _, group := range groups { if group != "" { fmt.Fprintf(h.registry.stdout, "%s:\n", group) } for _, cmd := range grouped[group] { // Format: " name synopsis" fmt.Fprintf(h.registry.stdout, " %-12s %s\n", cmd.Name(), cmd.Synopsis()) } fmt.Fprintf(h.registry.stdout, "\n") } fmt.Fprintf(h.registry.stdout, "Use 'help ' for more information about a command.\n") return ExitSuccess } type manHelpCommand struct { prefix string } // 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. // // If you're not providing man pages with your CLI, use [subcmd.HelpCommand] instead. func ManHelpCommand(prefix string) Command { return &manHelpCommand{prefix: prefix} } func (m *manHelpCommand) Name() string { return "help" } func (m *manHelpCommand) Synopsis() string { return "show manual page" } func (m *manHelpCommand) Usage() string { return "help []\n\nOpen the manual page for a subcommand.\n" } func (m *manHelpCommand) SetFlags(f *flag.FlagSet) {} func (m *manHelpCommand) Execute(ctx context.Context, f *flag.FlagSet, args ...any) ExitStatus { page := m.prefix if f.NArg() > 0 { for _, arg := range f.Args() { page = page + "-" + arg } } cmd := execCommand("man", page) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { return ExitFailure } return ExitSuccess } // execCommand is a thin wrapper around exec.Command to ease testing. var execCommand = func(name string, args ...string) *exec.Cmd { return exec.Command(name, args...) } type commandsCommand struct { registry *Registry } // CommandsCommand provides a `commands` subcommand that lists all // available subcommand names, one on each line. func CommandsCommand() Command { return &commandsCommand{registry: defaultRegistry} } func (c *commandsCommand) Name() string { return "commands" } func (c *commandsCommand) Synopsis() string { return "list all command names" } func (c *commandsCommand) Usage() string { return `commands: 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 { 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 } type flagsCommand struct { registry *Registry } // FlagsCommand provides a `flags` subcommand that lists the global // command flags. func FlagsCommand() Command { return &flagsCommand{registry: defaultRegistry} } func (f *flagsCommand) Name() string { return "flags" } func (f *flagsCommand) Synopsis() string { return "describe all known top-level flags" } func (f *flagsCommand) Usage() string { return `flags: 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) { fmt.Fprintf(&b, " -%s", fl.Name) if fl.DefValue != "" { fmt.Fprintf(&b, " (default: %s)", fl.DefValue) } fmt.Fprintf(&b, "\n %s\n", fl.Usage) }) if b.Len() == 0 { fmt.Fprintf(f.registry.stdout, "No top-level flags defined.\n") } else { fmt.Fprintf(f.registry.stdout, "Top-level flags:\n%s", b.String()) } return ExitSuccess }