-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanalyzer.go
125 lines (105 loc) · 2.38 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package samealias
import (
"bufio"
"flag"
"go/ast"
"go/token"
"os"
"strconv"
"strings"
"sync"
"golang.org/x/tools/go/analysis"
)
type aliaspath struct {
alias string
position token.Position
}
var imports sync.Map
//nolint:gochecknoglobals
var flagSet flag.FlagSet
//nolint:gochecknoglobals
var (
skipAutogens bool
)
//nolint:gochecknoinits
func init() {
flagSet.BoolVar(&skipAutogens, "skipAutogens", true, "should the linter skip autogen files")
}
func NewAnalyzer() *analysis.Analyzer {
return &analysis.Analyzer{
Name: "samealias",
Doc: "check different aliases for same package",
Run: run,
Flags: flagSet,
}
}
func run(pass *analysis.Pass) (interface{}, error) {
for _, file := range pass.Files {
filename := pass.Fset.Position((file.Pos())).Filename
if skipAutogens && isAutogenFile(filename) {
continue
}
ast.Inspect(file, func(node ast.Node) bool {
f, ok := node.(*ast.ImportSpec)
if !ok {
if node == nil {
return true
}
return true
}
if f.Name == nil {
return true
}
alias := ""
if f.Name != nil {
alias = f.Name.String()
}
if alias == "." {
return true // Dot aliases are generally used in tests, so ignore.
}
if strings.HasPrefix(alias, "_") {
return true // Used by go test and for auto-includes, not a conflict.
}
path, err := strconv.Unquote(f.Path.Value)
if err != nil {
pass.Reportf(f.Pos(), "import not quoted")
}
if alias != "" {
value, exist := imports.Load(path)
if exist {
val, ok := value.(aliaspath)
if ok {
if val.alias != alias {
pass.Reportf(f.Pos(), "package %q have alias %q, conflict with %q in %q", path, alias, val.alias, val.position)
}
} else {
pass.Reportf(f.Pos(), "value.(aliaspath) failed, value : ", value)
}
} else {
imports.Store(path, aliaspath{alias: alias, position: pass.Fset.Position(f.Pos())})
}
}
return true
})
}
return nil, nil
}
// autogen files containe "do not edit" before package key word
func isAutogenFile(path string) bool {
file, err := os.Open(path)
if err != nil {
return false
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines := strings.ToUpper(scanner.Text())
if strings.Contains(lines, "PACKAGE") {
return false
}
if strings.Contains(lines, "DO NOT EDIT") {
return true
}
}
return false
}