diff options
| author | Eugene Triguba <hello@eugenetriguba.com> | 2025-10-13 09:41:56 -0400 |
|---|---|---|
| committer | Eugene Triguba <hello@eugenetriguba.com> | 2025-10-13 09:43:59 -0400 |
| commit | f869ca390c2685c5d5fa7d0756832c1b7e56c926 (patch) | |
| tree | 009ab9cf9fec4caad515f37b2fd64458d9791bbe /internal/subcmd | |
| parent | Revert "Add support for versioned docs" (diff) | |
| download | cli-f869ca390c2685c5d5fa7d0756832c1b7e56c926.zip | |
Extract out subcmd package to standalone library
Diffstat (limited to 'internal/subcmd')
| -rw-r--r-- | internal/subcmd/subcmd.go | 289 | ||||
| -rw-r--r-- | internal/subcmd/subcmd_test.go | 342 |
2 files changed, 0 insertions, 631 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 -} diff --git a/internal/subcmd/subcmd_test.go b/internal/subcmd/subcmd_test.go deleted file mode 100644 index 726cef9..0000000 --- a/internal/subcmd/subcmd_test.go +++ /dev/null @@ -1,342 +0,0 @@ -package subcmd - -import ( - "bytes" - "context" - "flag" - "os" - "strings" - "testing" - - "git.sr.ht/~eugenetriguba/checkmate/check" -) - -// mockCommand is a simple test command -type mockCommand struct { - name string - synopsis string - usage string - exitStatus ExitStatus - executed bool - flagValue string -} - -func (m *mockCommand) Name() string { return m.name } -func (m *mockCommand) Synopsis() string { return m.synopsis } -func (m *mockCommand) Usage() string { return m.usage } - -func (m *mockCommand) SetFlags(f *flag.FlagSet) { - f.StringVar(&m.flagValue, "test", "", "test flag") -} - -func (m *mockCommand) Execute(ctx context.Context, f *flag.FlagSet, args ...any) ExitStatus { - m.executed = true - return m.exitStatus -} - -func TestRegistry_Register(t *testing.T) { - r := NewRegistry() - - cmd1 := &mockCommand{name: "test1", synopsis: "Test command 1"} - cmd2 := &mockCommand{name: "test2", synopsis: "Test command 2"} - - r.Register(cmd1, "") - r.Register(cmd2, "group1") - - check.Equal(t, r.Command("test1"), cmd1) - check.Equal(t, r.Command("test2"), cmd2) - check.Nil(t, r.Command("nonexistent")) -} - -func TestRegistry_Execute_NoSubcommand(t *testing.T) { - r := NewRegistry() - var buf bytes.Buffer - r.SetOutput(&buf) - - // Simulate no subcommand - oldArgs := os.Args - os.Args = []string{"prog"} - flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError) - flag.Parse() - defer func() { os.Args = oldArgs }() - - status := r.Execute(context.Background()) - - check.Equal(t, status, ExitFailure) - check.Contains(t, buf.String(), "No subcommand specified") -} - -func TestRegistry_Execute_UnknownSubcommand(t *testing.T) { - r := NewRegistry() - var buf bytes.Buffer - r.SetOutput(&buf) - - oldArgs := os.Args - os.Args = []string{"prog", "unknown"} - flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError) - flag.Parse() - defer func() { os.Args = oldArgs }() - - status := r.Execute(context.Background()) - - check.Equal(t, status, ExitFailure) - check.Contains(t, buf.String(), "Unknown subcommand: unknown") -} - -func TestRegistry_Execute_Success(t *testing.T) { - r := NewRegistry() - var buf bytes.Buffer - r.SetOutput(&buf) - - cmd := &mockCommand{ - name: "test", - exitStatus: ExitSuccess, - } - r.Register(cmd, "") - - oldArgs := os.Args - os.Args = []string{"prog", "test"} - flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError) - flag.Parse() - defer func() { os.Args = oldArgs }() - - status := r.Execute(context.Background()) - - check.Equal(t, status, ExitSuccess) - check.Equal(t, cmd.executed, true) -} - -func TestRegistry_Execute_WithFlags(t *testing.T) { - r := NewRegistry() - var buf bytes.Buffer - r.SetOutput(&buf) - - cmd := &mockCommand{ - name: "test", - exitStatus: ExitSuccess, - } - r.Register(cmd, "") - - oldArgs := os.Args - os.Args = []string{"prog", "test", "-test=value"} - flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError) - flag.Parse() - defer func() { os.Args = oldArgs }() - - status := r.Execute(context.Background()) - - check.Equal(t, status, ExitSuccess) - check.Equal(t, cmd.flagValue, "value") -} - -func TestRegistry_Commands(t *testing.T) { - r := NewRegistry() - - cmd1 := &mockCommand{name: "aaa", synopsis: "First"} - cmd2 := &mockCommand{name: "bbb", synopsis: "Second"} - cmd3 := &mockCommand{name: "ccc", synopsis: "Third"} - - r.Register(cmd1, "group1") - r.Register(cmd2, "group1") - r.Register(cmd3, "group2") - - commands := r.Commands() - - check.Equal(t, len(commands), 2) - - group1 := commands["group1"] - check.Equal(t, len(group1), 2) - - // Check sorting - check.Equal(t, group1[0].Name(), "aaa") - check.Equal(t, group1[1].Name(), "bbb") - - group2 := commands["group2"] - check.Equal(t, len(group2), 1) -} - -func TestHelpCommand_NoArgs(t *testing.T) { - r := NewRegistry() - var buf bytes.Buffer - r.SetOutput(&buf) - - help := &helpCommand{registry: r} - r.Register(help, "") - - cmd1 := &mockCommand{name: "test1", synopsis: "Test command 1"} - cmd2 := &mockCommand{name: "test2", synopsis: "Test command 2"} - r.Register(cmd1, "group1") - r.Register(cmd2, "group1") - - fs := flag.NewFlagSet("help", flag.ExitOnError) - status := help.Execute(context.Background(), fs) - - check.Equal(t, status, ExitSuccess) - - output := buf.String() - check.Contains(t, output, "Available commands") - check.Contains(t, output, "test1") - check.Contains(t, output, "test2") - check.Contains(t, output, "Test command 1") -} - -func TestHelpCommand_WithArg(t *testing.T) { - r := NewRegistry() - var buf bytes.Buffer - r.SetOutput(&buf) - - help := &helpCommand{registry: r} - r.Register(help, "") - - cmd := &mockCommand{ - name: "test", - usage: "test:\n This is a test command\n", - } - r.Register(cmd, "") - - fs := flag.NewFlagSet("help", flag.ExitOnError) - fs.Parse([]string{"test"}) - - status := help.Execute(context.Background(), fs) - - check.Equal(t, status, ExitSuccess) - check.Contains(t, buf.String(), "This is a test command") -} - -func TestHelpCommand_UnknownCommand(t *testing.T) { - r := NewRegistry() - var buf bytes.Buffer - r.SetOutput(&buf) - - help := &helpCommand{registry: r} - - fs := flag.NewFlagSet("help", flag.ExitOnError) - fs.Parse([]string{"unknown"}) - - status := help.Execute(context.Background(), fs) - - check.Equal(t, status, ExitFailure) - check.Contains(t, buf.String(), "Unknown command: unknown") -} - -func TestCommandsCommand(t *testing.T) { - r := NewRegistry() - var buf bytes.Buffer - r.SetOutput(&buf) - - cmds := &commandsCommand{registry: r} - r.Register(cmds, "") - - r.Register(&mockCommand{name: "zzz"}, "") - r.Register(&mockCommand{name: "aaa"}, "") - r.Register(&mockCommand{name: "mmm"}, "") - - fs := flag.NewFlagSet("commands", flag.ExitOnError) - status := cmds.Execute(context.Background(), fs) - - check.Equal(t, status, ExitSuccess) - - output := buf.String() - lines := strings.Split(strings.TrimSpace(output), "\n") - - // Should be sorted alphabetically - check.Equal(t, len(lines), 4) - - expected := []string{"aaa", "commands", "mmm", "zzz"} - for i, line := range lines { - check.Equal(t, line, expected[i]) - } -} - -func TestFlagsCommand_NoFlags(t *testing.T) { - // Create a clean flag set - oldCommandLine := flag.CommandLine - flag.CommandLine = flag.NewFlagSet("test", flag.ExitOnError) - defer func() { flag.CommandLine = oldCommandLine }() - - r := NewRegistry() - var buf bytes.Buffer - r.SetOutput(&buf) - - flags := &flagsCommand{registry: r} - - fs := flag.NewFlagSet("flags", flag.ExitOnError) - status := flags.Execute(context.Background(), fs) - - check.Equal(t, status, ExitSuccess) - check.Contains(t, buf.String(), "No top-level flags defined") -} - -func TestFlagsCommand_WithFlags(t *testing.T) { - // Create a clean flag set with a test flag - oldCommandLine := flag.CommandLine - flag.CommandLine = flag.NewFlagSet("test", flag.ExitOnError) - flag.String("testflag", "default", "test flag description") - defer func() { flag.CommandLine = oldCommandLine }() - - r := NewRegistry() - var buf bytes.Buffer - r.SetOutput(&buf) - - flags := &flagsCommand{registry: r} - - fs := flag.NewFlagSet("flags", flag.ExitOnError) - status := flags.Execute(context.Background(), fs) - - check.Equal(t, status, ExitSuccess) - - output := buf.String() - check.Contains(t, output, "testflag") - check.Contains(t, output, "test flag description") -} - -func TestPackageLevelFunctions(t *testing.T) { - // Save and restore default registry - oldRegistry := defaultRegistry - defer func() { defaultRegistry = oldRegistry }() - - defaultRegistry = NewRegistry() - var buf bytes.Buffer - SetOutput(&buf) - - cmd := &mockCommand{ - name: "test", - synopsis: "Test command", - exitStatus: ExitSuccess, - } - - Register(cmd, "group1") - - // Test Commands() - commands := Commands() - check.Equal(t, len(commands["group1"]), 1) - - // Verify command is registered (use registry method) - check.Equal(t, defaultRegistry.Command("test"), cmd) - - // Test Execute() - oldArgs := os.Args - os.Args = []string{"prog", "test"} - flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError) - flag.Parse() - defer func() { os.Args = oldArgs }() - - status := Execute(context.Background()) - check.Equal(t, status, ExitSuccess) -} - -func TestExitStatus(t *testing.T) { - check.Equal(t, int(ExitSuccess), 0) - check.Equal(t, int(ExitFailure), 1) -} - -func TestBuiltInCommands(t *testing.T) { - help := HelpCommand() - check.Equal(t, help.Name(), "help") - - commands := CommandsCommand() - check.Equal(t, commands.Name(), "commands") - - flags := FlagsCommand() - check.Equal(t, flags.Name(), "flags") -} |