You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

blank-imports.go 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package rule
  2. import (
  3. "go/ast"
  4. "github.com/mgechev/revive/lint"
  5. )
  6. // BlankImportsRule lints given else constructs.
  7. type BlankImportsRule struct{}
  8. // Apply applies the rule to given file.
  9. func (r *BlankImportsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
  10. var failures []lint.Failure
  11. fileAst := file.AST
  12. walker := lintBlankImports{
  13. file: file,
  14. fileAst: fileAst,
  15. onFailure: func(failure lint.Failure) {
  16. failures = append(failures, failure)
  17. },
  18. }
  19. ast.Walk(walker, fileAst)
  20. return failures
  21. }
  22. // Name returns the rule name.
  23. func (r *BlankImportsRule) Name() string {
  24. return "blank-imports"
  25. }
  26. type lintBlankImports struct {
  27. fileAst *ast.File
  28. file *lint.File
  29. onFailure func(lint.Failure)
  30. }
  31. func (w lintBlankImports) Visit(_ ast.Node) ast.Visitor {
  32. // In package main and in tests, we don't complain about blank imports.
  33. if w.file.Pkg.IsMain() || w.file.IsTest() {
  34. return nil
  35. }
  36. // The first element of each contiguous group of blank imports should have
  37. // an explanatory comment of some kind.
  38. for i, imp := range w.fileAst.Imports {
  39. pos := w.file.ToPosition(imp.Pos())
  40. if !isBlank(imp.Name) {
  41. continue // Ignore non-blank imports.
  42. }
  43. if i > 0 {
  44. prev := w.fileAst.Imports[i-1]
  45. prevPos := w.file.ToPosition(prev.Pos())
  46. if isBlank(prev.Name) && prevPos.Line+1 == pos.Line {
  47. continue // A subsequent blank in a group.
  48. }
  49. }
  50. // This is the first blank import of a group.
  51. if imp.Doc == nil && imp.Comment == nil {
  52. w.onFailure(lint.Failure{
  53. Node: imp,
  54. Failure: "a blank import should be only in a main or test package, or have a comment justifying it",
  55. Confidence: 1,
  56. Category: "imports",
  57. })
  58. }
  59. }
  60. return nil
  61. }