Open timidsmile opened 7 months ago
You can play around with adding the Args
field.
If you search issues you’ll find there have been multiple discussions about this.
I think the main problem is here:
https://github.com/spf13/cobra/blob/e94f6d0dd9a5e5738dca6bce03c4b1207ffbc0ec/command.go#L925-L927
If we could just return another error code instead of flag.ErrHelp
lets say ErrUnknownSubcommand
then the outer error would be forwarded in the lines @timidsmile mentioned, and the user at the outside call of e.g. rootCmd.Execute()
could handle that error and print e.g. help or call os.exit(1)
- that would solve many problems here. When automating things with scripts we have otherwise no idea when a sub-command is not even implemented! Would this really break the API for the others? Should I pose a merge request with that patch?
In my opinion it must be possible to differentiate between calling help
and an unknown subcommand! So a few lines above the help command uses the same error code!
https://github.com/spf13/cobra/blob/e94f6d0dd9a5e5738dca6bce03c4b1207ffbc0ec/command.go#L905-L907
and the user at the outside call of e.g. rootCmd.Execute() could handle that error and print e.g. help or call os.exit(1)
This requires the caller to change their code to keep the current behavior, which breaks backwards compatibility. If this is important enough, then we could add this as an optional opt-in behavior.
Ok. What about a further flag in the Command
struct such like
type Command struct {
// everything else ...
ErrorOnUnknownSubcommand bool
}
Default is false - and we would then change the lines in Execute
like this
if !c.Runnable() {
if c.ErrorOnUnknownSubcommand {
return ErrUnknownSubcommand
} else {
return flag.ErrHelp
}
}
would that be fine? All users who really want this feature can just activate it - and all others will not care.
That seems reasonable
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:
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 :
When I execute:
I can get the following prompt without an error.
Expectations
Need to return error
Is there some special consideration here? https://github.com/spf13/cobra/blob/main/command.go#L1123