From 8766aaeab5ca44d0eceae49614346e28ab11c439 Mon Sep 17 00:00:00 2001 From: iamgnat Date: Thu, 21 Jun 2018 12:23:39 -0400 Subject: [PATCH] Adding WroteHelp() helper --- help.go | 20 ++++++++++++++++++++ help_test.go | 23 +++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/help.go b/help.go index 8e3eba9..4743cc9 100644 --- a/help.go +++ b/help.go @@ -489,3 +489,23 @@ func (p *Parser) WriteHelp(writer io.Writer) { wr.Flush() } + +// WroteHelp is a helper to test the error from ParseArgs() to +// determine if the help message was written. It is safe to +// call without first checking that error is nil. +func WroteHelp(err error) bool { + if err == nil { // No error + return false + } + + flagError, ok := err.(*Error) + if !ok { // Not a go-flag error + return false + } + + if flagError.Type != ErrHelp { // Did not print the help message + return false + } + + return true +} diff --git a/help_test.go b/help_test.go index bb76640..7faea34 100644 --- a/help_test.go +++ b/help_test.go @@ -3,6 +3,7 @@ package flags import ( "bufio" "bytes" + "errors" "fmt" "os" "runtime" @@ -536,3 +537,25 @@ func TestHelpDefaultMask(t *testing.T) { } } } + +func TestWroteHelp(t *testing.T) { + type testInfo struct { + value error + isHelp bool + } + tests := map[string]testInfo{ + "No error": testInfo{value: nil, isHelp: false}, + "Plain error": testInfo{value: errors.New("an error"), isHelp: false}, + "ErrUnknown": testInfo{value: newError(ErrUnknown, "an error"), isHelp: false}, + "ErrHelp": testInfo{value: newError(ErrHelp, "an error"), isHelp: true}, + } + + for name, test := range tests { + t.Run(name, func(t *testing.T) { + res := WroteHelp(test.value) + if test.isHelp != res { + t.Errorf("Expected %t, got %t", test.isHelp, res) + } + }) + } +}