added functionality to check the error message returned from Cobra, if any. for uage message text. If its present, the usage message gets truncated and the resulting message is returned to be used for the rest of the error message. If the resulting error is blank, no error message is printed

This commit is contained in:
Joel Scoble 2014-08-23 16:12:36 -05:00 committed by spf13
parent 4c735a7878
commit 4b979b17cc
2 changed files with 54 additions and 2 deletions

View file

@ -2,6 +2,7 @@ package utils
import (
"os"
"strings"
jww "github.com/spf13/jwalterweatherman"
)
@ -21,12 +22,35 @@ func CheckErr(err error, s ...string) {
func StopOnErr(err error, s ...string) {
if err != nil {
if len(s) == 0 {
jww.CRITICAL.Println(err)
newMessage := cutUsageMessage(err.Error())
// Printing an empty string results in a error with
// no message, no bueno.
if newMessage != "" {
jww.CRITICAL.Println(newMessage)
}
} else {
for _, message := range s {
message := cutUsageMessage(message)
if message != "" {
jww.CRITICAL.Println(message)
}
}
}
os.Exit(-1)
}
}
// cutUsageMessage splits the incoming string on the beginning of the usage
// message text. Anything in the first element of the returned slice, trimmed
// of its Unicode defined spaces, should be returned. The 2nd element of the
// slice will have the usage message that we wish to elide.
//
// This is done because Cobra already prints Hugo's usage message; not eliding
// would result in the usage output being printed twice, which leads to bug
// reports, more specifically: https://github.com/spf13/hugo/issues/374
func cutUsageMessage(s string) string {
pieces := strings.Split(s, "Usage of")
return strings.TrimSpace(pieces[0])
}

28
utils/utils_test.go Normal file
View file

@ -0,0 +1,28 @@
package utils
import (
"testing"
)
func TestCutUsageMessage(t *testing.T) {
tests := []struct{
message string
cutMessage string
}{
{"", ""},
{" Usage of hugo: \n -b, --baseUrl=...", ""},
{"Some error Usage of hugo: \n", "Some error"},
{"Usage of hugo: \n -b --baseU", ""},
{"CRITICAL error for usage of hugo ", "CRITICAL error for usage of hugo"},
{"Invalid short flag a in -abcde", "Invalid short flag a in -abcde"},
}
for _, test := range tests {
message := cutUsageMessage(test.message)
if message != test.cutMessage {
t.Errorf("Expected %#v, got %#v", test.cutMessage, message)
}
}
}