1
0
mirror of https://github.com/mgechev/revive.git synced 2024-11-30 08:57:07 +02:00
revive/rule/blank-imports.go

76 lines
1.7 KiB
Go
Raw Normal View History

2018-01-22 04:04:41 +02:00
package rule
2017-11-27 04:58:15 +02:00
import (
"go/ast"
"strings"
2017-11-27 04:58:15 +02:00
2018-01-25 01:44:03 +02:00
"github.com/mgechev/revive/lint"
2017-11-27 04:58:15 +02:00
)
// BlankImportsRule lints given else constructs.
type BlankImportsRule struct{}
// Name returns the rule name.
2022-04-10 11:55:13 +02:00
func (*BlankImportsRule) Name() string {
2017-11-27 05:06:02 +02:00
return "blank-imports"
2017-11-27 04:58:15 +02: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() {
2017-11-27 04:58:15 +02:00
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
2017-11-27 04:58:15 +02:00
// 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())
2017-11-27 04:58:15 +02:00
if !isBlank(imp.Name) {
continue // Ignore non-blank imports.
}
2017-11-27 04:58:15 +02:00
if i > 0 {
prev := file.AST.Imports[i-1]
prevPos := file.ToPosition(prev.Pos())
2021-10-23 13:25:41 +02:00
isSubsequentBlancInAGroup := prevPos.Line+1 == pos.Line && prev.Path.Value != embedImportPath && isBlank(prev.Name)
if isSubsequentBlancInAGroup {
continue
2017-11-27 04:58:15 +02:00
}
}
if imp.Path.Value == embedImportPath && r.fileHasValidEmbedComment(file.AST) {
continue
}
2017-11-27 04:58:15 +02:00
// 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})
2017-11-27 04:58:15 +02:00
}
}
return failures
}
2022-04-10 11:55:13 +02:00
func (*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
2017-11-27 04:58:15 +02:00
}