aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorEugene Triguba <hello@eugenetriguba.com>2025-12-27 06:16:15 -0500
committerEugene Triguba <hello@eugenetriguba.com>2025-12-27 06:16:15 -0500
commitc9b15a7c574929d29d4caa3bca27fd0d0755bbeb (patch)
tree3be0574d75f85dabfa06a1896087b40a4ed9046e
parentRelease v0.3.0 (diff)
downloadsubcmd-c9b15a7c574929d29d4caa3bca27fd0d0755bbeb.zip
Fix -h flag and use functional options
-rw-r--r--CHANGELOG.md18
-rw-r--r--subcmd.go49
-rw-r--r--subcmd_test.go95
3 files changed, 93 insertions, 69 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 98a9549..f25a892 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- `WithOutput(io.Writer)` option for configuring registry output writer.
+- `WithErrorHandling(flag.ErrorHandling)` option for configuring flag parse error handling.
+
+### Changed
+
+- `NewRegistry` now accepts functional options instead of relying on setter methods.
+
+### Fixed
+
+- Subcommand `-h` flag now displays the command's Usage() string instead of empty output.
+
+### Removed
+
+- `Registry.SetOutput` method - use `WithOutput` option with `NewRegistry` instead.
+- Package-level `SetOutput` function - create a custom registry with `NewRegistry(WithOutput(w))`.
+
## [0.3.0] - 2025-12-27
### Added
diff --git a/subcmd.go b/subcmd.go
index 56f778b..22f1e45 100644
--- a/subcmd.go
+++ b/subcmd.go
@@ -49,21 +49,39 @@ type commandGroup struct {
// Registry manages subcommand registration and execution.
type Registry struct {
- commands map[string]*commandGroup
- output io.Writer
+ commands map[string]*commandGroup
+ output io.Writer
+ errorHandling flag.ErrorHandling
}
-// NewRegistry creates a new command registry.
-func NewRegistry() *Registry {
- return &Registry{
- commands: make(map[string]*commandGroup),
- output: os.Stdout,
+// Option configures a Registry.
+type Option func(*Registry)
+
+// WithOutput sets the output writer.
+func WithOutput(w io.Writer) Option {
+ return func(r *Registry) {
+ r.output = w
}
}
-// SetOutput sets the output writer for the registry.
-func (r *Registry) SetOutput(w io.Writer) {
- r.output = w
+// WithErrorHandling sets how flag parsing errors are handled.
+func WithErrorHandling(e flag.ErrorHandling) Option {
+ return func(r *Registry) {
+ r.errorHandling = e
+ }
+}
+
+// NewRegistry creates a new command registry.
+func NewRegistry(opts ...Option) *Registry {
+ r := &Registry{
+ commands: make(map[string]*commandGroup),
+ output: os.Stdout,
+ errorHandling: flag.ExitOnError,
+ }
+ for _, opt := range opts {
+ opt(r)
+ }
+ return r
}
// Register registers a command with an optional group name.
@@ -90,7 +108,11 @@ func (r *Registry) Execute(ctx context.Context, args ...any) ExitStatus {
return ExitFailure
}
- fs := flag.NewFlagSet(cmdName, flag.ExitOnError)
+ fs := flag.NewFlagSet(cmdName, r.errorHandling)
+ fs.SetOutput(r.output)
+ fs.Usage = func() {
+ fmt.Fprint(r.output, cg.cmd.Usage())
+ }
cg.cmd.SetFlags(fs)
if err := fs.Parse(flag.Args()[1:]); err != nil {
return ExitFailure
@@ -158,11 +180,6 @@ 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()
diff --git a/subcmd_test.go b/subcmd_test.go
index 57b86c2..bd3c083 100644
--- a/subcmd_test.go
+++ b/subcmd_test.go
@@ -33,32 +33,6 @@ func (m *mockCommand) Execute(ctx context.Context, f *flag.FlagSet, args ...any)
return m.exitStatus
}
-// testRegistryOption configures a test registry.
-type testRegistryOption func(*Registry)
-
-// withCommand adds a command to the registry.
-func withCommand(cmd Command, group string) testRegistryOption {
- return func(r *Registry) {
- r.Register(cmd, group)
- }
-}
-
-// withBuffer sets the output writer for the registry.
-func withBuffer(buf *bytes.Buffer) testRegistryOption {
- return func(r *Registry) {
- r.SetOutput(buf)
- }
-}
-
-// newTestRegistry creates a registry configured for testing with
-// the given options.
-func newTestRegistry(opts ...testRegistryOption) *Registry {
- r := NewRegistry()
- for _, opt := range opts {
- opt(r)
- }
- return r
-}
// setupOsArgs sets up os.Args and flag.CommandLine for testing,
// returning a cleanup function that restores the original state.
@@ -85,7 +59,7 @@ func TestRegistry_Register(t *testing.T) {
func TestRegistry_Execute_NoSubcommand(t *testing.T) {
var buf bytes.Buffer
- r := newTestRegistry(withBuffer(&buf))
+ r := NewRegistry(WithOutput(&buf))
cleanup := setupOsArgs("prog")
defer cleanup()
@@ -99,7 +73,7 @@ func TestRegistry_Execute_NoSubcommand(t *testing.T) {
func TestRegistry_Execute_UnknownSubcommand(t *testing.T) {
var buf bytes.Buffer
- r := newTestRegistry(withBuffer(&buf))
+ r := NewRegistry(WithOutput(&buf))
cleanup := setupOsArgs("prog", "unknown")
defer cleanup()
@@ -115,10 +89,8 @@ func TestRegistry_Execute_Success(t *testing.T) {
name: "test",
exitStatus: ExitSuccess,
}
- r := newTestRegistry(
- withBuffer(&buf),
- withCommand(cmd, ""),
- )
+ r := NewRegistry(WithOutput(&buf))
+ r.Register(cmd, "")
cleanup := setupOsArgs("prog", "test")
defer cleanup()
@@ -134,7 +106,8 @@ func TestRegistry_Execute_WithFlags(t *testing.T) {
name: "test",
exitStatus: ExitSuccess,
}
- r := newTestRegistry(withBuffer(&buf), withCommand(cmd, ""))
+ r := NewRegistry(WithOutput(&buf))
+ r.Register(cmd, "")
cleanup := setupOsArgs("prog", "test", "-test=value")
defer cleanup()
@@ -144,15 +117,34 @@ func TestRegistry_Execute_WithFlags(t *testing.T) {
check.Equal(t, cmd.flagValue, "value")
}
+func TestRegistry_Execute_HelpFlag(t *testing.T) {
+ var buf bytes.Buffer
+ cmd := &mockCommand{
+ name: "test",
+ usage: "test:\n This is the test command usage.\n",
+ }
+ r := NewRegistry(
+ WithOutput(&buf),
+ WithErrorHandling(flag.ContinueOnError),
+ )
+ r.Register(cmd, "")
+ cleanup := setupOsArgs("prog", "test", "-h")
+ defer cleanup()
+
+ status := r.Execute(context.Background())
+
+ check.Equal(t, status, ExitFailure)
+ check.Contains(t, buf.String(), "This is the test command usage.")
+}
+
func TestRegistry_Commands(t *testing.T) {
cmd1 := &mockCommand{name: "aaa", synopsis: "First"}
cmd2 := &mockCommand{name: "bbb", synopsis: "Second"}
cmd3 := &mockCommand{name: "ccc", synopsis: "Third"}
- r := newTestRegistry(
- withCommand(cmd2, "group1"),
- withCommand(cmd1, "group1"),
- withCommand(cmd3, "group2"),
- )
+ r := NewRegistry()
+ r.Register(cmd2, "group1")
+ r.Register(cmd1, "group1")
+ r.Register(cmd3, "group2")
commands := r.Commands()
@@ -199,11 +191,9 @@ func TestHelpCommand_NoArgs(t *testing.T) {
var buf bytes.Buffer
cmd1 := &mockCommand{name: "test1", synopsis: "Test command 1"}
cmd2 := &mockCommand{name: "test2", synopsis: "Test command 2"}
- r := newTestRegistry(
- withBuffer(&buf),
- withCommand(cmd1, "group1"),
- withCommand(cmd2, "group1"),
- )
+ r := NewRegistry(WithOutput(&buf))
+ r.Register(cmd1, "group1")
+ r.Register(cmd2, "group1")
help := &helpCommand{registry: r}
r.Register(help, "")
fs := flag.NewFlagSet("help", flag.ExitOnError)
@@ -226,7 +216,8 @@ func TestHelpCommand_WithArg(t *testing.T) {
name: "test",
usage: "test:\n This is a test command\n",
}
- r := newTestRegistry(withBuffer(&buf), withCommand(cmd, ""))
+ r := NewRegistry(WithOutput(&buf))
+ r.Register(cmd, "")
help := &helpCommand{registry: r}
r.Register(help, "")
fs := flag.NewFlagSet("help", flag.ExitOnError)
@@ -240,7 +231,7 @@ func TestHelpCommand_WithArg(t *testing.T) {
func TestHelpCommand_UnknownCommand(t *testing.T) {
var buf bytes.Buffer
- r := newTestRegistry(withBuffer(&buf))
+ r := NewRegistry(WithOutput(&buf))
help := &helpCommand{registry: r}
fs := flag.NewFlagSet("help", flag.ExitOnError)
fs.Parse([]string{"unknown"})
@@ -293,12 +284,10 @@ func TestManHelpCommand_WithSubcommand(t *testing.T) {
func TestCommandsCommand(t *testing.T) {
var buf bytes.Buffer
- r := newTestRegistry(
- withBuffer(&buf),
- withCommand(&mockCommand{name: "zzz"}, ""),
- withCommand(&mockCommand{name: "aaa"}, ""),
- withCommand(&mockCommand{name: "mmm"}, ""),
- )
+ r := NewRegistry(WithOutput(&buf))
+ r.Register(&mockCommand{name: "zzz"}, "")
+ r.Register(&mockCommand{name: "aaa"}, "")
+ r.Register(&mockCommand{name: "mmm"}, "")
cmds := &commandsCommand{registry: r}
r.Register(cmds, "")
fs := flag.NewFlagSet("commands", flag.ExitOnError)
@@ -318,7 +307,7 @@ func TestCommandsCommand(t *testing.T) {
func TestFlagsCommand_NoFlags(t *testing.T) {
var buf bytes.Buffer
- r := newTestRegistry(withBuffer(&buf))
+ r := NewRegistry(WithOutput(&buf))
flags := &flagsCommand{registry: r}
fs := flag.NewFlagSet("flags", flag.ExitOnError)
@@ -330,7 +319,7 @@ func TestFlagsCommand_NoFlags(t *testing.T) {
func TestFlagsCommand_WithFlags(t *testing.T) {
var buf bytes.Buffer
- r := newTestRegistry(withBuffer(&buf))
+ r := NewRegistry(WithOutput(&buf))
fs := flag.NewFlagSet("flags", flag.ExitOnError)
flag.String("testflag", "default", "test flag description")
flags := &flagsCommand{registry: r}