Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
timidsmile opened this issue Apr 15, 2024 · 1 comment
Open

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

timidsmile opened this issue Apr 15, 2024 · 1 comment

Comments

@timidsmile
Copy link

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

@marckhouzam
Copy link
Collaborator

You can play around with adding the Args field.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants