2020-04-04 00:59:12 +05:30
|
|
|
package rule
|
|
|
|
|
|
|
|
import (
|
|
|
|
"go/ast"
|
2021-04-23 05:38:53 +05:30
|
|
|
"strings"
|
2020-04-04 00:59:12 +05:30
|
|
|
|
|
|
|
"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 05:38:53 +05:30
|
|
|
// 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-04 00:59:12 +05:30
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-04-23 05:38:53 +05:30
|
|
|
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-04 00:59:12 +05:30
|
|
|
// The first element of each contiguous group of blank imports should have
|
|
|
|
// an explanatory comment of some kind.
|
2021-04-23 05:38:53 +05:30
|
|
|
for i, imp := range file.AST.Imports {
|
|
|
|
pos := file.ToPosition(imp.Pos())
|
2020-04-04 00:59:12 +05:30
|
|
|
|
|
|
|
if !isBlank(imp.Name) {
|
|
|
|
continue // Ignore non-blank imports.
|
|
|
|
}
|
2021-04-23 05:38:53 +05:30
|
|
|
|
2020-04-04 00:59:12 +05:30
|
|
|
if i > 0 {
|
2021-04-23 05:38:53 +05:30
|
|
|
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-04 00:59:12 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-23 05:38:53 +05:30
|
|
|
if imp.Path.Value == embedImportPath && r.fileHasValidEmbedComment(file.AST) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2020-04-04 00:59:12 +05:30
|
|
|
// This is the first blank import of a group.
|
|
|
|
if imp.Doc == nil && imp.Comment == nil {
|
2021-04-23 05:38:53 +05:30
|
|
|
failures = append(failures, lint.Failure{Failure: message, Category: category, Node: imp, Confidence: 1})
|
2020-04-04 00:59:12 +05:30
|
|
|
}
|
|
|
|
}
|
2021-04-23 05:38:53 +05:30
|
|
|
|
|
|
|
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-04 00:59:12 +05:30
|
|
|
}
|