diff --git a/importPackageName_checker.go b/importPackageName_checker.go new file mode 100644 index 0000000..6f7e5a3 --- /dev/null +++ b/importPackageName_checker.go @@ -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") +} diff --git a/testdata/importPackageName/negative_tests.go b/testdata/importPackageName/negative_tests.go new file mode 100644 index 0000000..9f7f493 --- /dev/null +++ b/testdata/importPackageName/negative_tests.go @@ -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{}) +} diff --git a/testdata/importPackageName/positive_tests.go b/testdata/importPackageName/positive_tests.go new file mode 100644 index 0000000..fa4de95 --- /dev/null +++ b/testdata/importPackageName/positive_tests.go @@ -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{}) +}