cobracmd: unknown subcommands of a command group are usage errors (exit 2)

cobra rejects an unknown subcommand only at the root; "prog group nosuch"
printed the group's help and exited 0. Execute now calls StrictGroups
first (found in yamase-ctl while rolling out cobracmd/v0.1.0).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
terminarandClaude Opus 5.5 committed 2026-10-26 14:48:52 +01:00
1 parent 5288c4ce74
commit 5471863163
2 files changed
+37

No files matched your search

+30
View File
@@ -94,7 +94,13 @@ func IsUsage(err error) bool {
// Execute runs root and returns the exit code: 0, 2 for a usage error,
// 1 for any other error. cobra prints the error itself unless the
// command sets SilenceErrors.
//
// Before running, it makes every command group below root strict (see
// StrictGroups): cobra itself rejects an unknown subcommand only at the
// root ("prog nosuch"), while "prog group nosuch" printed the group's
// help and exited 0.
func Execute(root *cobra.Command) int {
StrictGroups(root)
err := root.Execute()
switch {
case err == nil:
@@ -106,6 +112,30 @@ func Execute(root *cobra.Command) int {
}
}
// StrictGroups makes every command below root that only groups
// subcommands (it has subcommands, no Run/RunE and no Args of its own)
// reject an unknown subcommand as a usage error; called without one it
// still prints its help (exit 0). Execute calls it; it is exported for
// programs that run root.Execute themselves.
func StrictGroups(root *cobra.Command) {
var walk func(c *cobra.Command)
walk = func(c *cobra.Command) {
for _, sub := range c.Commands() {
if sub.HasSubCommands() && !sub.Runnable() && sub.Args == nil {
sub.Args = func(cmd *cobra.Command, args []string) error {
if len(args) > 0 {
return Usage(fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath()))
}
return nil
}
sub.RunE = func(cmd *cobra.Command, _ []string) error { return cmd.Help() }
}
walk(sub)
}
}
walk(root)
}
// Completion replaces cobra's default completion command on root with
// "completion <bash|zsh|fish|powershell>": exactly one argument, one of
// Shells; anything else is a usage error. The script is cobra's own