diff options
| -rw-r--r-- | CHANGELOG.md | 5 | ||||
| -rw-r--r-- | subcmd.go | 25 | ||||
| -rw-r--r-- | subcmd_test.go | 4 |
3 files changed, 29 insertions, 5 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index adf3e79..e99c87d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed + +- When no subcommands are specified, usage information and help text will be + shown with an exit code of 1. + ## [0.1.0] - 2025-10-13 - Initial Release @@ -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) diff --git a/subcmd_test.go b/subcmd_test.go index 726cef9..91c189d 100644 --- a/subcmd_test.go +++ b/subcmd_test.go @@ -63,7 +63,9 @@ func TestRegistry_Execute_NoSubcommand(t *testing.T) { status := r.Execute(context.Background()) check.Equal(t, status, ExitFailure) - check.Contains(t, buf.String(), "No subcommand specified") + output := buf.String() + check.Contains(t, output, "Usage: prog <flags> <subcommand> <subcommand args>") + check.Contains(t, output, "Subcommands:") } func TestRegistry_Execute_UnknownSubcommand(t *testing.T) { |