diff options
Diffstat (limited to 'internal/subcmd/subcmd.go')
| -rw-r--r-- | internal/subcmd/subcmd.go | 289 |
1 files changed, 0 insertions, 289 deletions
diff --git a/internal/subcmd/subcmd.go b/internal/subcmd/subcmd.go deleted file mode 100644 index c8dc55e..0000000 --- a/internal/subcmd/subcmd.go +++ /dev/null @@ -1,289 +0,0 @@ -// 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" - "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 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 - output io.Writer -} - -// NewRegistry creates a new command registry. -func NewRegistry() *Registry { - return &Registry{ - commands: make(map[string]*commandGroup), - output: os.Stdout, - } -} - -// SetOutput sets the output writer for the registry. -func (r *Registry) SetOutput(w io.Writer) { - r.output = w -} - -// Register registers a command with an optional group name. -// If a command with the same name already exists, it will be overwritten. -func (r *Registry) Register(cmd Command, group string) { - r.commands[cmd.Name()] = &commandGroup{ - cmd: cmd, - group: group, - } -} - -// Execute executes the subcommand specified in os.Args. -// It expects flag.Parse() to have been called already. -func (r *Registry) Execute(ctx context.Context, args ...any) ExitStatus { - if flag.NArg() < 1 { - fmt.Fprintf(r.output, "No subcommand specified. Use 'help' for available commands.\n") - return ExitFailure - } - - cmdName := flag.Arg(0) - cg, ok := r.commands[cmdName] - if !ok { - fmt.Fprintf(r.output, "Unknown subcommand: %s\n", cmdName) - return ExitFailure - } - - // Create a new FlagSet for the subcommand - fs := flag.NewFlagSet(cmdName, flag.ExitOnError) - cg.cmd.SetFlags(fs) - - // Parse the subcommand flags (everything after the subcommand name) - if err := fs.Parse(flag.Args()[1:]); err != nil { - return ExitFailure - } - - return cg.cmd.Execute(ctx, fs, args...) -} - -// Commands returns all registered commands 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 command 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 registry. -func Register(cmd Command, group string) { - defaultRegistry.Register(cmd, group) -} - -// Execute executes a subcommand using the default registry. -func Execute(ctx context.Context, args ...any) ExitStatus { - return defaultRegistry.Execute(ctx, args...) -} - -// SetOutput sets the output writer for the default registry. -func SetOutput(w io.Writer) { - defaultRegistry.SetOutput(w) -} - -// Commands returns all registered commands from the default registry. -func Commands() map[string][]Command { - return defaultRegistry.Commands() -} - -// helpCommand implements the built-in help command. -type helpCommand struct { - registry *Registry -} - -// HelpCommand returns a command that prints help information. -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 [<subcommand>]: - 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.output, "Unknown command: %s\n", cmdName) - return ExitFailure - } - - fmt.Fprintf(h.registry.output, "%s\n", cmd.Usage()) - return ExitSuccess - } - - // Otherwise, show all commands grouped by group - fmt.Fprintf(h.registry.output, "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.output, "%s:\n", group) - } - - for _, cmd := range grouped[group] { - // Format: " name synopsis" - fmt.Fprintf(h.registry.output, " %-12s %s\n", cmd.Name(), cmd.Synopsis()) - } - - fmt.Fprintf(h.registry.output, "\n") - } - - fmt.Fprintf(h.registry.output, "Use 'help <subcommand>' for more information about a command.\n") - return ExitSuccess -} - -// commandsCommand implements the built-in commands listing command. -type commandsCommand struct { - registry *Registry -} - -// CommandsCommand returns a command that lists all available commands. -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 { - // 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.output, "%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. -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 - flag.CommandLine.VisitAll(func(f *flag.Flag) { - fmt.Fprintf(&b, " -%s", f.Name) - if f.DefValue != "" { - fmt.Fprintf(&b, " (default: %s)", f.DefValue) - } - fmt.Fprintf(&b, "\n %s\n", f.Usage) - }) - - if b.Len() == 0 { - fmt.Fprintf(f.registry.output, "No top-level flags defined.\n") - } else { - fmt.Fprintf(f.registry.output, "Top-level flags:\n%s", b.String()) - } - - return ExitSuccess -} |