diff options
| author | Eugene Triguba <hello@eugenetriguba.com> | 2025-12-27 06:16:15 -0500 |
|---|---|---|
| committer | Eugene Triguba <hello@eugenetriguba.com> | 2025-12-27 06:16:15 -0500 |
| commit | c9b15a7c574929d29d4caa3bca27fd0d0755bbeb (patch) | |
| tree | 3be0574d75f85dabfa06a1896087b40a4ed9046e /subcmd.go | |
| parent | Release v0.3.0 (diff) | |
| download | subcmd-c9b15a7c574929d29d4caa3bca27fd0d0755bbeb.zip | |
Fix -h flag and use functional options
Diffstat (limited to 'subcmd.go')
| -rw-r--r-- | subcmd.go | 49 |
1 files changed, 33 insertions, 16 deletions
@@ -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() |