diff options
| -rw-r--r-- | .builds/test.yml | 9 | ||||
| -rw-r--r-- | .editorconfig | 25 | ||||
| -rw-r--r-- | .gitignore | 10 | ||||
| -rw-r--r-- | CHANGELOG.md | 9 | ||||
| -rw-r--r-- | LICENSE | 21 | ||||
| -rw-r--r-- | README.md | 80 | ||||
| -rw-r--r-- | doc.go | 76 | ||||
| -rw-r--r-- | go.mod | 7 | ||||
| -rw-r--r-- | go.sum | 4 | ||||
| -rwxr-xr-x | scripts/release.sh | 147 | ||||
| -rwxr-xr-x | scripts/test.sh | 13 | ||||
| -rw-r--r-- | subcmd.go | 289 | ||||
| -rw-r--r-- | subcmd_test.go | 342 |
13 files changed, 1032 insertions, 0 deletions
diff --git a/.builds/test.yml b/.builds/test.yml new file mode 100644 index 0000000..c676328 --- /dev/null +++ b/.builds/test.yml @@ -0,0 +1,9 @@ +image: archlinux +packages: + - go +sources: + - https://git.sr.ht/~eugenetriguba/subcmd +tasks: + - test: | + cd subcmd + ./scripts/test.sh diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..b5949b4 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,25 @@ +# https://editorconfig.org +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{sh,bash}] +indent_style = space +indent_size = 2 +# switch_case_indent: true is equivalent to -ci flag in shfmt +switch_case_indent = true + +[*.go] +indent_style = tab +indent_size = 4 + +[*.{yml,yaml}] +indent_style = space +indent_size = 2 + +[*.{md,markdown}] +trim_trailing_whitespace = false diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..651c285 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +# macOS +.DS_Store + +# Editors +/tags + +# Test output +/cover.out +/cover.html +/coverage*.out diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..743064c --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,9 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Eugene Triguba + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..e2b565b --- /dev/null +++ b/README.md @@ -0,0 +1,80 @@ +# subcmd + +[](https://godoc.org/git.sr.ht/~eugenetriguba/subcmd) + +[](https://builds.sr.ht/~eugenetriguba/subcmd/commits/main?) + +A simple and flexible subcommand framework for Go, built on top of the standard library's `flag` package. + +## Why subcmd? + +- **Simple** - Small 5-method interface and register your commands +- **Familiar** - Built on `flag.FlagSet` +- **Flexible** - Command groups, custom registries, and built-in help system +- **Lightweight** - Zero external dependencies for production use +- **Testable** - Custom registries make testing easy + +## Installation + +```bash +go get git.sr.ht/~eugenetriguba/subcmd +``` + +## Example + +```go +package main + +import ( + "context" + "flag" + "fmt" + "os" + + "git.sr.ht/~eugenetriguba/subcmd" +) + +type greetCmd struct { + name string +} + +func (g *greetCmd) Name() string { return "greet" } +func (g *greetCmd) Synopsis() string { return "greet a person" } +func (g *greetCmd) Usage() string { return "greet -name <name>: Prints a greeting" } + +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 +} + +func main() { + subcmd.Register(&greetCmd{}, "") + subcmd.Register(subcmd.HelpCommand(), "") + flag.Parse() + os.Exit(int(subcmd.Execute(context.Background()))) +} +``` + +```bash +$ go run main.go greet -name Alice +Hello, Alice! +``` + +## Documentation + +See the [GoDoc documentation](https://godoc.org/git.sr.ht/~eugenetriguba/subcmd) +for full documentation on: + +- Command interface implementation +- Organizing commands into groups +- Built-in commands (help, commands, flags) +- Custom registries for testing +- Advanced usage patterns + +## License + +See [LICENSE](./LICENSE) file for details. @@ -0,0 +1,76 @@ +// Package subcmd provides a simple and flexible subcommand framework built on +// 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 +// can have its own flags and logic while sharing common top-level flags. +// +// # 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. +// +// type greetCmd struct { +// name string +// } +// +// func (g *greetCmd) Name() string { return "greet" } +// func (g *greetCmd) Synopsis() string { return "greet a person" } +// func (g *greetCmd) Usage() string { +// return `greet -name <name>: +// 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 +// } +// +// func main() { +// // Register commands +// subcmd.Register(&greetCmd{}, "") +// subcmd.Register(subcmd.HelpCommand(), "") +// +// // Parse top-level flags +// flag.Parse() +// +// // Execute the subcommand +// ctx := context.Background() +// os.Exit(int(subcmd.Execute(ctx))) +// } +// +// # Command Groups +// +// Commands can be organized into groups for better help output: +// +// subcmd.Register(&listCmd{}, "Database Commands") +// subcmd.Register(&migrateCmd{}, "Database Commands") +// subcmd.Register(&statusCmd{}, "Utility Commands") +// +// # Built-in Commands +// +// The package provides several built-in commands: +// +// - HelpCommand() - Display help for all commands or a specific command +// - CommandsCommand() - List all available command names +// - FlagsCommand() - List all top-level flags +// +// # Registry +// +// While the package provides a default registry for convenience, you can +// create custom registries for more control: +// +// registry := subcmd.NewRegistry() +// registry.Register(&myCmd{}, "") +// registry.SetOutput(customWriter) +// status := registry.Execute(ctx) +// +// This is useful for testing or when building applications that need multiple +// independent command sets. +package subcmd @@ -0,0 +1,7 @@ +module git.sr.ht/~eugenetriguba/subcmd + +go 1.24.0 + +require git.sr.ht/~eugenetriguba/checkmate v0.4.0 + +require github.com/google/go-cmp v0.6.0 // indirect @@ -0,0 +1,4 @@ +git.sr.ht/~eugenetriguba/checkmate v0.4.0 h1:9BokIJjo5BF44q3pS4Kcuo7aooOrQCin1dBBQ5n+aOs= +git.sr.ht/~eugenetriguba/checkmate v0.4.0/go.mod h1:Pxv1PKcBSbOqmoEOZxOBJVv9dHUGU+zcwuwfnGqZEQk= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= diff --git a/scripts/release.sh b/scripts/release.sh new file mode 100755 index 0000000..f8f564b --- /dev/null +++ b/scripts/release.sh @@ -0,0 +1,147 @@ +#!/usr/bin/env bash +# +# Release script for subcmd package +# Updates version in CHANGELOG.md and README.md, creates git tag, and pushes + +set -euo pipefail + +# shellcheck disable=SC2155 +readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck disable=SC2155 +readonly PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" +readonly CHANGELOG="${PROJECT_ROOT}/CHANGELOG.md" +readonly README="${PROJECT_ROOT}/README.md" + +usage() { + cat <<EOF +Usage: $(basename "$0") VERSION + +Create a new release with the specified version. + +Arguments: + VERSION Semantic version number (e.g., 1.0.0, 0.2.1) + +Examples: + $(basename "$0") 1.0.0 + $(basename "$0") 0.2.1 +EOF + exit 1 +} + +main() { + if [[ $# -ne 1 ]]; then + usage + fi + + local version="$1" + + validate_version "$version" + check_clean_working_tree + + echo "Release plan:" + echo " Version: $version" + echo " Update: $CHANGELOG" + echo " Update: $README" + echo " Create: git commit" + echo " Create: git tag v${version}" + echo " Push: commit and tag to origin/main" + echo + + if ! confirm "Proceed with release?"; then + echo "Release cancelled." + exit 0 + fi + + update_changelog "$version" + update_readme_badge "$version" + create_commit "$version" + create_tag "$version" + + echo + if confirm "Push to remote?"; then + push_changes "$version" + echo + echo "v${version} released!" + else + echo + echo "Changes committed and tagged locally." + echo "To push manually, run:" + echo " git push origin main" + echo " git push origin v${version}" + fi +} + +validate_version() { + local ver="$1" + if [[ ! "$ver" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + error "Invalid version format: $ver (expected: X.Y.Z)" + fi +} + +error() { + echo "Error: $*" >&2 + exit 1 +} + +confirm() { + local prompt="$1" + local response + read -r -p "$prompt [y/N] " response + [[ "$response" =~ ^[Yy]$ ]] +} + +check_clean_working_tree() { + if ! git diff-index --quiet HEAD --; then + error "Working tree has uncommitted changes. Please commit or stash them first." + fi +} + +update_changelog() { + local ver="$1" + local date + date="$(date +%Y-%m-%d)" + + if ! grep -q "## \[Unreleased\]" "$CHANGELOG"; then + error "Could not find [Unreleased] section in $CHANGELOG" + fi + + echo "Updating $CHANGELOG..." + sed -i.bak "s/## \[Unreleased\]/## [Unreleased]\n\n## [$ver] - $date/" "$CHANGELOG" + rm "${CHANGELOG}.bak" +} + +update_readme_badge() { + local ver="$1" + + if ! grep -q "img.shields.io/badge/version-" "$README"; then + error "Could not find version badge in $README" + fi + + echo "Updating version badge in $README..." + sed -i.bak "s/badge\/version-[0-9.]*-/badge\/version-${ver}-/" "$README" + rm "${README}.bak" +} + +create_commit() { + local ver="$1" + + echo "Creating git commit..." + git add "$CHANGELOG" "$README" + git commit -m "Release v${ver}" +} + +create_tag() { + local ver="$1" + + echo "Creating git tag v${ver}..." + git tag -a "v${ver}" -m "Release v${ver}" +} + +push_changes() { + local ver="$1" + echo "Pushing commit and tag to remote..." + git push origin main + git push origin "v${ver}" +} + +main "$@" diff --git a/scripts/test.sh b/scripts/test.sh new file mode 100755 index 0000000..955f5b0 --- /dev/null +++ b/scripts/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# +# Test script for subcmd package +# Runs all Go tests with verbose output +set -euo pipefail + +main() { + echo "Running tests..." + go test -v ./... + echo "✓ All tests passed" +} + +main "$@" diff --git a/subcmd.go b/subcmd.go new file mode 100644 index 0000000..c8dc55e --- /dev/null +++ b/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/subcmd_test.go b/subcmd_test.go new file mode 100644 index 0000000..726cef9 --- /dev/null +++ b/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") +} |