diff --git a/.travis.yml b/.travis.yml index 0ac2b7a..81e650b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,9 +1,11 @@ +arch: + - amd64 + language: go go_import_path: github.com/pkg/errors go: - - 1.9.x - - 1.10.x - - 1.11.x + - 1.14 + - 1.15 - tip script: diff --git a/README.md b/README.md index cf771e7..54dfdcb 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ default: With the upcoming [Go2 error proposals](https://go.googlesource.com/proposal/+/master/design/go2draft.md) this package is moving into maintenance mode. The roadmap for a 1.0 release is as follows: -- 0.9. Remove pre Go 1.9 support, address outstanding pull requests (if possible) +- 0.9. Remove pre Go 1.9 and Go 1.10 support, address outstanding pull requests (if possible) - 1.0. Final release. ## Contributing diff --git a/errors.go b/errors.go index 8617bee..161aea2 100644 --- a/errors.go +++ b/errors.go @@ -159,6 +159,9 @@ type withStack struct { func (w *withStack) Cause() error { return w.error } +// Unwrap provides compatibility for Go 1.13 error chains. +func (w *withStack) Unwrap() error { return w.error } + func (w *withStack) Format(s fmt.State, verb rune) { switch verb { case 'v': @@ -241,6 +244,9 @@ type withMessage struct { func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } func (w *withMessage) Cause() error { return w.cause } +// Unwrap provides compatibility for Go 1.13 error chains. +func (w *withMessage) Unwrap() error { return w.cause } + func (w *withMessage) Format(s fmt.State, verb rune) { switch verb { case 'v': diff --git a/example_test.go b/example_test.go index c1fc13e..7d0e286 100644 --- a/example_test.go +++ b/example_test.go @@ -195,7 +195,7 @@ func Example_stackTrace() { func ExampleCause_printf() { err := errors.Wrap(func() error { return func() error { - return errors.Errorf("hello %s", fmt.Sprintf("world")) + return errors.New("hello world") }() }(), "failed") diff --git a/format_test.go b/format_test.go index c2eef5f..cb1df82 100644 --- a/format_test.go +++ b/format_test.go @@ -360,7 +360,32 @@ func TestFormatGeneric(t *testing.T) { } } +func wrappedNew(message string) error { // This function will be mid-stack inlined in go 1.12+ + return New(message) +} + +func TestFormatWrappedNew(t *testing.T) { + tests := []struct { + error + format string + want string + }{{ + wrappedNew("error"), + "%+v", + "error\n" + + "github.com/pkg/errors.wrappedNew\n" + + "\t.+/github.com/pkg/errors/format_test.go:364\n" + + "github.com/pkg/errors.TestFormatWrappedNew\n" + + "\t.+/github.com/pkg/errors/format_test.go:373", + }} + + for i, tt := range tests { + testFormatRegexp(t, i, tt.error, tt.format, tt.want) + } +} + func testFormatRegexp(t *testing.T, n int, arg interface{}, format, want string) { + t.Helper() got := fmt.Sprintf(format, arg) gotLines := strings.SplitN(got, "\n", -1) wantLines := strings.SplitN(want, "\n", -1) diff --git a/go113.go b/go113.go new file mode 100644 index 0000000..be0d10d --- /dev/null +++ b/go113.go @@ -0,0 +1,38 @@ +// +build go1.13 + +package errors + +import ( + stderrors "errors" +) + +// Is reports whether any error in err's chain matches target. +// +// The chain consists of err itself followed by the sequence of errors obtained by +// repeatedly calling Unwrap. +// +// An error is considered to match a target if it is equal to that target or if +// it implements a method Is(error) bool such that Is(target) returns true. +func Is(err, target error) bool { return stderrors.Is(err, target) } + +// As finds the first error in err's chain that matches target, and if so, sets +// target to that error value and returns true. +// +// The chain consists of err itself followed by the sequence of errors obtained by +// repeatedly calling Unwrap. +// +// An error matches target if the error's concrete value is assignable to the value +// pointed to by target, or if the error has a method As(interface{}) bool such that +// As(target) returns true. In the latter case, the As method is responsible for +// setting target. +// +// As will panic if target is not a non-nil pointer to either a type that implements +// error, or to any interface type. As returns false if err is nil. +func As(err error, target interface{}) bool { return stderrors.As(err, target) } + +// Unwrap returns the result of calling the Unwrap method on err, if err's +// type contains an Unwrap method returning error. +// Otherwise, Unwrap returns nil. +func Unwrap(err error) error { + return stderrors.Unwrap(err) +} diff --git a/go113_test.go b/go113_test.go new file mode 100644 index 0000000..4ea37e6 --- /dev/null +++ b/go113_test.go @@ -0,0 +1,178 @@ +// +build go1.13 + +package errors + +import ( + stderrors "errors" + "fmt" + "reflect" + "testing" +) + +func TestErrorChainCompat(t *testing.T) { + err := stderrors.New("error that gets wrapped") + wrapped := Wrap(err, "wrapped up") + if !stderrors.Is(wrapped, err) { + t.Errorf("Wrap does not support Go 1.13 error chains") + } +} + +func TestIs(t *testing.T) { + err := New("test") + + type args struct { + err error + target error + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "with stack", + args: args{ + err: WithStack(err), + target: err, + }, + want: true, + }, + { + name: "with message", + args: args{ + err: WithMessage(err, "test"), + target: err, + }, + want: true, + }, + { + name: "with message format", + args: args{ + err: WithMessagef(err, "%s", "test"), + target: err, + }, + want: true, + }, + { + name: "std errors compatibility", + args: args{ + err: fmt.Errorf("wrap it: %w", err), + target: err, + }, + want: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Is(tt.args.err, tt.args.target); got != tt.want { + t.Errorf("Is() = %v, want %v", got, tt.want) + } + }) + } +} + +type customErr struct { + msg string +} + +func (c customErr) Error() string { return c.msg } + +func TestAs(t *testing.T) { + var err = customErr{msg: "test message"} + + type args struct { + err error + target interface{} + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "with stack", + args: args{ + err: WithStack(err), + target: new(customErr), + }, + want: true, + }, + { + name: "with message", + args: args{ + err: WithMessage(err, "test"), + target: new(customErr), + }, + want: true, + }, + { + name: "with message format", + args: args{ + err: WithMessagef(err, "%s", "test"), + target: new(customErr), + }, + want: true, + }, + { + name: "std errors compatibility", + args: args{ + err: fmt.Errorf("wrap it: %w", err), + target: new(customErr), + }, + want: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := As(tt.args.err, tt.args.target); got != tt.want { + t.Errorf("As() = %v, want %v", got, tt.want) + } + + ce := tt.args.target.(*customErr) + if !reflect.DeepEqual(err, *ce) { + t.Errorf("set target error failed, target error is %v", *ce) + } + }) + } +} + +func TestUnwrap(t *testing.T) { + err := New("test") + + type args struct { + err error + } + tests := []struct { + name string + args args + want error + }{ + { + name: "with stack", + args: args{err: WithStack(err)}, + want: err, + }, + { + name: "with message", + args: args{err: WithMessage(err, "test")}, + want: err, + }, + { + name: "with message format", + args: args{err: WithMessagef(err, "%s", "test")}, + want: err, + }, + { + name: "std errors compatibility", + args: args{err: fmt.Errorf("wrap: %w", err)}, + want: err, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := Unwrap(tt.args.err); !reflect.DeepEqual(err, tt.want) { + t.Errorf("Unwrap() error = %v, want %v", err, tt.want) + } + }) + } +} diff --git a/json_test.go b/json_test.go new file mode 100644 index 0000000..ad1adec --- /dev/null +++ b/json_test.go @@ -0,0 +1,51 @@ +package errors + +import ( + "encoding/json" + "regexp" + "testing" +) + +func TestFrameMarshalText(t *testing.T) { + var tests = []struct { + Frame + want string + }{{ + initpc, + `^github.com/pkg/errors\.init(\.ializers)? .+/github\.com/pkg/errors/stack_test.go:\d+$`, + }, { + 0, + `^unknown$`, + }} + for i, tt := range tests { + got, err := tt.Frame.MarshalText() + if err != nil { + t.Fatal(err) + } + if !regexp.MustCompile(tt.want).Match(got) { + t.Errorf("test %d: MarshalJSON:\n got %q\n want %q", i+1, string(got), tt.want) + } + } +} + +func TestFrameMarshalJSON(t *testing.T) { + var tests = []struct { + Frame + want string + }{{ + initpc, + `^"github\.com/pkg/errors\.init(\.ializers)? .+/github\.com/pkg/errors/stack_test.go:\d+"$`, + }, { + 0, + `^"unknown"$`, + }} + for i, tt := range tests { + got, err := json.Marshal(tt.Frame) + if err != nil { + t.Fatal(err) + } + if !regexp.MustCompile(tt.want).Match(got) { + t.Errorf("test %d: MarshalJSON:\n got %q\n want %q", i+1, string(got), tt.want) + } + } +} diff --git a/stack.go b/stack.go index 3b582c2..779a834 100644 --- a/stack.go +++ b/stack.go @@ -1,7 +1,6 @@ package errors import ( - "bytes" "fmt" "io" "path" @@ -11,7 +10,44 @@ import ( ) // Frame represents a program counter inside a stack frame. -type Frame runtime.Frame +// For historical reasons if Frame is interpreted as a uintptr +// its value represents the program counter + 1. +type Frame uintptr + +// pc returns the program counter for this frame; +// multiple frames may have the same PC value. +func (f Frame) pc() uintptr { return uintptr(f) - 1 } + +// file returns the full path to the file that contains the +// function for this Frame's pc. +func (f Frame) file() string { + fn := runtime.FuncForPC(f.pc()) + if fn == nil { + return "unknown" + } + file, _ := fn.FileLine(f.pc()) + return file +} + +// line returns the line number of source code of the +// function for this Frame's pc. +func (f Frame) line() int { + fn := runtime.FuncForPC(f.pc()) + if fn == nil { + return 0 + } + _, line := fn.FileLine(f.pc()) + return line +} + +// name returns the name of this function, if known. +func (f Frame) name() string { + fn := runtime.FuncForPC(f.pc()) + if fn == nil { + return "unknown" + } + return fn.Name() +} // Format formats the frame according to the fmt.Formatter interface. // @@ -26,40 +62,35 @@ type Frame runtime.Frame // GOPATH separated by \n\t (\n\t) // %+v equivalent to %+s:%d func (f Frame) Format(s fmt.State, verb rune) { - f.format(s, s, verb) -} - -// format allows stack trace printing calls to be made with a bytes.Buffer. -func (f Frame) format(w io.Writer, s fmt.State, verb rune) { switch verb { case 's': switch { case s.Flag('+'): - fn := f.Func - if fn == nil { - io.WriteString(w, "unknown") - } else { - io.WriteString(w, fn.Name()) - io.WriteString(w, "\n\t") - io.WriteString(w, f.File) - } + io.WriteString(s, f.name()) + io.WriteString(s, "\n\t") + io.WriteString(s, f.file()) default: - file := f.File - if file == "" { - file = "unknown" - } - io.WriteString(w, path.Base(file)) + io.WriteString(s, path.Base(f.file())) } case 'd': - io.WriteString(w, strconv.Itoa(f.Line)) + io.WriteString(s, strconv.Itoa(f.line())) case 'n': - name := f.Function - io.WriteString(s, funcname(name)) + io.WriteString(s, funcname(f.name())) case 'v': - f.format(w, s, 's') - io.WriteString(w, ":") - f.format(w, s, 'd') + f.Format(s, 's') + io.WriteString(s, ":") + f.Format(s, 'd') + } +} + +// MarshalText formats a stacktrace Frame as a text string. The output is the +// same as that of fmt.Sprintf("%+v", f), but without newlines or tabs. +func (f Frame) MarshalText() ([]byte, error) { + name := f.name() + if name == "unknown" { + return []byte(name), nil } + return []byte(fmt.Sprintf("%s %s:%d", name, f.file(), f.line())), nil } // StackTrace is stack of Frames from innermost (newest) to outermost (oldest). @@ -74,50 +105,37 @@ type StackTrace []Frame // // %+v Prints filename, function, and line number for each Frame in the stack. func (st StackTrace) Format(s fmt.State, verb rune) { - var b bytes.Buffer switch verb { case 'v': switch { case s.Flag('+'): - b.Grow(len(st) * stackMinLen) - for _, fr := range st { - b.WriteByte('\n') - fr.format(&b, s, verb) + for _, f := range st { + io.WriteString(s, "\n") + f.Format(s, verb) } case s.Flag('#'): - fmt.Fprintf(&b, "%#v", []Frame(st)) + fmt.Fprintf(s, "%#v", []Frame(st)) default: - st.formatSlice(&b, s, verb) + st.formatSlice(s, verb) } case 's': - st.formatSlice(&b, s, verb) + st.formatSlice(s, verb) } - io.Copy(s, &b) } // formatSlice will format this StackTrace into the given buffer as a slice of // Frame, only valid when called with '%s' or '%v'. -func (st StackTrace) formatSlice(b *bytes.Buffer, s fmt.State, verb rune) { - b.WriteByte('[') - if len(st) == 0 { - b.WriteByte(']') - return - } - - b.Grow(len(st) * (stackMinLen / 4)) - st[0].format(b, s, verb) - for _, fr := range st[1:] { - b.WriteByte(' ') - fr.format(b, s, verb) +func (st StackTrace) formatSlice(s fmt.State, verb rune) { + io.WriteString(s, "[") + for i, f := range st { + if i > 0 { + io.WriteString(s, " ") + } + f.Format(s, verb) } - b.WriteByte(']') + io.WriteString(s, "]") } -// stackMinLen is a best-guess at the minimum length of a stack trace. It -// doesn't need to be exact, just give a good enough head start for the buffer -// to avoid the expensive early growth. -const stackMinLen = 96 - // stack represents a stack of program counters. type stack []uintptr @@ -126,29 +144,20 @@ func (s *stack) Format(st fmt.State, verb rune) { case 'v': switch { case st.Flag('+'): - frames := runtime.CallersFrames(*s) - for { - frame, more := frames.Next() - fmt.Fprintf(st, "\n%+v", Frame(frame)) - if !more { - break - } + for _, pc := range *s { + f := Frame(pc) + fmt.Fprintf(st, "\n%+v", f) } } } } func (s *stack) StackTrace() StackTrace { - var st []Frame - frames := runtime.CallersFrames(*s) - for { - frame, more := frames.Next() - st = append(st, Frame(frame)) - if !more { - break - } + f := make([]Frame, len(*s)) + for i := 0; i < len(f); i++ { + f[i] = Frame((*s)[i]) } - return st + return f } func callers() *stack { diff --git a/stack_test.go b/stack_test.go index 7f76694..aa10a72 100644 --- a/stack_test.go +++ b/stack_test.go @@ -35,11 +35,11 @@ func TestFrameFormat(t *testing.T) { "github.com/pkg/errors.init\n" + "\t.+/github.com/pkg/errors/stack_test.go", }, { - Frame{}, + 0, "%s", "unknown", }, { - Frame{}, + 0, "%+s", "unknown", }, { @@ -47,7 +47,7 @@ func TestFrameFormat(t *testing.T) { "%d", "9", }, { - Frame{}, + 0, "%d", "0", }, { @@ -69,7 +69,7 @@ func TestFrameFormat(t *testing.T) { "%n", "X.val", }, { - Frame{}, + 0, "%n", "", }, { @@ -82,7 +82,7 @@ func TestFrameFormat(t *testing.T) { "github.com/pkg/errors.init\n" + "\t.+/github.com/pkg/errors/stack_test.go:9", }, { - Frame{}, + 0, "%v", "unknown:0", }} @@ -133,7 +133,7 @@ func TestStackTrace(t *testing.T) { "\t.+/github.com/pkg/errors/stack_test.go:131", // this is the stack of New }, }, { - func() error { noinline(); return New("ooh") }(), []string{ + func() error { return New("ooh") }(), []string{ `github.com/pkg/errors.TestStackTrace.func1` + "\n\t.+/github.com/pkg/errors/stack_test.go:136", // this is the stack of New "github.com/pkg/errors.TestStackTrace\n" + @@ -142,7 +142,7 @@ func TestStackTrace(t *testing.T) { }, { Cause(func() error { return func() error { - return Errorf("hello %s", fmt.Sprintf("world")) + return Errorf("hello %s", fmt.Sprintf("world: %s", "ooh")) }() }()), []string{ `github.com/pkg/errors.TestStackTrace.func2.1` + @@ -246,9 +246,5 @@ func caller() Frame { n := runtime.Callers(2, pcs[:]) frames := runtime.CallersFrames(pcs[:n]) frame, _ := frames.Next() - return Frame(frame) + return Frame(frame.PC) } - -//go:noinline -// noinline prevents the caller being inlined -func noinline() {}