cobra icon indicating copy to clipboard operation
cobra copied to clipboard

Return "unknown command" error for unknown subcommands.

Open MAnyKey opened this issue 6 years ago • 19 comments

Right now there is a difference in handling between unknown command and unknown subcommand. Let's consider the example:

package main

import "github.com/spf13/cobra"

func main() {

	subCmd := &cobra.Command{
		Use: "foo",
	}
	subCmd.AddCommand(&cobra.Command{
		Use: "bar",
		Run: func(cmd *cobra.Command, args []string) {
			cmd.Println("bar")
		},
	})
	subCmd.AddCommand(&cobra.Command{
		Use: "baz",
		Run: func(cmd *cobra.Command, args []string) {
			cmd.Println("baz")
		},
	})

	rootCmd := &cobra.Command{
		Use: "test",
	}
	rootCmd.AddCommand(subCmd)
	rootCmd.Execute()
}

When I run it as ./test unknown I get 'unknown command' error:

Error: unknown command "unknown" for "test"
Run 'test --help' for usage.

If I run it as ./test foo unknown I receive help message:

$ go run main.go foo unknown
Usage:
  test foo [command]

Available Commands:
  bar         
  baz         

Flags:
  -h, --help   help for foo

Use "test foo [command] --help" for more information about a command.

It seems very much like inconsistency.

I suppose that we don't need to return flag.ErrHelp on not runnable command and treat it like "unknown subcommand".

MAnyKey avatar Jun 15 '18 07:06 MAnyKey