forked from alecthomas/gometalinter
/
check_no_globals.go
87 lines (78 loc) · 1.87 KB
/
check_no_globals.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
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"strings"
)
func isWhitelisted(i *ast.Ident) bool {
return i.Name == "_" || looksLikeError(i)
}
// looksLikeError returns true if the AST identifier starts
// with 'err' or 'Err', or false otherwise.
//
// TODO: https://github.com/leighmcculloch/gochecknoglobals/issues/5
func looksLikeError(i *ast.Ident) bool {
prefix := "err"
if i.IsExported() {
prefix = "Err"
}
return strings.HasPrefix(i.Name, prefix)
}
func checkNoGlobals(rootPath string, includeTests bool) ([]string, error) {
const recursiveSuffix = string(filepath.Separator) + "..."
recursive := false
if strings.HasSuffix(rootPath, recursiveSuffix) {
recursive = true
rootPath = rootPath[:len(rootPath)-len(recursiveSuffix)]
}
messages := []string{}
err := filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
if !recursive && path != rootPath {
return filepath.SkipDir
}
return nil
}
if !strings.HasSuffix(path, ".go") {
return nil
}
if !includeTests && strings.HasSuffix(path, "_test.go") {
return nil
}
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, path, nil, 0)
if err != nil {
return err
}
for _, decl := range file.Decls {
genDecl, ok := decl.(*ast.GenDecl)
if !ok {
continue
}
if genDecl.Tok != token.VAR {
continue
}
filename := fset.Position(genDecl.TokPos).Filename
for _, spec := range genDecl.Specs {
valueSpec := spec.(*ast.ValueSpec)
for _, vn := range valueSpec.Names {
if isWhitelisted(vn) {
continue
}
line := fset.Position(vn.Pos()).Line
message := fmt.Sprintf("%s:%d %s is a global variable", filename, line, vn.Name)
messages = append(messages, message)
}
}
}
return nil
})
return messages, err
}