From 2ca72142592093a1f2e7778f3ca000d4cd4e4301 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Tue, 20 Sep 2022 15:31:38 +0300 Subject: [PATCH] fix: Produce unknown subcommand errors for bad command names (#4089) Fixes #1616 --- cli/root.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/cli/root.go b/cli/root.go index fc460265af..3179823a2a 100644 --- a/cli/root.go +++ b/cli/root.go @@ -165,6 +165,7 @@ func Root(subcommands []*cobra.Command) *cobra.Command { } cmd.AddCommand(subcommands...) + fixUnknownSubcommandError(cmd.Commands()) cmd.SetUsageTemplate(usageTemplate()) @@ -187,6 +188,35 @@ func Root(subcommands []*cobra.Command) *cobra.Command { return cmd } +// fixUnknownSubcommandError modifies the provided commands so that the +// ones with subcommands output the correct error message when an +// unknown subcommand is invoked. +// +// Example: +// +// unknown command "bad" for "coder templates" +func fixUnknownSubcommandError(commands []*cobra.Command) { + for _, sc := range commands { + if sc.HasSubCommands() { + if sc.Run == nil && sc.RunE == nil { + if sc.Args != nil { + // In case the developer does not know about this + // behavior in Cobra they must verify correct + // behavior. For instance, settings Args to + // `cobra.ExactArgs(0)` will not give the same + // message as `cobra.NoArgs`. Likewise, omitting the + // run function will not give the wanted error. + panic("developer error: subcommand has subcommands and Args but no Run or RunE") + } + sc.Args = cobra.NoArgs + sc.Run = func(*cobra.Command, []string) {} + } + + fixUnknownSubcommandError(sc.Commands()) + } + } +} + // versionCmd prints the coder version func versionCmd() *cobra.Command { return &cobra.Command{