spf13/cobra

Need an error when the command is not found in the subcommand

timidsmile opened this issue · 1 comments

hi

Description

When I execute a job on our task center, I need to get the final result of the execution, for example:

myapp job1 args1

When job1 doesn't exist, I can get the error:

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

Then the task center can be accessed by echo $? to get the final execution result.
However, when I use a subcommand, I can't get the error.

How to reproduce

For example :

package main

import (
	"github.com/spf13/cobra"
)

func main() {
	var rootCmd = &cobra.Command{}

	configCmd := cobra.Command{
		Use: "config",
	}

	getCmd := cobra.Command{
		Use: "set",
		Run: func(cmd *cobra.Command, args []string) {
			println("this is the config set")
		},
	}
	setCmd := cobra.Command{
		Use: "get",
		Run: func(cmd *cobra.Command, args []string) {
			println("this is the config get")
		},
	}
	configCmd.AddCommand(&getCmd)
	configCmd.AddCommand(&setCmd)
	rootCmd.AddCommand(&configCmd)

	if err := rootCmd.Execute(); err != nil {
		panic(err.Error())
	}
}

When I execute:

myapp config xxx

I can get the following prompt without an error.

Usage:
   config [command]

Available Commands:
  get         
  set         

Flags:
  -h, --help   help for config

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

Expectations

Need to return error


Is there some special consideration here?
https://github.com/spf13/cobra/blob/main/command.go#L1123

You can play around with adding the Args field.

If you search issues you’ll find there have been multiple discussions about this.