diff options
Diffstat (limited to 'utils')
-rw-r--r-- | utils/utils.go | 28 | ||||
-rw-r--r-- | utils/utils_test.go | 28 |
2 files changed, 54 insertions, 2 deletions
diff --git a/utils/utils.go b/utils/utils.go index 9d6e0a844..df54737fc 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -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 { - jww.CRITICAL.Println(message) + 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]) +} diff --git a/utils/utils_test.go b/utils/utils_test.go new file mode 100644 index 000000000..0bb92dea8 --- /dev/null +++ b/utils/utils_test.go @@ -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) + } + } +} |