aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorEugene Triguba <hello@eugenetriguba.com>2025-12-27 17:05:01 -0500
committerEugene Triguba <hello@eugenetriguba.com>2025-12-27 17:05:01 -0500
commit7d3da0e6851240a8b701ef01c88a2cba6ebc96ff (patch)
treeb74a831cd34a57cf7fe9f86f826c0d3e6e801874
parentRelease v0.4.0 (diff)
downloadsubcmd-7d3da0e6851240a8b701ef01c88a2cba6ebc96ff.zip
Use internal flagset within the registry
-rw-r--r--CHANGELOG.md20
-rw-r--r--README.md1
-rw-r--r--doc.go21
-rw-r--r--subcmd.go106
-rw-r--r--subcmd_test.go56
5 files changed, 135 insertions, 69 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1876f92..5edf071 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- `Flags()` method and package-level function to access the top-level FlagSet.
+- `WithStdout(io.Writer)` option for configuring help/usage output.
+- `WithStderr(io.Writer)` option for configuring error output.
+
+### Changed
+
+- `Registry` now owns its own FlagSet instead of using the global `flag.CommandLine`.
+- `Execute` now parses flags internally. Callers no longer need to call `flag.Parse()`.
+- `WithOutput(io.Writer)` now sets both stdout and stderr.
+- Only help/usage output goes to stdout now. Error messages now go to stderr.
+ Previously, all output was going to stdout.
+- Invoking the help flag now results in a successful exit code of 0 rather than
+ 1.
+
+### Fixed
+
+- Top-level `-h` flag now displays available subcommands instead of empty output.
+
## [0.4.0] - 2025-12-27
### Added
diff --git a/README.md b/README.md
index cf5d39d..492d926 100644
--- a/README.md
+++ b/README.md
@@ -58,7 +58,6 @@ func (g *greetCmd) Execute(ctx context.Context, f *flag.FlagSet, args ...any) su
func main() {
subcmd.Register(&greetCmd{}, "")
subcmd.Register(subcmd.HelpCommand(), "")
- flag.Parse()
os.Exit(int(subcmd.Execute(context.Background())))
}
```
diff --git a/doc.go b/doc.go
index eccb871..d38be35 100644
--- a/doc.go
+++ b/doc.go
@@ -33,16 +33,9 @@
// }
//
// 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)))
+// os.Exit(int(subcmd.Execute(context.Background())))
// }
//
// # Command Groups
@@ -67,11 +60,19 @@
// While the package provides a default registry for convenience, you can
// create custom registries for more control:
//
-// registry := subcmd.NewRegistry()
+// registry := subcmd.NewRegistry(subcmd.WithOutput(customWriter))
// 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.
+//
+// # Top-level Flags
+//
+// To add top-level flags (flags that apply before the subcommand), use the
+// Flags() accessor:
+//
+// verbose := subcmd.Flags().Bool("v", false, "verbose output")
+// subcmd.Register(&myCmd{}, "")
+// os.Exit(int(subcmd.Execute(context.Background())))
package subcmd
diff --git a/subcmd.go b/subcmd.go
index 22f1e45..6edfac0 100644
--- a/subcmd.go
+++ b/subcmd.go
@@ -50,17 +50,34 @@ type commandGroup struct {
// Registry manages subcommand registration and execution.
type Registry struct {
commands map[string]*commandGroup
- output io.Writer
+ stdout io.Writer
+ stderr io.Writer
+ flags *flag.FlagSet
errorHandling flag.ErrorHandling
}
// Option configures a Registry.
type Option func(*Registry)
-// WithOutput sets the output writer.
+// WithOutput sets both stdout and stderr to the same writer.
func WithOutput(w io.Writer) Option {
return func(r *Registry) {
- r.output = w
+ r.stdout = w
+ r.stderr = w
+ }
+}
+
+// WithStdout sets the help/usage output writer.
+func WithStdout(w io.Writer) Option {
+ return func(r *Registry) {
+ r.stdout = w
+ }
+}
+
+// WithStderr sets the error output writer.
+func WithStderr(w io.Writer) Option {
+ return func(r *Registry) {
+ r.stderr = w
}
}
@@ -75,15 +92,24 @@ func WithErrorHandling(e flag.ErrorHandling) Option {
func NewRegistry(opts ...Option) *Registry {
r := &Registry{
commands: make(map[string]*commandGroup),
- output: os.Stdout,
+ stdout: os.Stdout,
+ stderr: os.Stderr,
errorHandling: flag.ExitOnError,
}
for _, opt := range opts {
opt(r)
}
+ r.flags = flag.NewFlagSet(os.Args[0], r.errorHandling)
+ r.flags.SetOutput(r.stderr)
+ r.flags.Usage = r.printUsage
return r
}
+// Flags returns the top-level FlagSet for adding program-wide flags.
+func (r *Registry) Flags() *flag.FlagSet {
+ return r.flags
+}
+
// 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) {
@@ -93,28 +119,37 @@ func (r *Registry) Register(cmd Command, group string) {
}
}
-// Execute executes the subcommand specified in os.Args.
-// It expects flag.Parse() to have been called already.
+// Execute parses top-level flags and executes the appropriate subcommand.
func (r *Registry) Execute(ctx context.Context, args ...any) ExitStatus {
- if flag.NArg() < 1 {
+ if err := r.flags.Parse(os.Args[1:]); err != nil {
+ if err == flag.ErrHelp {
+ return ExitSuccess
+ }
+ return ExitFailure
+ }
+
+ if r.flags.NArg() < 1 {
r.printUsage()
return ExitFailure
}
- cmdName := flag.Arg(0)
+ cmdName := r.flags.Arg(0)
cg, ok := r.commands[cmdName]
if !ok {
- fmt.Fprintf(r.output, "Unknown subcommand: %s\n", cmdName)
+ fmt.Fprintf(r.stderr, "Unknown subcommand: %s\n", cmdName)
return ExitFailure
}
fs := flag.NewFlagSet(cmdName, r.errorHandling)
- fs.SetOutput(r.output)
+ fs.SetOutput(r.stderr)
fs.Usage = func() {
- fmt.Fprint(r.output, cg.cmd.Usage())
+ fmt.Fprint(r.stdout, cg.cmd.Usage())
}
cg.cmd.SetFlags(fs)
- if err := fs.Parse(flag.Args()[1:]); err != nil {
+ if err := fs.Parse(r.flags.Args()[1:]); err != nil {
+ if err == flag.ErrHelp {
+ return ExitSuccess
+ }
return ExitFailure
}
@@ -123,13 +158,9 @@ func (r *Registry) Execute(ctx context.Context, args ...any) ExitStatus {
// printUsage prints usage information when no subcommand is specified.
func (r *Registry) printUsage() {
- progName := "program"
- if len(os.Args) > 0 {
- progName = os.Args[0]
- }
- fmt.Fprintf(r.output, "Usage: %s <flags> <subcommand> <subcommand args>\n\n", progName)
+ fmt.Fprintf(r.stdout, "Usage: %s <flags> <subcommand> <subcommand args>\n\n", r.flags.Name())
- fmt.Fprintf(r.output, "Subcommands:\n")
+ fmt.Fprintf(r.stdout, "Subcommands:\n")
names := make([]string, 0, len(r.commands))
for name := range r.commands {
names = append(names, name)
@@ -137,7 +168,7 @@ func (r *Registry) printUsage() {
sort.Strings(names)
for _, name := range names {
cmd := r.commands[name].cmd
- fmt.Fprintf(r.output, "\t%-16s %s\n", name, cmd.Synopsis())
+ fmt.Fprintf(r.stdout, "\t%-16s %s\n", name, cmd.Synopsis())
}
}
@@ -175,11 +206,16 @@ func Register(cmd Command, group string) {
defaultRegistry.Register(cmd, group)
}
-// Execute executes a subcommand using the default registry.
+// Execute parses flags and executes a subcommand using the default registry.
func Execute(ctx context.Context, args ...any) ExitStatus {
return defaultRegistry.Execute(ctx, args...)
}
+// Flags returns the top-level FlagSet from the default registry.
+func Flags() *flag.FlagSet {
+ return defaultRegistry.Flags()
+}
+
// Commands returns all registered commands from the default registry.
func Commands() map[string][]Command {
return defaultRegistry.Commands()
@@ -212,16 +248,16 @@ func (h *helpCommand) Execute(ctx context.Context, f *flag.FlagSet, args ...any)
cmdName := f.Arg(0)
cmd := h.registry.Command(cmdName)
if cmd == nil {
- fmt.Fprintf(h.registry.output, "Unknown command: %s\n", cmdName)
+ fmt.Fprintf(h.registry.stderr, "Unknown command: %s\n", cmdName)
return ExitFailure
}
- fmt.Fprintf(h.registry.output, "%s\n", cmd.Usage())
+ fmt.Fprintf(h.registry.stdout, "%s\n", cmd.Usage())
return ExitSuccess
}
// Otherwise, show all commands grouped by group
- fmt.Fprintf(h.registry.output, "Available commands:\n\n")
+ fmt.Fprintf(h.registry.stdout, "Available commands:\n\n")
grouped := h.registry.Commands()
@@ -234,18 +270,18 @@ func (h *helpCommand) Execute(ctx context.Context, f *flag.FlagSet, args ...any)
for _, group := range groups {
if group != "" {
- fmt.Fprintf(h.registry.output, "%s:\n", group)
+ fmt.Fprintf(h.registry.stdout, "%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.stdout, " %-12s %s\n", cmd.Name(), cmd.Synopsis())
}
- fmt.Fprintf(h.registry.output, "\n")
+ fmt.Fprintf(h.registry.stdout, "\n")
}
- fmt.Fprintf(h.registry.output, "Use 'help <subcommand>' for more information about a command.\n")
+ fmt.Fprintf(h.registry.stdout, "Use 'help <subcommand>' for more information about a command.\n")
return ExitSuccess
}
@@ -321,7 +357,7 @@ func (c *commandsCommand) Execute(ctx context.Context, f *flag.FlagSet, args ...
sort.Strings(names)
for _, name := range names {
- fmt.Fprintf(c.registry.output, "%s\n", name)
+ fmt.Fprintf(c.registry.stdout, "%s\n", name)
}
return ExitSuccess
@@ -349,18 +385,18 @@ 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)
+ f.registry.flags.VisitAll(func(fl *flag.Flag) {
+ fmt.Fprintf(&b, " -%s", fl.Name)
+ if fl.DefValue != "" {
+ fmt.Fprintf(&b, " (default: %s)", fl.DefValue)
}
- fmt.Fprintf(&b, "\n %s\n", f.Usage)
+ fmt.Fprintf(&b, "\n %s\n", fl.Usage)
})
if b.Len() == 0 {
- fmt.Fprintf(f.registry.output, "No top-level flags defined.\n")
+ fmt.Fprintf(f.registry.stdout, "No top-level flags defined.\n")
} else {
- fmt.Fprintf(f.registry.output, "Top-level flags:\n%s", b.String())
+ fmt.Fprintf(f.registry.stdout, "Top-level flags:\n%s", b.String())
}
return ExitSuccess
diff --git a/subcmd_test.go b/subcmd_test.go
index bd3c083..e6e5301 100644
--- a/subcmd_test.go
+++ b/subcmd_test.go
@@ -34,13 +34,11 @@ func (m *mockCommand) Execute(ctx context.Context, f *flag.FlagSet, args ...any)
}
-// setupOsArgs sets up os.Args and flag.CommandLine for testing,
+// setupOsArgs sets up os.Args for testing,
// returning a cleanup function that restores the original state.
func setupOsArgs(args ...string) func() {
oldArgs := os.Args
os.Args = args
- flag.CommandLine = flag.NewFlagSet(args[0], flag.ExitOnError)
- flag.Parse()
return func() { os.Args = oldArgs }
}
@@ -59,9 +57,9 @@ func TestRegistry_Register(t *testing.T) {
func TestRegistry_Execute_NoSubcommand(t *testing.T) {
var buf bytes.Buffer
- r := NewRegistry(WithOutput(&buf))
cleanup := setupOsArgs("prog")
defer cleanup()
+ r := NewRegistry(WithOutput(&buf))
status := r.Execute(context.Background())
@@ -73,9 +71,9 @@ func TestRegistry_Execute_NoSubcommand(t *testing.T) {
func TestRegistry_Execute_UnknownSubcommand(t *testing.T) {
var buf bytes.Buffer
- r := NewRegistry(WithOutput(&buf))
cleanup := setupOsArgs("prog", "unknown")
defer cleanup()
+ r := NewRegistry(WithOutput(&buf))
status := r.Execute(context.Background())
@@ -89,10 +87,10 @@ func TestRegistry_Execute_Success(t *testing.T) {
name: "test",
exitStatus: ExitSuccess,
}
- r := NewRegistry(WithOutput(&buf))
- r.Register(cmd, "")
cleanup := setupOsArgs("prog", "test")
defer cleanup()
+ r := NewRegistry(WithOutput(&buf))
+ r.Register(cmd, "")
status := r.Execute(context.Background())
@@ -106,10 +104,10 @@ func TestRegistry_Execute_WithFlags(t *testing.T) {
name: "test",
exitStatus: ExitSuccess,
}
- r := NewRegistry(WithOutput(&buf))
- r.Register(cmd, "")
cleanup := setupOsArgs("prog", "test", "-test=value")
defer cleanup()
+ r := NewRegistry(WithOutput(&buf))
+ r.Register(cmd, "")
status := r.Execute(context.Background())
@@ -117,26 +115,45 @@ func TestRegistry_Execute_WithFlags(t *testing.T) {
check.Equal(t, cmd.flagValue, "value")
}
-func TestRegistry_Execute_HelpFlag(t *testing.T) {
+func TestRegistry_Execute_SubcommandHelpFlag(t *testing.T) {
var buf bytes.Buffer
cmd := &mockCommand{
name: "test",
usage: "test:\n This is the test command usage.\n",
}
+ cleanup := setupOsArgs("prog", "test", "-h")
+ defer cleanup()
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.Equal(t, status, ExitSuccess)
check.Contains(t, buf.String(), "This is the test command usage.")
}
+func TestRegistry_Execute_TopLevelHelpFlag(t *testing.T) {
+ var buf bytes.Buffer
+ cmd := &mockCommand{name: "test", synopsis: "Test command"}
+ cleanup := setupOsArgs("prog", "-h")
+ defer cleanup()
+ r := NewRegistry(
+ WithOutput(&buf),
+ WithErrorHandling(flag.ContinueOnError),
+ )
+ r.Register(cmd, "")
+
+ status := r.Execute(context.Background())
+
+ check.Equal(t, status, ExitSuccess)
+ output := buf.String()
+ check.Contains(t, output, "Usage: prog")
+ check.Contains(t, output, "test")
+}
+
func TestRegistry_Commands(t *testing.T) {
cmd1 := &mockCommand{name: "aaa", synopsis: "First"}
cmd2 := &mockCommand{name: "bbb", synopsis: "Second"}
@@ -320,21 +337,14 @@ func TestFlagsCommand_NoFlags(t *testing.T) {
func TestFlagsCommand_WithFlags(t *testing.T) {
var buf bytes.Buffer
r := NewRegistry(WithOutput(&buf))
+ r.Flags().String("testflag", "default", "test flag description")
+ cmd := &flagsCommand{registry: r}
fs := flag.NewFlagSet("flags", flag.ExitOnError)
- flag.String("testflag", "default", "test flag description")
- flags := &flagsCommand{registry: r}
- status := flags.Execute(context.Background(), fs)
+ status := cmd.Execute(context.Background(), fs)
check.Equal(t, status, ExitSuccess)
output := buf.String()
- check.Equal(
- t,
- output,
- `Top-level flags:
- -testflag (default: default)
- test flag description
-`)
check.Contains(t, output, "testflag")
check.Contains(t, output, "test flag description")
}