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

Return error when usage was output due to non-runnable command #642

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 13 additions & 2 deletions command.go
Expand Up @@ -17,6 +17,7 @@ package cobra

import (
"bytes"
"errors"
"fmt"
"io"
"os"
Expand All @@ -27,6 +28,8 @@ import (
flag "github.com/spf13/pflag"
)

var NotRunnable = errors.New("Command not runnable; need subcommand.")

// Command is just that, a command for your application.
// E.g. 'go run ...' - 'run' is the command. Cobra requires
// you to define the usage and description as part of your command
Expand Down Expand Up @@ -308,7 +311,7 @@ func (c *Command) HelpFunc() func(*Command, []string) {
}
return func(c *Command, a []string) {
c.mergePersistentFlags()
err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)
err := tmpl(c.OutOrStderr(), c.HelpTemplate(), c)
if err != nil {
c.Println(err)
}
Expand Down Expand Up @@ -713,7 +716,7 @@ func (c *Command) execute(a []string) (err error) {
}

if !c.Runnable() {
return flag.ErrHelp
return NotRunnable
}

c.preRun()
Expand Down Expand Up @@ -849,6 +852,14 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
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,
// all subcommands should respect it
if !cmd.SilenceErrors && !c.SilenceErrors {
Expand Down
4 changes: 2 additions & 2 deletions command_test.go
Expand Up @@ -836,8 +836,8 @@ func TestHelpExecutedOnNonRunnableChild(t *testing.T) {
rootCmd.AddCommand(childCmd)

output, err := executeCommand(rootCmd, "child")
if err != nil {
t.Errorf("Unexpected error: %v", err)
if err != NotRunnable {
t.Error("Expected error for missing subcommand.")
}

checkStringContains(t, output, childCmd.Long)
Expand Down