aboutsummaryrefslogtreecommitdiffstats
path: root/subcmd.go
diff options
context:
space:
mode:
Diffstat (limited to 'subcmd.go')
-rw-r--r--subcmd.go25
1 files changed, 21 insertions, 4 deletions
diff --git a/subcmd.go b/subcmd.go
index c8dc55e..a8ed787 100644
--- a/subcmd.go
+++ b/subcmd.go
@@ -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)