Skip to content

Commit 2ca7214

Browse files
authored
fix: Produce unknown subcommand errors for bad command names (#4089)
Fixes #1616
1 parent 8d7954b commit 2ca7214

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

cli/root.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,7 @@ func Root(subcommands []*cobra.Command) *cobra.Command {
165165
}
166166

167167
cmd.AddCommand(subcommands...)
168+
fixUnknownSubcommandError(cmd.Commands())
168169

169170
cmd.SetUsageTemplate(usageTemplate())
170171

@@ -187,6 +188,35 @@ func Root(subcommands []*cobra.Command) *cobra.Command {
187188
return cmd
188189
}
189190

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+
190220
// versionCmd prints the coder version
191221
func versionCmd() *cobra.Command {
192222
return &cobra.Command{

0 commit comments

Comments
 (0)