aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--doc.go54
-rw-r--r--subcmd.go101
2 files changed, 111 insertions, 44 deletions
diff --git a/doc.go b/doc.go
index d38be35..0e38488 100644
--- a/doc.go
+++ b/doc.go
@@ -1,5 +1,5 @@
// Package subcmd provides a simple and flexible subcommand framework built on
-// top of the standard library's flag package.
+// top of the standard library's [flag] package.
//
// This package makes it easy to build command-line applications with multiple
// subcommands, similar to tools like git, docker, or kubectl. Each subcommand
@@ -7,9 +7,19 @@
//
// # Basic Usage
//
-// To use subcmd, implement the Command interface for each subcommand and
-// register them with a Registry. The framework handles parsing, flag management,
-// and command execution.
+// To use subcmd, implement the [subcmd.Command] interface for each subcommand and
+// [subcmd.Register] them. The library handles parsing, flag management, and command
+// execution.
+//
+// package main
+//
+// import (
+// "context"
+// "flag"
+// "fmt"
+// "git.sr.ht/~eugenetriguba/subcmd"
+// "os"
+// )
//
// type greetCmd struct {
// name string
@@ -22,11 +32,9 @@
// Prints a greeting message.
// `
// }
-//
// func (g *greetCmd) SetFlags(f *flag.FlagSet) {
// f.StringVar(&g.name, "name", "World", "name to greet")
// }
-//
// func (g *greetCmd) Execute(ctx context.Context, f *flag.FlagSet, args ...any) subcmd.ExitStatus {
// fmt.Printf("Hello, %s!\n", g.name)
// return subcmd.ExitSuccess
@@ -38,6 +46,23 @@
// os.Exit(int(subcmd.Execute(context.Background())))
// }
//
+// We'll see the following output when we run our new CLI:
+//
+// $ go build -o main
+// $ ./main
+// Usage: ./main <flags> <subcommand> <subcommand args>
+//
+// Subcommands:
+// greet greet a person
+// help describe subcommands and their syntax
+//
+// $ ./main help greet
+// greet -name <name>:
+// Prints a greeting message.
+//
+// $ ./main greet -name eugene
+// Hello, eugene!
+//
// # Command Groups
//
// Commands can be organized into groups for better help output:
@@ -50,15 +75,18 @@
//
// The package provides several built-in commands:
//
-// - HelpCommand() - Display help for all commands or a specific command
-// - ManHelpCommand(prefix) - Open man pages for commands (e.g., "myapp" and "myapp-subcommand")
-// - CommandsCommand() - List all available command names
-// - FlagsCommand() - List all top-level flags
+// - [subcmd.HelpCommand]
+// - [subcmd.ManHelpCommand]
+// - [subcmd.CommandsCommand]
+// - [subcmd.FlagsCommand]
//
// # Registry
//
-// While the package provides a default registry for convenience, you can
-// create custom registries for more control:
+// Many top-level functions, like [subcmd.Register], operate on a
+// global default package-level registry. This makes it easier to
+// use the library in the common case.
+//
+// However, you can create custom registries for more control:
//
// registry := subcmd.NewRegistry(subcmd.WithOutput(customWriter))
// registry.Register(&myCmd{}, "")
@@ -70,7 +98,7 @@
// # Top-level Flags
//
// To add top-level flags (flags that apply before the subcommand), use the
-// Flags() accessor:
+// [subcmd.Flags] accessor:
//
// verbose := subcmd.Flags().Bool("v", false, "verbose output")
// subcmd.Register(&myCmd{}, "")
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 <flags> <subcommand> <subcommand args>\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.
+//
+// - `<cli> 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.
+// - `<cli> help <subcmd>` 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 `<cli> 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) {