Merge pull request #496 from urfave/write-non-nil-error-message-exit-nonzero

Write err to stderr, exit 1 if err != ""
This commit is contained in:
Dan Buch 2016-07-24 12:06:30 -04:00 committed by GitHub
commit 8ae5b3d5e2
3 changed files with 69 additions and 4 deletions

View File

@ -13,6 +13,19 @@ import (
"testing"
)
var (
lastExitCode = 0
fakeOsExiter = func(rc int) {
lastExitCode = rc
}
fakeErrWriter = &bytes.Buffer{}
)
func init() {
OsExiter = fakeOsExiter
ErrWriter = fakeErrWriter
}
type opCounts struct {
Total, BashComplete, OnUsageError, Before, CommandNotFound, Action, After, SubCommand int
}

View File

@ -88,5 +88,11 @@ func HandleExitCoder(err error) {
for _, merr := range multiErr.Errors {
HandleExitCoder(merr)
}
return
}
if err.Error() != "" {
fmt.Fprintln(ErrWriter, err)
OsExiter(1)
}
}

View File

@ -1,8 +1,8 @@
package cli
import (
"bytes"
"errors"
"os"
"testing"
)
@ -15,7 +15,7 @@ func TestHandleExitCoder_nil(t *testing.T) {
called = true
}
defer func() { OsExiter = os.Exit }()
defer func() { OsExiter = fakeOsExiter }()
HandleExitCoder(nil)
@ -32,7 +32,7 @@ func TestHandleExitCoder_ExitCoder(t *testing.T) {
called = true
}
defer func() { OsExiter = os.Exit }()
defer func() { OsExiter = fakeOsExiter }()
HandleExitCoder(NewExitError("galactic perimeter breach", 9))
@ -49,7 +49,7 @@ func TestHandleExitCoder_MultiErrorWithExitCoder(t *testing.T) {
called = true
}
defer func() { OsExiter = os.Exit }()
defer func() { OsExiter = fakeOsExiter }()
exitErr := NewExitError("galactic perimeter breach", 9)
err := NewMultiError(errors.New("wowsa"), errors.New("egad"), exitErr)
@ -58,3 +58,49 @@ func TestHandleExitCoder_MultiErrorWithExitCoder(t *testing.T) {
expect(t, exitCode, 9)
expect(t, called, true)
}
func TestHandleExitCoder_ErrorWithMessage(t *testing.T) {
exitCode := 0
called := false
OsExiter = func(rc int) {
exitCode = rc
called = true
}
ErrWriter = &bytes.Buffer{}
defer func() {
OsExiter = fakeOsExiter
ErrWriter = fakeErrWriter
}()
err := errors.New("gourd havens")
HandleExitCoder(err)
expect(t, exitCode, 1)
expect(t, called, true)
expect(t, ErrWriter.(*bytes.Buffer).String(), "gourd havens\n")
}
func TestHandleExitCoder_ErrorWithoutMessage(t *testing.T) {
exitCode := 0
called := false
OsExiter = func(rc int) {
exitCode = rc
called = true
}
ErrWriter = &bytes.Buffer{}
defer func() {
OsExiter = fakeOsExiter
ErrWriter = fakeErrWriter
}()
err := errors.New("")
HandleExitCoder(err)
expect(t, exitCode, 0)
expect(t, called, false)
expect(t, ErrWriter.(*bytes.Buffer).String(), "")
}