-
Notifications
You must be signed in to change notification settings - Fork 0
/
singleimports.go
60 lines (44 loc) · 1.07 KB
/
singleimports.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
package consistent
import (
"go/ast"
"go/token"
"golang.org/x/tools/go/analysis"
)
const (
singleImportsBare = "bare"
singleImportsParens = "parens"
)
var singleImportsFlagAllowedValues = []string{flagIgnore, singleImportsBare, singleImportsParens}
func checkSingleImports(pass *analysis.Pass, file *ast.File, mode string) {
if mode == flagIgnore {
return
}
decls := importGenDecls(file)
if len(decls) != 1 {
return
}
decl := decls[0]
if len(decl.Specs) != 1 {
return
}
switch parens := decl.Lparen.IsValid() && decl.Rparen.IsValid(); {
case mode == singleImportsBare && parens:
reportf(pass, decl.Pos(), "remove parens around single import declaration")
case mode == singleImportsParens && !parens:
reportf(pass, decl.Pos(), "add parens around single import declaration")
}
}
func importGenDecls(file *ast.File) []*ast.GenDecl {
decls := []*ast.GenDecl{}
for _, decl := range file.Decls {
decl, ok := decl.(*ast.GenDecl)
if !ok {
continue
}
if decl.Tok != token.IMPORT {
continue
}
decls = append(decls, decl)
}
return decls
}