@@ -165,6 +165,7 @@ func Root(subcommands []*cobra.Command) *cobra.Command {
165
165
}
166
166
167
167
cmd .AddCommand (subcommands ... )
168
+ fixUnknownSubcommandError (cmd .Commands ())
168
169
169
170
cmd .SetUsageTemplate (usageTemplate ())
170
171
@@ -187,6 +188,35 @@ func Root(subcommands []*cobra.Command) *cobra.Command {
187
188
return cmd
188
189
}
189
190
191
+ // fixUnknownSubcommandError modifies the provided commands so that the
192
+ // ones with subcommands output the correct error message when an
193
+ // unknown subcommand is invoked.
194
+ //
195
+ // Example:
196
+ //
197
+ // unknown command "bad" for "coder templates"
198
+ func fixUnknownSubcommandError (commands []* cobra.Command ) {
199
+ for _ , sc := range commands {
200
+ if sc .HasSubCommands () {
201
+ if sc .Run == nil && sc .RunE == nil {
202
+ if sc .Args != nil {
203
+ // In case the developer does not know about this
204
+ // behavior in Cobra they must verify correct
205
+ // behavior. For instance, settings Args to
206
+ // `cobra.ExactArgs(0)` will not give the same
207
+ // message as `cobra.NoArgs`. Likewise, omitting the
208
+ // run function will not give the wanted error.
209
+ panic ("developer error: subcommand has subcommands and Args but no Run or RunE" )
210
+ }
211
+ sc .Args = cobra .NoArgs
212
+ sc .Run = func (* cobra.Command , []string ) {}
213
+ }
214
+
215
+ fixUnknownSubcommandError (sc .Commands ())
216
+ }
217
+ }
218
+ }
219
+
190
220
// versionCmd prints the coder version
191
221
func versionCmd () * cobra.Command {
192
222
return & cobra.Command {
0 commit comments