2020-04-03 19:29:12 +00:00
|
|
|
package rule
|
|
|
|
|
|
|
|
import (
|
|
|
|
"go/ast"
|
2021-04-23 00:08:53 +00:00
|
|
|
"strings"
|
2020-04-03 19:29:12 +00:00
|
|
|
|
|
|
|
"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"
|
|
|
|
}
|
|
|
|
|
2021-04-23 00:08:53 +00:00
|
|
|
// Apply applies the rule to given file.
|
|
|
|
func (r *BlankImportsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
|
|
|
|
if file.Pkg.IsMain() || file.IsTest() {
|
2020-04-03 19:29:12 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-04-23 00:08:53 +00:00
|
|
|
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
|
|
|
|
|
2020-04-03 19:29:12 +00:00
|
|
|
// The first element of each contiguous group of blank imports should have
|
|
|
|
// an explanatory comment of some kind.
|
2021-04-23 00:08:53 +00:00
|
|
|
for i, imp := range file.AST.Imports {
|
|
|
|
pos := file.ToPosition(imp.Pos())
|
2020-04-03 19:29:12 +00:00
|
|
|
|
|
|
|
if !isBlank(imp.Name) {
|
|
|
|
continue // Ignore non-blank imports.
|
|
|
|
}
|
2021-04-23 00:08:53 +00:00
|
|
|
|
2020-04-03 19:29:12 +00:00
|
|
|
if i > 0 {
|
2021-04-23 00:08:53 +00:00
|
|
|
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
|
2020-04-03 19:29:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-23 00:08:53 +00:00
|
|
|
if imp.Path.Value == embedImportPath && r.fileHasValidEmbedComment(file.AST) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2020-04-03 19:29:12 +00:00
|
|
|
// This is the first blank import of a group.
|
|
|
|
if imp.Doc == nil && imp.Comment == nil {
|
2021-04-23 00:08:53 +00:00
|
|
|
failures = append(failures, lint.Failure{Failure: message, Category: category, Node: imp, Confidence: 1})
|
2020-04-03 19:29:12 +00:00
|
|
|
}
|
|
|
|
}
|
2021-04-23 00:08:53 +00:00
|
|
|
|
|
|
|
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
|
2020-04-03 19:29:12 +00:00
|
|
|
}
|