-
Notifications
You must be signed in to change notification settings - Fork 265
/
blank-imports.go
75 lines (58 loc) 路 1.75 KB
/
blank-imports.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
package rule
import (
"go/ast"
"strings"
"github.com/mgechev/revive/lint"
)
// BlankImportsRule lints given else constructs.
type BlankImportsRule struct{}
// Name returns the rule name.
func (r *BlankImportsRule) Name() string {
return "blank-imports"
}
// Apply applies the rule to given file.
func (r *BlankImportsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
if file.Pkg.IsMain() || file.IsTest() {
return nil
}
const (
message = "a blank import should be only in a main or test package, or have a comment justifying it"
category = "imports"
embedImportPath = `"embed"`
)
var failures []lint.Failure
// The first element of each contiguous group of blank imports should have
// an explanatory comment of some kind.
for i, imp := range file.AST.Imports {
pos := file.ToPosition(imp.Pos())
if !isBlank(imp.Name) {
continue // Ignore non-blank imports.
}
if i > 0 {
prev := file.AST.Imports[i-1]
prevPos := file.ToPosition(prev.Pos())
isSubsequentBlancInAGroup := isBlank(prev.Name) && prevPos.Line+1 == pos.Line && prev.Path.Value != embedImportPath
if isSubsequentBlancInAGroup {
continue
}
}
if imp.Path.Value == embedImportPath && r.fileHasValidEmbedComment(file.AST) {
continue
}
// This is the first blank import of a group.
if imp.Doc == nil && imp.Comment == nil {
failures = append(failures, lint.Failure{Failure: message, Category: category, Node: imp, Confidence: 1})
}
}
return failures
}
func (r *BlankImportsRule) fileHasValidEmbedComment(fileAst *ast.File) bool {
for _, commentGroup := range fileAst.Comments {
for _, comment := range commentGroup.List {
if strings.HasPrefix(comment.Text, "//go:embed ") {
return true
}
}
}
return false
}