-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathanalyzer.go
83 lines (69 loc) · 1.91 KB
/
analyzer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package wraperr
import (
"go/ast"
"go/token"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
var Analyzer = &analysis.Analyzer{
Name: "wraperr",
Doc: "Check that error return value are wrapped",
Requires: []*analysis.Analyzer{inspect.Analyzer},
Run: runAnalyze,
}
var (
// WrapperFuncList contains "path/to/pkg.Funcname" strings that adds a context to errors.
WrapperFuncList = []string{
// stdlibs
"errors.New",
"fmt.Errorf",
// github.com/pkg/errors
"github.com/pkg/errors.Errorf",
"github.com/pkg/errors.New",
"github.com/pkg/errors.WithMessage",
"github.com/pkg/errors.WithStack",
"github.com/pkg/errors.Wrap",
"github.com/pkg/errors.Wrapf",
// github.com/srvc/fail
"github.com/srvc/fail.Errorf",
"github.com/srvc/fail.New",
"github.com/srvc/fail.Wrap",
}
)
type errIdent struct {
*ast.Ident
wrapped bool
}
var wrapperFuncSet map[string]struct{}
func init() {
wrapperFuncSet = make(map[string]struct{}, len(WrapperFuncList))
for _, f := range WrapperFuncList {
wrapperFuncSet[f] = struct{}{}
}
}
func runAnalyze(pass *analysis.Pass) (interface{}, error) {
r := newFileReader(pass.Fset)
reportFunc := func(assignedAt, returnedAt token.Pos) {
occPos := pass.Fset.Position(assignedAt)
line := sprintInlineCode(r.GetLine(assignedAt))
pass.Reportf(returnedAt, "the error is assigned on L%d: %s", occPos.Line, line)
}
inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
nodeFilter := []ast.Node{
(*ast.FuncDecl)(nil),
}
inspect.WithStack(nodeFilter, func(n ast.Node, push bool, stack []ast.Node) bool {
switch f := stack[0].(type) {
case *ast.File:
if isTestFile(pass.Fset, f) || isGeneratedFile(f) {
return false
}
default:
panic("unreachable")
}
NewChecker(pass.Fset, pass.TypesInfo, n.(*ast.FuncDecl)).Check(reportFunc)
return false
})
return nil, nil
}