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

Silence some usage and error logging in Execute #168

Closed
wants to merge 1 commit 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 76 additions & 2 deletions cobra_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ package cobra

import (
"bytes"
"errors"
"fmt"
"github.com/spf13/pflag"
"os"
"reflect"
"runtime"
"strings"
"testing"
"text/template"

"github.com/spf13/pflag"
)

var _ = fmt.Println
Expand All @@ -25,6 +25,22 @@ var globalFlag1 bool
var flagEcho, rootcalled bool
var versionUsed int

type silentErr int

func (silentErr) Error() string { return "<nil>" }
func (silentErr) ShouldLogError() bool { return false }
func (silentErr) ShouldLogUsage() bool { return false }

type noErrorLogging int

func (noErrorLogging) Error() string { return "<nil>" }
func (noErrorLogging) ShouldLogError() bool { return false }

type noUsageLogging int

func (noUsageLogging) Error() string { return "<nil>" }
func (noUsageLogging) ShouldLogUsage() bool { return false }

const strtwoParentHelp = "help message for parent flag strtwo"
const strtwoChildHelp = "help message for child flag strtwo"

Expand Down Expand Up @@ -582,6 +598,64 @@ func TestSubcommandArgEvaluation(t *testing.T) {
}
}

func TestSilentError(t *testing.T) {
rootCmd := initializeWithRootCmd()

tests := []struct {
cmd *Command
logError bool
logUsage bool
}{
{
&Command{
Use: "silent",
RunE: func(cmd *Command, args []string) error {
return silentErr(1)
}}, false, false},
{
&Command{
Use: "nousage",
RunE: func(cmd *Command, args []string) error {
return noUsageLogging(2)
}}, true, false},
{
&Command{
Use: "noerror",
RunE: func(cmd *Command, args []string) error {
return noErrorLogging(3)
}}, false, true},
{
&Command{
Use: "regular",
RunE: func(cmd *Command, args []string) error {
return errors.New("Failed")
}}, true, true},
}

for _, tc := range tests {
rootCmd.AddCommand(tc.cmd)
}

for i, tc := range tests {
result := fullTester(rootCmd, tc.cmd.Use)
if result.Error == nil {
t.Fatalf("[%d] Err was nil", i)
}
hasError := strings.Contains(result.Output, "Error:")
hasUsage := strings.Contains(result.Output, "Usage:")

if hasError != tc.logError {
t.Errorf("[%d] Error was logged: %s", i, result.Output)
}

if hasUsage != tc.logUsage {
t.Errorf("[%d] Usage was logged: %s", i, result.Output)
}

}

}

func TestPersistentFlags(t *testing.T) {
fullSetupTest("echo -s something -p more here")

Expand Down
28 changes: 26 additions & 2 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,16 @@ type Command struct {
SuggestionsMinimumDistance int
}

// LogError can be implemented to toggle error logging when error is returned from RunE.
type LogError interface {
ShouldLogError() bool
}

// LogUsage can be implemented to toggle usage logging when error is returned from RunE.
type LogUsage interface {
ShouldLogUsage() bool
}

// os.Args[1:] by default, if desired, can be overridden
// particularly useful when testing.
func (c *Command) SetArgs(a []string) {
Expand Down Expand Up @@ -637,8 +647,22 @@ func (c *Command) Execute() (err error) {
cmd.HelpFunc()(cmd, args)
return nil
}
c.Println(cmd.UsageString())
c.Println("Error:", err.Error())

logError := true
logUsage := true

if le, ok := err.(LogError); ok {
logError = le.ShouldLogError()
}
if lu, ok := err.(LogUsage); ok {
logUsage = lu.ShouldLogUsage()
}
if logUsage {
c.Println(cmd.UsageString())
}
if logError {
c.Println("Error:", err.Error())
}
}

return
Expand Down