Maintain identical output

This commit is contained in:
Chris Williams 2018-02-26 11:11:58 -08:00
parent b3917f15b3
commit ddad852e88
2 changed files with 14 additions and 4 deletions

View file

@ -23,11 +23,13 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"sort" "sort"
"strings"
flag "github.com/spf13/pflag" flag "github.com/spf13/pflag"
"strings"
) )
var NotRunnable = errors.New("Command not runnable; need subcommand.")
// Command is just that, a command for your application. // Command is just that, a command for your application.
// E.g. 'go run ...' - 'run' is the command. Cobra requires // E.g. 'go run ...' - 'run' is the command. Cobra requires
// you to define the usage and description as part of your command // you to define the usage and description as part of your command
@ -714,7 +716,7 @@ func (c *Command) execute(a []string) (err error) {
} }
if !c.Runnable() { if !c.Runnable() {
return errors.New("Subcommand required.") return NotRunnable
} }
c.preRun() c.preRun()
@ -850,6 +852,14 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
return cmd, nil return cmd, nil
} }
// If command wasn't runnable, show full help, but do return the error.
// This will result in apps by default returning a non-success exit code, but also gives them the option to
// handle specially.
if err == NotRunnable {
cmd.HelpFunc()(cmd, args)
return cmd, err
}
// If root command has SilentErrors flagged, // If root command has SilentErrors flagged,
// all subcommands should respect it // all subcommands should respect it
if !cmd.SilenceErrors && !c.SilenceErrors { if !cmd.SilenceErrors && !c.SilenceErrors {

View file

@ -836,8 +836,8 @@ func TestHelpExecutedOnNonRunnableChild(t *testing.T) {
rootCmd.AddCommand(childCmd) rootCmd.AddCommand(childCmd)
output, err := executeCommand(rootCmd, "child") output, err := executeCommand(rootCmd, "child")
if err != nil { if err != NotRunnable {
t.Errorf("Unexpected error: %v", err) t.Error("Expected error for missing subcommand.")
} }
checkStringContains(t, output, childCmd.Long) checkStringContains(t, output, childCmd.Long)