diff options
| author | Eugene Triguba <hello@eugenetriguba.com> | 2025-10-13 11:30:07 -0400 |
|---|---|---|
| committer | Eugene Triguba <hello@eugenetriguba.com> | 2025-10-13 11:30:07 -0400 |
| commit | 2621190a1db1c0d255e036d401dd2e768fbc9af9 (patch) | |
| tree | f28e06477e15e694bb54928cc5f4598516097112 /subcmd.go | |
| parent | Release v0.1.0 (diff) | |
| download | subcmd-2621190a1db1c0d255e036d401dd2e768fbc9af9.zip | |
Show usage and help text when no subcommands are passed
Diffstat (limited to 'subcmd.go')
| -rw-r--r-- | subcmd.go | 25 |
1 files changed, 21 insertions, 4 deletions
@@ -78,7 +78,7 @@ func (r *Registry) Register(cmd Command, group string) { // It expects flag.Parse() to have been called already. func (r *Registry) Execute(ctx context.Context, args ...any) ExitStatus { if flag.NArg() < 1 { - fmt.Fprintf(r.output, "No subcommand specified. Use 'help' for available commands.\n") + r.printUsage() return ExitFailure } @@ -89,11 +89,8 @@ func (r *Registry) Execute(ctx context.Context, args ...any) ExitStatus { return ExitFailure } - // Create a new FlagSet for the subcommand fs := flag.NewFlagSet(cmdName, flag.ExitOnError) cg.cmd.SetFlags(fs) - - // Parse the subcommand flags (everything after the subcommand name) if err := fs.Parse(flag.Args()[1:]); err != nil { return ExitFailure } @@ -101,6 +98,26 @@ func (r *Registry) Execute(ctx context.Context, args ...any) ExitStatus { return cg.cmd.Execute(ctx, fs, args...) } +// 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.output, "Subcommands:\n") + names := make([]string, 0, len(r.commands)) + for name := range r.commands { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + cmd := r.commands[name].cmd + fmt.Fprintf(r.output, "\t%-16s %s\n", name, cmd.Synopsis()) + } +} + // Commands returns all registered commands grouped by their group name. func (r *Registry) Commands() map[string][]Command { result := make(map[string][]Command) |