Skip to content

Commit

Permalink
add importPackageName checker
Browse files Browse the repository at this point in the history
Signed-off-by: Iskander Sharipov <[email protected]>
  • Loading branch information
quasilyte committed Oct 21, 2018
1 parent 034ed78 commit aab431f
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 0 deletions.
47 changes: 47 additions & 0 deletions importPackageName_checker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package contrib

import (
"go/ast"
"strings"

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

func init() {
var info lintpack.CheckerInfo
info.Name = "importPackageName"
info.Tags = []string{"style"}
info.Summary = "Detects when imported package names are unnecessary renamed"
info.Before = `import lint "github.com/go-critic/go-critic/lint"`
info.After = `import "github.com/go-critic/go-critic/lint"`

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

type importPackageNameChecker struct {
astwalk.WalkHandler
ctx *lintpack.CheckerContext
}

func (c *importPackageNameChecker) WalkFile(file *ast.File) {
for _, imp := range file.Imports {
var pkgName string
for _, pkgImport := range c.ctx.Pkg.Imports() {
if pkgImport.Path() == strings.Trim(imp.Path.Value, `"`) {
pkgName = pkgImport.Name()
break
}
}

if imp.Name != nil && imp.Name.Name == pkgName {
c.warn(imp)
}
}
}

func (c *importPackageNameChecker) warn(cause ast.Node) {
c.ctx.Warn(cause, "unnecessary rename of import package")
}
15 changes: 15 additions & 0 deletions testdata/importPackageName/negative_tests.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package checker_test

import (
"fmt"

linter "github.com/go-critic/go-critic/lint"

dummy "github.com/go-critic/go-critic/lint/internal/dummy"
)

func noWarnings() {
dummy.Dummy()

fmt.Printf("Hello Rule=%v", linter.Rule{})
}
18 changes: 18 additions & 0 deletions testdata/importPackageName/positive_tests.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package checker_test

import (
/// unnecessary rename of import package
fmt "fmt"

/// unnecessary rename of import package
lint "github.com/go-critic/go-critic/lint"

/// unnecessary rename of import package
dummypkg "github.com/go-critic/go-critic/lint/internal/dummy"
)

func warnings() {
dummypkg.Dummy()

fmt.Printf("Hello Rule=%v\n", lint.Rule{})
}

0 comments on commit aab431f

Please sign in to comment.