2016-04-27 13:13:52 +00:00
|
|
|
package cli
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2016-04-27 13:18:42 +00:00
|
|
|
"os"
|
2016-04-27 13:13:52 +00:00
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type MultiError struct {
|
|
|
|
Errors []error
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewMultiError(err ...error) MultiError {
|
|
|
|
return MultiError{Errors: err}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m MultiError) Error() string {
|
|
|
|
errs := make([]string, len(m.Errors))
|
|
|
|
for i, err := range m.Errors {
|
|
|
|
errs[i] = err.Error()
|
|
|
|
}
|
|
|
|
|
|
|
|
return strings.Join(errs, "\n")
|
|
|
|
}
|
|
|
|
|
2016-04-27 13:54:08 +00:00
|
|
|
// ExitCoder is the interface checked by `App` and `Command` for a custom exit
|
|
|
|
// code
|
2016-04-27 13:13:52 +00:00
|
|
|
type ExitCoder interface {
|
|
|
|
ExitCode() int
|
|
|
|
}
|
|
|
|
|
2016-04-27 13:54:08 +00:00
|
|
|
// ExitError fulfills both the builtin `error` interface and `ExitCoder`
|
2016-04-27 13:13:52 +00:00
|
|
|
type ExitError struct {
|
|
|
|
exitCode int
|
|
|
|
message string
|
|
|
|
}
|
|
|
|
|
2016-04-27 13:54:08 +00:00
|
|
|
// NewExitError makes a new *ExitError
|
2016-04-27 13:13:52 +00:00
|
|
|
func NewExitError(message string, exitCode int) *ExitError {
|
|
|
|
return &ExitError{
|
|
|
|
exitCode: exitCode,
|
|
|
|
message: message,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-04-27 13:54:08 +00:00
|
|
|
// Error returns the string message, fulfilling the interface required by
|
|
|
|
// `error`
|
2016-04-27 13:13:52 +00:00
|
|
|
func (ee *ExitError) Error() string {
|
|
|
|
return ee.message
|
|
|
|
}
|
|
|
|
|
2016-04-27 13:54:08 +00:00
|
|
|
// ExitCode returns the exit code, fulfilling the interface required by
|
|
|
|
// `ExitCoder`
|
2016-04-27 13:13:52 +00:00
|
|
|
func (ee *ExitError) ExitCode() int {
|
|
|
|
return ee.exitCode
|
|
|
|
}
|
2016-04-27 13:18:42 +00:00
|
|
|
|
|
|
|
// HandleExitCoder checks if the error fulfills the ExitCoder interface, and if
|
2016-04-27 13:54:08 +00:00
|
|
|
// so prints the error to stderr (if it is non-empty) and calls os.Exit with the
|
|
|
|
// given exit code. If the given error is a MultiError, then this func is
|
|
|
|
// called on all members of the Errors slice.
|
2016-04-27 13:18:42 +00:00
|
|
|
func HandleExitCoder(err error) {
|
|
|
|
if exitErr, ok := err.(ExitCoder); ok {
|
2016-04-27 13:54:08 +00:00
|
|
|
if err.Error() != "" {
|
|
|
|
fmt.Fprintln(os.Stderr, err)
|
|
|
|
}
|
2016-04-27 13:18:42 +00:00
|
|
|
os.Exit(exitErr.ExitCode())
|
|
|
|
}
|
2016-04-27 13:54:08 +00:00
|
|
|
|
|
|
|
if multiErr, ok := err.(MultiError); ok {
|
|
|
|
for _, merr := range multiErr.Errors {
|
|
|
|
HandleExitCoder(merr)
|
|
|
|
}
|
|
|
|
}
|
2016-04-27 13:18:42 +00:00
|
|
|
}
|