aboutsummaryrefslogtreecommitdiffstats
path: root/subcmd.go
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 /subcmd.go
parentRelease v0.4.0 (diff)
downloadsubcmd-7d3da0e6851240a8b701ef01c88a2cba6ebc96ff.zip
Use internal flagset within the registry
Diffstat (limited to 'subcmd.go')
-rw-r--r--subcmd.go106
1 files changed, 71 insertions, 35 deletions
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