Skip to content

Commit

Permalink
checkers: add dupImports checker (go-critic#814)
Browse files Browse the repository at this point in the history
  • Loading branch information
Helcaraxan authored and quasilyte committed Feb 28, 2019
1 parent a9a4a15 commit f5dab9f
Show file tree
Hide file tree
Showing 3 changed files with 102 additions and 0 deletions.
76 changes: 76 additions & 0 deletions checkers/dupImports_checker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package checkers

import (
"fmt"
"go/ast"

"github.com/go-lintpack/lintpack"
)

func init() {
var info lintpack.CheckerInfo
info.Name = "dupImports"
info.Tags = []string{"style", "experimental"}
info.Summary = "Detects multiple imports of the same package under different aliases."
info.Before = `
import (
"fmt"
priting "fmt"
)
func helloWorld() {
fmt.Println("Hello")
printing.Println("World")
}`
info.After = `
import(
"fmt"
)
func helloWorld() {
fmt.Println("Hello")
fmt.Println("World")
}`

collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker {
return &dupImportChecker{ctx: ctx}
})
}

type dupImportChecker struct {
ctx *lintpack.CheckerContext
}

func (c *dupImportChecker) WalkFile(f *ast.File) {
imports := make(map[string][]*ast.ImportSpec)
for _, importDcl := range f.Imports {
pkg := importDcl.Path.Value
imports[pkg] = append(imports[pkg], importDcl)
}

fPos := c.ctx.FileSet.File(f.Pos())
if fPos == nil {
// Bail out if we can't, for any reason, determine
// the source file we are dealing with.
return
}
for _, importList := range imports {
if len(importList) == 1 {
continue
}

msg := fmt.Sprintf("package is imported %d times under different aliases on lines", len(importList))
for idx, importDcl := range importList {
switch {
case idx == len(importList)-1:
msg += " and"
case idx > 0:
msg += ","
}
msg += fmt.Sprintf(" %d", fPos.Line(importDcl.Pos()))
}
for _, importDcl := range importList {
c.ctx.Warn(importDcl, msg)
}
}
}
9 changes: 9 additions & 0 deletions checkers/testdata/dupImports/negative_tests.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package checker_test

import "fmt"

func negativeHelloworld() {
fmt.Println("Hello")
fmt.Println("Shiny")
fmt.Println("World")
}
17 changes: 17 additions & 0 deletions checkers/testdata/dupImports/positive_tests.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package checker_test

/*! package is imported 3 times under different aliases on lines 4, 8 and 10 */
import printing "fmt"

import (
/*! package is imported 3 times under different aliases on lines 4, 8 and 10 */
"fmt"
/*! package is imported 3 times under different aliases on lines 4, 8 and 10 */
print "fmt"
)

func positiveHelloworld() {
fmt.Println("Hello")
print.Println("Shiny")
printing.Println("World")
}

0 comments on commit f5dab9f

Please sign in to comment.