Merge pull request #30 from ameihm0912/errors

Use errors package from stdlib
This commit is contained in:
Aaron Meihm 2017-08-25 16:46:35 -05:00 коммит произвёл GitHub
Родитель f3fe37ec83 fe01971938
Коммит fa62b711f5
10 изменённых файлов: 5 добавлений и 718 удалений

Просмотреть файл

@ -5,11 +5,10 @@
package libaudit
import (
"errors"
"fmt"
"strconv"
"syscall"
"github.com/pkg/errors"
)
// EventCallback is the function definition for any function that wants to receive an AuditEvent as soon as

Просмотреть файл

@ -17,7 +17,6 @@ import (
"github.com/lunixbochs/struc"
"github.com/mozilla/libaudit-go/headers"
"github.com/pkg/errors"
)
// fieldType denotes the integer values of various fields occuring in audit messages
@ -1196,7 +1195,7 @@ func printIP6OptName(fieldValue string) (string, error) {
func printTCPOptName(fieldValue string) (string, error) {
ival, err := strconv.ParseInt(fieldValue, 16, 64)
if err != nil {
return "", errors.Wrap(err, "tcp opt parsing failed")
return "", err
}
if _, ok := headers.TcpOptLookup[int(ival)]; !ok {
return fmt.Sprintf("unknown tcpopt name (0x%s)", fieldValue), nil
@ -1268,7 +1267,7 @@ func printSHMFlags(fieldValue string) (string, error) {
partial = ival & 000777
tmode, err := printModeShortInt(partial)
if err != nil {
return "", errors.Wrap(err, "shm parsing failed")
return "", err
}
if len(name) > 0 {
name += "|"

Просмотреть файл

@ -8,6 +8,7 @@ import (
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"os"
"os/user"
@ -19,7 +20,6 @@ import (
"github.com/lunixbochs/struc"
"github.com/mozilla/libaudit-go/headers"
"github.com/pkg/errors"
)
// AuditRules describes a set of audit rules in JSON format
@ -373,7 +373,7 @@ func auditRuleFieldPairData(rule *auditRuleData, fpd *fieldPairData) error {
} else {
user, err := user.Lookup(val)
if err != nil {
return errors.Wrapf(err, "unknown user %v", user)
return fmt.Errorf("bad user: %v: %v", user, err)
}
userID, err := strconv.Atoi(user.Uid)
if err != nil {

24
vendor/github.com/pkg/errors/.gitignore сгенерированный поставляемый
Просмотреть файл

@ -1,24 +0,0 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof

10
vendor/github.com/pkg/errors/.travis.yml сгенерированный поставляемый
Просмотреть файл

@ -1,10 +0,0 @@
language: go
go_import_path: github.com/pkg/errors
go:
- 1.4.3
- 1.5.4
- 1.6.2
- tip
script:
- go test -v ./...

24
vendor/github.com/pkg/errors/LICENSE сгенерированный поставляемый
Просмотреть файл

@ -1,24 +0,0 @@
Copyright (c) 2015, Dave Cheney <dave@cheney.net>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

59
vendor/github.com/pkg/errors/README.md сгенерированный поставляемый
Просмотреть файл

@ -1,59 +0,0 @@
# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors)
Package errors provides simple error handling primitives.
The traditional error handling idiom in Go is roughly akin to
```go
if err != nil {
return err
}
```
which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error.
## Adding context to an error
The errors.Wrap function returns a new error that adds context to the original error. For example
```go
_, err := ioutil.ReadAll(r)
if err != nil {
return errors.Wrap(err, "read failed")
}
```
## Retrieving the stack trace of an error or wrapper
`New`, `Errorf`, `Wrap`, and `Wrapf` record a stack trace at the point they are invoked.
This information can be retrieved with the following interface.
```go
type Stack interface {
Stack() []uintptr
}
```
## Retrieving the cause of an error
Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to recurse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`.
```go
type causer interface {
Cause() error
}
```
`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example:
```go
switch err := errors.Cause(err).(type) {
case *MyError:
// handle specifically
default:
// unknown error
}
```
Would you like to know more? Read the [blog post](http://dave.cheney.net/2016/04/27/dont-just-check-errors-handle-them-gracefully).
## Contributing
We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high.
Before proposing a change, please discuss your change by raising an issue.
## Licence
MIT

259
vendor/github.com/pkg/errors/errors.go сгенерированный поставляемый
Просмотреть файл

@ -1,259 +0,0 @@
// Package errors provides simple error handling primitives.
//
// The traditional error handling idiom in Go is roughly akin to
//
// if err != nil {
// return err
// }
//
// which applied recursively up the call stack results in error reports
// without context or debugging information. The errors package allows
// programmers to add context to the failure path in their code in a way
// that does not destroy the original value of the error.
//
// Adding context to an error
//
// The errors.Wrap function returns a new error that adds context to the
// original error. For example
//
// _, err := ioutil.ReadAll(r)
// if err != nil {
// return errors.Wrap(err, "read failed")
// }
//
// Retrieving the stack trace of an error or wrapper
//
// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are
// invoked. This information can be retrieved with the following interface.
//
// type Stack interface {
// Stack() []uintptr
// }
//
// Retrieving the cause of an error
//
// Using errors.Wrap constructs a stack of errors, adding context to the
// preceding error. Depending on the nature of the error it may be necessary
// to reverse the operation of errors.Wrap to retrieve the original error
// for inspection. Any error value which implements this interface
//
// type Causer interface {
// Cause() error
// }
//
// can be inspected by errors.Cause. errors.Cause will recursively retrieve
// the topmost error which does not implement causer, which is assumed to be
// the original cause. For example:
//
// switch err := errors.Cause(err).(type) {
// case *MyError:
// // handle specifically
// default:
// // unknown error
// }
package errors
import (
"errors"
"fmt"
"io"
"runtime"
"strings"
)
// stack represents a stack of programm counters.
type stack []uintptr
func (s *stack) Stack() []uintptr { return *s }
func (s *stack) Location() (string, int) {
return location((*s)[0] - 1)
}
// New returns an error that formats as the given text.
func New(text string) error {
return struct {
error
*stack
}{
errors.New(text),
callers(),
}
}
type cause struct {
cause error
message string
}
func (c cause) Error() string { return c.Message() + ": " + c.Cause().Error() }
func (c cause) Cause() error { return c.cause }
func (c cause) Message() string { return c.message }
// Errorf formats according to a format specifier and returns the string
// as a value that satisfies error.
func Errorf(format string, args ...interface{}) error {
return struct {
error
*stack
}{
fmt.Errorf(format, args...),
callers(),
}
}
// Wrap returns an error annotating err with message.
// If err is nil, Wrap returns nil.
func Wrap(err error, message string) error {
if err == nil {
return nil
}
return struct {
cause
*stack
}{
cause{
cause: err,
message: message,
},
callers(),
}
}
// Wrapf returns an error annotating err with the format specifier.
// If err is nil, Wrapf returns nil.
func Wrapf(err error, format string, args ...interface{}) error {
if err == nil {
return nil
}
return struct {
cause
*stack
}{
cause{
cause: err,
message: fmt.Sprintf(format, args...),
},
callers(),
}
}
type causer interface {
Cause() error
}
// Cause returns the underlying cause of the error, if possible.
// An error value has a cause if it implements the following
// interface:
//
// type Causer interface {
// Cause() error
// }
//
// If the error does not implement Cause, the original error will
// be returned. If the error is nil, nil will be returned without further
// investigation.
func Cause(err error) error {
for err != nil {
cause, ok := err.(causer)
if !ok {
break
}
err = cause.Cause()
}
return err
}
// Fprint prints the error to the supplied writer.
// If the error implements the Causer interface described in Cause
// Print will recurse into the error's cause.
// If the error implements the inteface:
//
// type Location interface {
// Location() (file string, line int)
// }
//
// Print will also print the file and line of the error.
// If err is nil, nothing is printed.
func Fprint(w io.Writer, err error) {
type location interface {
Location() (string, int)
}
type message interface {
Message() string
}
for err != nil {
if err, ok := err.(location); ok {
file, line := err.Location()
fmt.Fprintf(w, "%s:%d: ", file, line)
}
switch err := err.(type) {
case message:
fmt.Fprintln(w, err.Message())
default:
fmt.Fprintln(w, err.Error())
}
cause, ok := err.(causer)
if !ok {
break
}
err = cause.Cause()
}
}
func callers() *stack {
const depth = 32
var pcs [depth]uintptr
n := runtime.Callers(3, pcs[:])
var st stack = pcs[0:n]
return &st
}
// location returns the source file and line matching pc.
func location(pc uintptr) (string, int) {
fn := runtime.FuncForPC(pc)
if fn == nil {
return "unknown", 0
}
// Here we want to get the source file path relative to the compile time
// GOPATH. As of Go 1.6.x there is no direct way to know the compiled
// GOPATH at runtime, but we can infer the number of path segments in the
// GOPATH. We note that fn.Name() returns the function name qualified by
// the import path, which does not include the GOPATH. Thus we can trim
// segments from the beginning of the file path until the number of path
// separators remaining is one more than the number of path separators in
// the function name. For example, given:
//
// GOPATH /home/user
// file /home/user/src/pkg/sub/file.go
// fn.Name() pkg/sub.Type.Method
//
// We want to produce:
//
// pkg/sub/file.go
//
// From this we can easily see that fn.Name() has one less path separator
// than our desired output. We count separators from the end of the file
// path until it finds two more than in the function name and then move
// one character forward to preserve the initial path segment without a
// leading separator.
const sep = "/"
goal := strings.Count(fn.Name(), sep) + 2
file, line := fn.FileLine(pc)
i := len(file)
for n := 0; n < goal; n++ {
i = strings.LastIndex(file[:i], sep)
if i == -1 {
// not enough separators found, set i so that the slice expression
// below leaves file unmodified
i = -len(sep)
break
}
}
// get back to 0 or trim the leading separator
file = file[i+len(sep):]
return file, line
}

264
vendor/github.com/pkg/errors/errors_test.go сгенерированный поставляемый
Просмотреть файл

@ -1,264 +0,0 @@
package errors
import (
"bytes"
"errors"
"fmt"
"io"
"reflect"
"testing"
)
func TestNew(t *testing.T) {
tests := []struct {
err string
want error
}{
{"", fmt.Errorf("")},
{"foo", fmt.Errorf("foo")},
{"foo", New("foo")},
{"string with format specifiers: %v", errors.New("string with format specifiers: %v")},
}
for _, tt := range tests {
got := New(tt.err)
if got.Error() != tt.want.Error() {
t.Errorf("New.Error(): got: %q, want %q", got, tt.want)
}
}
}
func TestWrapNil(t *testing.T) {
got := Wrap(nil, "no error")
if got != nil {
t.Errorf("Wrap(nil, \"no error\"): got %#v, expected nil", got)
}
}
func TestWrap(t *testing.T) {
tests := []struct {
err error
message string
want string
}{
{io.EOF, "read error", "read error: EOF"},
{Wrap(io.EOF, "read error"), "client error", "client error: read error: EOF"},
}
for _, tt := range tests {
got := Wrap(tt.err, tt.message).Error()
if got != tt.want {
t.Errorf("Wrap(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want)
}
}
}
type nilError struct{}
func (nilError) Error() string { return "nil error" }
type causeError struct {
cause error
}
func (e *causeError) Error() string { return "cause error" }
func (e *causeError) Cause() error { return e.cause }
func TestCause(t *testing.T) {
x := New("error")
tests := []struct {
err error
want error
}{{
// nil error is nil
err: nil,
want: nil,
}, {
// explicit nil error is nil
err: (error)(nil),
want: nil,
}, {
// typed nil is nil
err: (*nilError)(nil),
want: (*nilError)(nil),
}, {
// uncaused error is unaffected
err: io.EOF,
want: io.EOF,
}, {
// caused error returns cause
err: &causeError{cause: io.EOF},
want: io.EOF,
}, {
err: x, // return from errors.New
want: x,
}}
for i, tt := range tests {
got := Cause(tt.err)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("test %d: got %#v, want %#v", i+1, got, tt.want)
}
}
}
func TestFprint(t *testing.T) {
x := New("error")
tests := []struct {
err error
want string
}{{
// nil error is nil
err: nil,
}, {
// explicit nil error is nil
err: (error)(nil),
}, {
// uncaused error is unaffected
err: io.EOF,
want: "EOF\n",
}, {
// caused error returns cause
err: &causeError{cause: io.EOF},
want: "cause error\nEOF\n",
}, {
err: x, // return from errors.New
want: "github.com/pkg/errors/errors_test.go:106: error\n",
}, {
err: Wrap(x, "message"),
want: "github.com/pkg/errors/errors_test.go:128: message\ngithub.com/pkg/errors/errors_test.go:106: error\n",
}, {
err: Wrap(Wrap(x, "message"), "another message"),
want: "github.com/pkg/errors/errors_test.go:131: another message\ngithub.com/pkg/errors/errors_test.go:131: message\ngithub.com/pkg/errors/errors_test.go:106: error\n",
}, {
err: Wrapf(x, "message"),
want: "github.com/pkg/errors/errors_test.go:134: message\ngithub.com/pkg/errors/errors_test.go:106: error\n",
}}
for i, tt := range tests {
var w bytes.Buffer
Fprint(&w, tt.err)
got := w.String()
if got != tt.want {
t.Errorf("test %d: Fprint(w, %q): got %q, want %q", i+1, tt.err, got, tt.want)
}
}
}
func TestWrapfNil(t *testing.T) {
got := Wrapf(nil, "no error")
if got != nil {
t.Errorf("Wrapf(nil, \"no error\"): got %#v, expected nil", got)
}
}
func TestWrapf(t *testing.T) {
tests := []struct {
err error
message string
want string
}{
{io.EOF, "read error", "read error: EOF"},
{Wrapf(io.EOF, "read error without format specifiers"), "client error", "client error: read error without format specifiers: EOF"},
{Wrapf(io.EOF, "read error with %d format specifier", 1), "client error", "client error: read error with 1 format specifier: EOF"},
}
for _, tt := range tests {
got := Wrapf(tt.err, tt.message).Error()
if got != tt.want {
t.Errorf("Wrapf(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want)
}
}
}
func TestErrorf(t *testing.T) {
tests := []struct {
err error
want string
}{
{Errorf("read error without format specifiers"), "read error without format specifiers"},
{Errorf("read error with %d format specifier", 1), "read error with 1 format specifier"},
}
for _, tt := range tests {
got := tt.err.Error()
if got != tt.want {
t.Errorf("Errorf(%v): got: %q, want %q", tt.err, got, tt.want)
}
}
}
func TestStack(t *testing.T) {
type fileline struct {
file string
line int
}
tests := []struct {
err error
want []fileline
}{{
New("ooh"), []fileline{
{"github.com/pkg/errors/errors_test.go", 200},
},
}, {
Wrap(New("ooh"), "ahh"), []fileline{
{"github.com/pkg/errors/errors_test.go", 204}, // this is the stack of Wrap, not New
},
}, {
Cause(Wrap(New("ooh"), "ahh")), []fileline{
{"github.com/pkg/errors/errors_test.go", 208}, // this is the stack of New
},
}, {
func() error { return New("ooh") }(), []fileline{
{"github.com/pkg/errors/errors_test.go", 212}, // this is the stack of New
{"github.com/pkg/errors/errors_test.go", 212}, // this is the stack of New's caller
},
}, {
Cause(func() error {
return func() error {
return Errorf("hello %s", fmt.Sprintf("world"))
}()
}()), []fileline{
{"github.com/pkg/errors/errors_test.go", 219}, // this is the stack of Errorf
{"github.com/pkg/errors/errors_test.go", 220}, // this is the stack of Errorf's caller
{"github.com/pkg/errors/errors_test.go", 221}, // this is the stack of Errorf's caller's caller
},
}}
for _, tt := range tests {
x, ok := tt.err.(interface {
Stack() []uintptr
})
if !ok {
t.Errorf("expected %#v to implement Stack()", tt.err)
continue
}
st := x.Stack()
for i, want := range tt.want {
file, line := location(st[i] - 1)
if file != want.file || line != want.line {
t.Errorf("frame %d: expected %s:%d, got %s:%d", i, want.file, want.line, file, line)
}
}
}
}
// errors.New, etc values are not expected to be compared by value
// but the change in errors#27 made them incomparable. Assert that
// various kinds of errors have a functional equality operator, even
// if the result of that equality is always false.
func TestErrorEquality(t *testing.T) {
tests := []struct {
err1, err2 error
}{
{io.EOF, io.EOF},
{io.EOF, nil},
{io.EOF, errors.New("EOF")},
{io.EOF, New("EOF")},
{New("EOF"), New("EOF")},
{New("EOF"), Errorf("EOF")},
{New("EOF"), Wrap(io.EOF, "EOF")},
}
for _, tt := range tests {
_ = tt.err1 == tt.err2 // mustn't panic
}
}

71
vendor/github.com/pkg/errors/example_test.go сгенерированный поставляемый
Просмотреть файл

@ -1,71 +0,0 @@
package errors_test
import (
"fmt"
"os"
"github.com/pkg/errors"
)
func ExampleNew() {
err := errors.New("whoops")
fmt.Println(err)
// Output: whoops
}
func ExampleNew_fprint() {
err := errors.New("whoops")
errors.Fprint(os.Stdout, err)
// Output: github.com/pkg/errors/example_test.go:18: whoops
}
func ExampleWrap() {
cause := errors.New("whoops")
err := errors.Wrap(cause, "oh noes")
fmt.Println(err)
// Output: oh noes: whoops
}
func fn() error {
e1 := errors.New("error")
e2 := errors.Wrap(e1, "inner")
e3 := errors.Wrap(e2, "middle")
return errors.Wrap(e3, "outer")
}
func ExampleCause() {
err := fn()
fmt.Println(err)
fmt.Println(errors.Cause(err))
// Output: outer: middle: inner: error
// error
}
func ExampleFprint() {
err := fn()
errors.Fprint(os.Stdout, err)
// Output: github.com/pkg/errors/example_test.go:36: outer
// github.com/pkg/errors/example_test.go:35: middle
// github.com/pkg/errors/example_test.go:34: inner
// github.com/pkg/errors/example_test.go:33: error
}
func ExampleWrapf() {
cause := errors.New("whoops")
err := errors.Wrapf(cause, "oh noes #%d", 2)
fmt.Println(err)
// Output: oh noes #2: whoops
}
func ExampleErrorf() {
err := errors.Errorf("whoops: %s", "foo")
errors.Fprint(os.Stdout, err)
// Output: github.com/pkg/errors/example_test.go:67: whoops: foo
}