-
Notifications
You must be signed in to change notification settings - Fork 152
/
errcheck.go
105 lines (93 loc) · 1.99 KB
/
errcheck.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"fmt"
"go/ast"
"go/token"
"go/types"
"os"
"path/filepath"
"golang.org/x/tools/go/packages"
)
func analyzePackage(pkg *packages.Package) (count int) {
for _, f := range pkg.Syntax {
count += analyzeFile(f, pkg)
}
return count
}
type callVisitor struct {
Fset *token.FileSet
TypeInfo *types.Info
Errors []error
}
func (c *callVisitor) Visit(node ast.Node) (w ast.Visitor) {
switch node := node.(type) {
case *ast.CallExpr:
var ident *ast.Ident
switch fun := node.Fun.(type) {
case *ast.SelectorExpr:
ident = fun.Sel
case *ast.Ident:
ident = fun
}
if obj := c.TypeInfo.ObjectOf(ident); obj != nil {
if fn, ok := obj.(*types.Func); ok {
c.check(node, fn)
}
}
return nil
}
return c
}
func (c *callVisitor) check(node ast.Node, fn *types.Func) {
if fn.Pkg() == nil {
return
}
pos := c.Fset.Position(node.Pos())
if cwd, err := os.Getwd(); err == nil {
if filename, err := filepath.Rel(cwd, pos.Filename); err == nil {
pos.Filename = filename
}
}
if fn.Pkg().Path() == "errors" && fn.Name() == "New" {
c.Errors = append(c.Errors, fmt.Errorf("%s: found usage of errors.New", pos))
}
if fn.Pkg().Path() == "fmt" && fn.Name() == "Errorf" {
c.Errors = append(c.Errors, fmt.Errorf("%s: found usage of fmt.Errorf", pos))
}
}
func analyzeFile(file *ast.File, pkg *packages.Package) int {
v := callVisitor{
Fset: pkg.Fset,
TypeInfo: pkg.TypesInfo,
}
ast.Walk(&v, file)
if len(v.Errors) > 0 {
for _, err := range v.Errors {
fmt.Println(err)
}
return 1
}
return 0
}
func main() {
cfg := packages.Config{
Mode: packages.NeedName |
packages.NeedFiles |
packages.NeedCompiledGoFiles |
packages.NeedImports |
packages.NeedDeps |
packages.NeedSyntax |
packages.NeedTypes |
packages.NeedTypesInfo,
Env: os.Environ(),
}
pkgs, err := packages.Load(&cfg, os.Args[1:]...)
if err != nil {
panic(err)
}
count := 0
for _, pkg := range pkgs {
count += analyzePackage(pkg)
}
os.Exit(count)
}