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 2, 2019
1 parent 9400919 commit 97bd1b4
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
4 changes: 4 additions & 0 deletions docs/cmd/kn_revision.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ Revision command group

Revision command group

```
kn revision [flags]
```

### Options

```
Expand Down
4 changes: 4 additions & 0 deletions docs/cmd/kn_service.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ Service command group

Service command group

```
kn service [flags]
```

### Options

```
Expand Down
26 changes: 26 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,36 @@ 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()
fmt.Println()

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 sub-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 97bd1b4

Please sign in to comment.