diff options
| author | Eugene Triguba <hello@eugenetriguba.com> | 2025-10-11 10:44:54 -0400 |
|---|---|---|
| committer | Eugene Triguba <hello@eugenetriguba.com> | 2025-10-11 10:44:54 -0400 |
| commit | 52a46b604094f30e79842e55761731a5f625d300 (patch) | |
| tree | e67b7ecd9443e1db24a32987033e59b4a16606c2 | |
| parent | Add ability to exclude bolttest from test coverage statistics (diff) | |
| download | cli-52a46b604094f30e79842e55761731a5f625d300.zip | |
Remove google subcommands
| -rw-r--r-- | go.mod | 3 | ||||
| -rw-r--r-- | go.sum | 4 | ||||
| -rw-r--r-- | internal/cli/cli.go | 20 | ||||
| -rw-r--r-- | internal/commands/down.go | 18 | ||||
| -rw-r--r-- | internal/commands/new.go | 12 | ||||
| -rw-r--r-- | internal/commands/status.go | 20 | ||||
| -rw-r--r-- | internal/commands/up.go | 18 | ||||
| -rw-r--r-- | internal/commands/version.go | 8 | ||||
| -rw-r--r-- | internal/subcmd/subcmd.go | 289 | ||||
| -rw-r--r-- | internal/subcmd/subcmd_test.go | 342 |
10 files changed, 682 insertions, 52 deletions
@@ -5,11 +5,10 @@ go 1.23.0 toolchain go1.24.4 require ( - git.sr.ht/~eugenetriguba/checkmate v0.3.3 + git.sr.ht/~eugenetriguba/checkmate v0.4.0 git.sr.ht/~eugenetriguba/envelope v0.2.0 github.com/BurntSushi/toml v1.3.2 github.com/go-sql-driver/mysql v1.8.0 - github.com/google/subcommands v1.2.0 github.com/jackc/pgx/v5 v5.5.5 github.com/mattn/go-sqlite3 v1.14.22 github.com/microsoft/go-mssqldb v1.7.0 @@ -2,6 +2,8 @@ filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= git.sr.ht/~eugenetriguba/checkmate v0.3.3 h1:5qEwiDLRVcaI4Z5LRpUQYz0CIsSA9OuWxFB9GBDRMrk= git.sr.ht/~eugenetriguba/checkmate v0.3.3/go.mod h1:Pxv1PKcBSbOqmoEOZxOBJVv9dHUGU+zcwuwfnGqZEQk= +git.sr.ht/~eugenetriguba/checkmate v0.4.0 h1:9BokIJjo5BF44q3pS4Kcuo7aooOrQCin1dBBQ5n+aOs= +git.sr.ht/~eugenetriguba/checkmate v0.4.0/go.mod h1:Pxv1PKcBSbOqmoEOZxOBJVv9dHUGU+zcwuwfnGqZEQk= git.sr.ht/~eugenetriguba/envelope v0.2.0 h1:+vq3MENb2Xo1K7D/jZJcOHB9dBTbdHOEvzKoRtWyQpc= git.sr.ht/~eugenetriguba/envelope v0.2.0/go.mod h1:DcP27+64+elmsPbHqA90L/z3zkiyguRAk3wfKVBtnA8= github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.1 h1:lGlwhPtrX6EVml1hO0ivjkUxsSyl4dsiw9qcA1k/3IQ= @@ -31,8 +33,6 @@ github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EOqtpKwwwHI= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/subcommands v1.2.0 h1:vWQspBTo2nEqTUFita5/KeEWlUL8kQObDFbub/EN9oE= -github.com/google/subcommands v1.2.0/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= diff --git a/internal/cli/cli.go b/internal/cli/cli.go index b7f047b..2cd9622 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -5,21 +5,21 @@ import ( "flag" "git.sr.ht/~eugenetriguba/bolt/internal/commands" - "github.com/google/subcommands" + "git.sr.ht/~eugenetriguba/bolt/internal/subcmd" ) // Run runs the Bolt CLI and returns the exit code. func Run() int { - subcommands.Register(subcommands.HelpCommand(), "") - subcommands.Register(subcommands.FlagsCommand(), "") - subcommands.Register(subcommands.CommandsCommand(), "") - subcommands.Register(&commands.VersionCmd{}, "") - subcommands.Register(&commands.NewCmd{}, "") - subcommands.Register(&commands.UpCmd{}, "") - subcommands.Register(&commands.DownCmd{}, "") - subcommands.Register(&commands.StatusCmd{}, "") + subcmd.Register(subcmd.HelpCommand(), "") + subcmd.Register(subcmd.FlagsCommand(), "") + subcmd.Register(subcmd.CommandsCommand(), "") + subcmd.Register(&commands.VersionCmd{}, "") + subcmd.Register(&commands.NewCmd{}, "") + subcmd.Register(&commands.UpCmd{}, "") + subcmd.Register(&commands.DownCmd{}, "") + subcmd.Register(&commands.StatusCmd{}, "") flag.Parse() ctx := context.Background() - return int(subcommands.Execute(ctx)) + return int(subcmd.Execute(ctx)) } diff --git a/internal/commands/down.go b/internal/commands/down.go index 88e00d2..7f835e2 100644 --- a/internal/commands/down.go +++ b/internal/commands/down.go @@ -10,7 +10,7 @@ import ( "git.sr.ht/~eugenetriguba/bolt/internal/repositories" "git.sr.ht/~eugenetriguba/bolt/internal/services" "git.sr.ht/~eugenetriguba/bolt/internal/storage" - "github.com/google/subcommands" + "git.sr.ht/~eugenetriguba/bolt/internal/subcmd" ) type DownCmd struct { @@ -45,32 +45,32 @@ func (cmd *DownCmd) Execute( _ context.Context, f *flag.FlagSet, _ ...interface{}, -) subcommands.ExitStatus { +) subcmd.ExitStatus { consoleOutputter := output.NewConsoleOutputter() cfg, err := configloader.NewConfig() if err != nil { consoleOutputter.Error(fmt.Errorf("unable to retrieve configuration: %w", err)) - return subcommands.ExitFailure + return subcmd.ExitFailure } db, err := storage.NewDB(cfg.Connection) if err != nil { consoleOutputter.Error(fmt.Errorf("unable to connect to database: %w", err)) - return subcommands.ExitFailure + return subcmd.ExitFailure } defer db.Close() migrationDBRepo, err := repositories.NewMigrationDBRepo(cfg.Connection.MigrationsTable, db) if err != nil { consoleOutputter.Error(err) - return subcommands.ExitFailure + return subcmd.ExitFailure } migrationFsRepo, err := repositories.NewMigrationFsRepo(&cfg.Migrations) if err != nil { consoleOutputter.Error(err) - return subcommands.ExitFailure + return subcmd.ExitFailure } migrationService := services.NewMigrationService( @@ -84,15 +84,15 @@ func (cmd *DownCmd) Execute( err = migrationService.RevertAllMigrations() if err != nil { consoleOutputter.Error(fmt.Errorf("unable to revert all migrations: %w", err)) - return subcommands.ExitFailure + return subcmd.ExitFailure } } else { err = migrationService.RevertDownToVersion(cmd.version) if err != nil { consoleOutputter.Error(fmt.Errorf("unable to revert migrations down to %s: %w", cmd.version, err)) - return subcommands.ExitFailure + return subcmd.ExitFailure } } - return subcommands.ExitSuccess + return subcmd.ExitSuccess } diff --git a/internal/commands/new.go b/internal/commands/new.go index 0a2f9cc..5820317 100644 --- a/internal/commands/new.go +++ b/internal/commands/new.go @@ -9,7 +9,7 @@ import ( "git.sr.ht/~eugenetriguba/bolt/internal/output" "git.sr.ht/~eugenetriguba/bolt/internal/repositories" "git.sr.ht/~eugenetriguba/bolt/internal/services" - "github.com/google/subcommands" + "git.sr.ht/~eugenetriguba/bolt/internal/subcmd" ) type NewCmd struct { @@ -44,13 +44,13 @@ func (cmd *NewCmd) Execute( _ context.Context, f *flag.FlagSet, _ ...interface{}, -) subcommands.ExitStatus { +) subcmd.ExitStatus { consoleOutputter := output.NewConsoleOutputter() cfg, err := configloader.NewConfig() if err != nil { consoleOutputter.Error(fmt.Errorf("unable to retrieve configuration: %w", err)) - return subcommands.ExitFailure + return subcmd.ExitFailure } migrationFsRepo, err := repositories.NewMigrationFsRepo(&cfg.Migrations) @@ -58,7 +58,7 @@ func (cmd *NewCmd) Execute( consoleOutputter.Error( fmt.Errorf("unable to setup local migrations directory: %w", err), ) - return subcommands.ExitFailure + return subcmd.ExitFailure } migrationService := services.NewMigrationService( @@ -71,8 +71,8 @@ func (cmd *NewCmd) Execute( _, err = migrationService.CreateMigration(cmd.message) if err != nil { consoleOutputter.Error(fmt.Errorf("unable to create new migration: %w", err)) - return subcommands.ExitFailure + return subcmd.ExitFailure } - return subcommands.ExitSuccess + return subcmd.ExitSuccess } diff --git a/internal/commands/status.go b/internal/commands/status.go index 20d5667..6be2e8a 100644 --- a/internal/commands/status.go +++ b/internal/commands/status.go @@ -10,7 +10,7 @@ import ( "git.sr.ht/~eugenetriguba/bolt/internal/repositories" "git.sr.ht/~eugenetriguba/bolt/internal/services" "git.sr.ht/~eugenetriguba/bolt/internal/storage" - "github.com/google/subcommands" + "git.sr.ht/~eugenetriguba/bolt/internal/subcmd" ) type StatusCmd struct{} @@ -35,32 +35,32 @@ func (m *StatusCmd) Execute( _ context.Context, f *flag.FlagSet, _ ...interface{}, -) subcommands.ExitStatus { +) subcmd.ExitStatus { consoleOutputter := output.NewConsoleOutputter() cfg, err := configloader.NewConfig() if err != nil { consoleOutputter.Error(fmt.Errorf("unable to retrieve configuration: %w", err)) - return subcommands.ExitFailure + return subcmd.ExitFailure } db, err := storage.NewDB(cfg.Connection) if err != nil { consoleOutputter.Error(fmt.Errorf("unable to connect to database: %w", err)) - return subcommands.ExitFailure + return subcmd.ExitFailure } defer db.Close() migrationDBRepo, err := repositories.NewMigrationDBRepo(cfg.Connection.MigrationsTable, db) if err != nil { consoleOutputter.Error(err) - return subcommands.ExitFailure + return subcmd.ExitFailure } migrationFsRepo, err := repositories.NewMigrationFsRepo(&cfg.Migrations) if err != nil { consoleOutputter.Error(err) - return subcommands.ExitFailure + return subcmd.ExitFailure } migrationService := services.NewMigrationService( @@ -73,7 +73,7 @@ func (m *StatusCmd) Execute( migrations, err := migrationService.ListMigrations(services.SortOrderAsc) if err != nil { consoleOutputter.Error(fmt.Errorf("unable to list migrations: %w", err)) - return subcommands.ExitFailure + return subcmd.ExitFailure } if len(migrations) == 0 { @@ -81,7 +81,7 @@ func (m *StatusCmd) Execute( "No migrations have been created.\n" + "Run 'bolt new' to create your first migration.", ) - return subcommands.ExitSuccess + return subcmd.ExitSuccess } headers := []string{"Version", "Message", "Applied"} @@ -100,8 +100,8 @@ func (m *StatusCmd) Execute( consoleOutputter.Error( fmt.Errorf("unable to output migrations as table: %w", err), ) - return subcommands.ExitFailure + return subcmd.ExitFailure } - return subcommands.ExitSuccess + return subcmd.ExitSuccess } diff --git a/internal/commands/up.go b/internal/commands/up.go index ee93060..948f774 100644 --- a/internal/commands/up.go +++ b/internal/commands/up.go @@ -10,7 +10,7 @@ import ( "git.sr.ht/~eugenetriguba/bolt/internal/repositories" "git.sr.ht/~eugenetriguba/bolt/internal/services" "git.sr.ht/~eugenetriguba/bolt/internal/storage" - "github.com/google/subcommands" + "git.sr.ht/~eugenetriguba/bolt/internal/subcmd" ) type UpCmd struct { @@ -45,32 +45,32 @@ func (cmd *UpCmd) Execute( _ context.Context, f *flag.FlagSet, _ ...interface{}, -) subcommands.ExitStatus { +) subcmd.ExitStatus { consoleOutputter := output.NewConsoleOutputter() cfg, err := configloader.NewConfig() if err != nil { consoleOutputter.Error(fmt.Errorf("unable to retrieve configuration: %w", err)) - return subcommands.ExitFailure + return subcmd.ExitFailure } db, err := storage.NewDB(cfg.Connection) if err != nil { consoleOutputter.Error(fmt.Errorf("unable to connect to database: %w", err)) - return subcommands.ExitFailure + return subcmd.ExitFailure } defer db.Close() migrationDBRepo, err := repositories.NewMigrationDBRepo(cfg.Connection.MigrationsTable, db) if err != nil { consoleOutputter.Error(err) - return subcommands.ExitFailure + return subcmd.ExitFailure } migrationFsRepo, err := repositories.NewMigrationFsRepo(&cfg.Migrations) if err != nil { consoleOutputter.Error(err) - return subcommands.ExitFailure + return subcmd.ExitFailure } migrationService := services.NewMigrationService( @@ -84,15 +84,15 @@ func (cmd *UpCmd) Execute( err = migrationService.ApplyAllMigrations() if err != nil { consoleOutputter.Error(fmt.Errorf("unable to apply all migrations: %w", err)) - return subcommands.ExitFailure + return subcmd.ExitFailure } } else { err = migrationService.ApplyUpToVersion(cmd.version) if err != nil { consoleOutputter.Error(fmt.Errorf("unable to apply migrations up to %s: %w", cmd.version, err)) - return subcommands.ExitFailure + return subcmd.ExitFailure } } - return subcommands.ExitSuccess + return subcmd.ExitSuccess } diff --git a/internal/commands/version.go b/internal/commands/version.go index af837da..f917ca2 100644 --- a/internal/commands/version.go +++ b/internal/commands/version.go @@ -5,7 +5,7 @@ import ( "flag" "git.sr.ht/~eugenetriguba/bolt/internal/output" - "github.com/google/subcommands" + "git.sr.ht/~eugenetriguba/bolt/internal/subcmd" ) type VersionCmd struct{} @@ -30,13 +30,13 @@ func (cmd *VersionCmd) Execute( _ context.Context, f *flag.FlagSet, _ ...interface{}, -) subcommands.ExitStatus { +) subcmd.ExitStatus { consoleOutputter := output.NewConsoleOutputter() err := consoleOutputter.Output("bolt v0.11.0") if err != nil { consoleOutputter.Error(err) - return subcommands.ExitFailure + return subcmd.ExitFailure } - return subcommands.ExitSuccess + return subcmd.ExitSuccess } diff --git a/internal/subcmd/subcmd.go b/internal/subcmd/subcmd.go new file mode 100644 index 0000000..c8dc55e --- /dev/null +++ b/internal/subcmd/subcmd.go @@ -0,0 +1,289 @@ +// 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 new file mode 100644 index 0000000..726cef9 --- /dev/null +++ b/internal/subcmd/subcmd_test.go @@ -0,0 +1,342 @@ +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") +} |