/
main.go
225 lines (195 loc) · 6.18 KB
/
main.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package main
import (
"flag"
"fmt"
"go/ast"
"go/build"
"go/token"
"go/types"
"log"
"strings"
"golang.org/x/tools/go/loader"
"github.com/kisielk/gotool"
)
type mapCallbackFunc func(loc token.Position, keyStr, valStr string)
type equalityCallbackFunc func(loc token.Position, xStr, yStr string)
func main() {
tags := flag.String("tags", "", "List of build tags to take into account when linting.")
skipVendor := flag.Bool("skip-vendor", true, "Skip vendor directors.")
skipMap := flag.Bool("skip-map", false, "Skip checking for map[time.Time]<T>")
skipEquality := flag.Bool("skip-equality", false, "Skip checking for time.Time == time.Time")
flag.Parse()
importPaths := gotool.ImportPaths(flag.Args())
if len(importPaths) == 0 {
flag.Usage()
return
}
var filteredPaths []string
if *skipVendor {
filteredPaths = filterOutVendor(importPaths)
} else {
filteredPaths = importPaths
}
mapKeyCallback := printMapKeyError
if *skipMap {
mapKeyCallback = nil
}
equalityCallback := printEqualityError
if *skipEquality {
equalityCallback = nil
}
handleImportPaths(filteredPaths, strings.Fields(*tags), mapKeyCallback, equalityCallback)
}
func filterOutVendor(importPaths []string) []string {
filteredStrings := []string{}
for _, importPath := range importPaths {
if !strings.Contains(importPath, "/vendor/") {
filteredStrings = append(filteredStrings, importPath)
}
}
return filteredStrings
}
func handleImportPaths(
importPaths []string,
buildTags []string,
mapCallback mapCallbackFunc,
equalityCallback equalityCallbackFunc,
) {
fs := token.NewFileSet()
ctx := build.Default
ctx.BuildTags = buildTags
conf := loader.Config{
Fset: fs,
Build: &ctx,
// Continue even if type or IO errors are present
AllowErrors: true,
}
for _, importPath := range importPaths {
conf.ImportWithTests(importPath)
}
prog, err := conf.Load()
if err != nil {
log.Fatal(err)
}
for _, pkg := range prog.InitialPackages() {
for _, file := range pkg.Files {
ast.Walk(nodeVisitor{
fs: fs,
types: pkg.Types,
mapCallback: mapCallback,
equalityCallback: equalityCallback,
}, file)
}
}
}
type nodeVisitor struct {
fs *token.FileSet
types map[ast.Expr]types.TypeAndValue
mapCallback mapCallbackFunc
equalityCallback equalityCallbackFunc
}
func (v nodeVisitor) Visit(node ast.Node) ast.Visitor {
// Detect time.Time == time.Time
binary, ok := node.(*ast.BinaryExpr)
if ok && v.equalityCallback != nil {
xType := v.types[binary.X].Type
yType := v.types[binary.Y].Type
if binary.Op == token.EQL &&
// Type can be nil if there was a type-error
xType != nil && isTimeOrContainsTime(xType) &&
yType != nil && isTimeOrContainsTime(yType) {
v.equalityCallback(v.fs.Position(binary.Pos()), xType.String(), yType.String())
}
return nil
}
// Detect map[time.Time]<T>
mapNode, ok := node.(*ast.MapType)
if ok && v.mapCallback != nil {
mapType := v.types[mapNode].Type.(*types.Map)
position := v.fs.Position(mapNode.Map)
keyStr := mapType.Key().String()
valStr := mapType.Elem().String()
containsTime := isTimeOrContainsTime(mapType.Key())
if containsTime {
v.mapCallback(position, keyStr, valStr)
return nil
}
}
return v
}
// isTimeOrContainsTime returns whether the type x represents an instance of
// time.Time or contains a nested time.Time
func isTimeOrContainsTime(x types.Type) bool {
typeUnderlying := x.Underlying()
_, ok := typeUnderlying.(*types.Struct)
if !ok {
return false
}
typeStr := x.String()
// Detects map[time.Time]<T>
if strings.Contains(typeStr, "time.Time") {
return true
}
// Detects map[timeAlias]<T>
structType, ok := typeUnderlying.(*types.Struct)
if ok && structType.NumFields() == 3 {
// VERSION <= go 1.8.X
if structType.Field(0).Name() == "sec" &&
structType.Field(0).Type().String() == "int64" &&
structType.Field(1).Name() == "nsec" &&
structType.Field(1).Type().String() == "int32" &&
structType.Field(2).Name() == "loc" &&
structType.Field(2).Type().String() == "*time.Location" {
return true
}
// VERSION >= go 1.9.X
if structType.Field(0).Name() == "wall" &&
structType.Field(0).Type().String() == "uint64" &&
structType.Field(1).Name() == "ext" &&
structType.Field(1).Type().String() == "int64" &&
structType.Field(2).Name() == "loc" &&
structType.Field(2).Type().String() == "*time.Location" {
return true
}
}
// Detects objects with nested time.Time I.E map[{inner: time.Time}]<T>
if strings.Contains(typeUnderlying.String(), "time.Time") {
return true
}
return false
}
func printMapKeyError(position token.Position, keyStr, valStr string) {
fmt.Printf(
"%s: Reconsider use of map[%s]%s . Storing an instance of time.Time as part of a map key is not recommended.\n",
position.String(),
keyStr,
valStr,
)
}
func printEqualityError(position token.Position, xStr, yStr string) {
fmt.Printf(
"%s: %s and %s contain time.Time which can be dangerous to compare with `==`. Consider writing a custom comparison or using the .Equal() method of time.Time.\n",
position.String(),
xStr,
yStr,
)
}