From c9b15a7c574929d29d4caa3bca27fd0d0755bbeb Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sat, 27 Dec 2025 06:16:15 -0500 Subject: Fix -h flag and use functional options --- subcmd.go | 49 +++++++++++++++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 16 deletions(-) (limited to 'subcmd.go') 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() -- cgit v1.2.3