Skip to content

Commit

Permalink
fixes(issue #111) generically for all command groups
Browse files Browse the repository at this point in the history
Explores all sub-commands from root and adds a RunE for all
commands that are groups with child commands and without a RunE.
The added RunE will return the correct errors when the command
is called with empty sub-command or with an unknown sub-command.
It will also print the command help message first.
  • Loading branch information
maximilien committed Jul 1, 2019
1 parent 9400919 commit f1c0571
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions pkg/kn/core/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package core

import (
"errors"
"flag"
"fmt"
"os"
Expand Down Expand Up @@ -71,11 +72,33 @@ Eventing: Manage event subscriptions and channels. Connect up event sources.`,
rootCmd.AddCommand(commands.NewCompletionCommand(p))
rootCmd.AddCommand(commands.NewVersionCommand(p))

// Deal with empty and unknown sub command groups
emptyAndUnknownSubcommands(rootCmd)

// For glog parse error.
flag.CommandLine.Parse([]string{})
return rootCmd
}

// emptyAndUnknownSubcommands adds a RunE to all commands that are groups to
// deal with errors when called with empty or unknown sub command
func emptyAndUnknownSubcommands(cmd *cobra.Command) {
for _, childCmd := range cmd.Commands() {
if childCmd.HasSubCommands() && childCmd.RunE == nil {
childCmd.RunE = func(aCmd *cobra.Command, args []string) error {
aCmd.Help()
if len(args) == 0 {
return errors.New(fmt.Sprintf("please provide a valid sub-command for \"kn %s\"", aCmd.Name()))
} else {
return errors.New(fmt.Sprintf("unknown command \"%s\" for \"kn %s\"", args[0], aCmd.Name()))
}
}
// recurse to deal with child commands that are themselves command groups
emptyAndUnknownSubcommands(childCmd)
}
}
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
if commands.CfgFile != "" {
Expand Down

0 comments on commit f1c0571

Please sign in to comment.