From 63c4d727a88b4a2feb1def575335487f9c0363c3 Mon Sep 17 00:00:00 2001 From: Leonel Quinteros Date: Tue, 5 Dec 2017 13:19:09 -0300 Subject: [PATCH] Fix False positives with custom errors-package and errors.New(fmt.Sprintf(...)) Issue #350 --- lint.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/lint.go b/lint.go index e1a5f302..69c7e419 100644 --- a/lint.go +++ b/lint.go @@ -23,6 +23,8 @@ import ( "unicode" "unicode/utf8" + "golang.org/x/tools/go/ast/astutil" + "golang.org/x/tools/go/gcexportdata" ) @@ -1115,6 +1117,9 @@ func (f *file) lintErrorf() { if !isErrorsNew && !isTestingError { return true } + if !f.imports("errors") { + return true + } arg := ce.Args[0] ce, ok = arg.(*ast.CallExpr) if !ok || !isPkgDot(ce.Fun, "fmt", "Sprintf") { @@ -1688,6 +1693,21 @@ func (f *file) srcLineWithMatch(node ast.Node, pattern string) (m []string) { return rx.FindStringSubmatch(line) } +// imports returns true if the current file imports the specified package path +func (f *file) imports(importPath string) bool { + all := astutil.Imports(f.fset, f.f) + for _, p := range all { + for _, i := range p { + uq, err := strconv.Unquote(i.Path.Value) + if err == nil && importPath == uq { + return true + } + } + } + + return false +} + // srcLine returns the complete line at p, including the terminating newline. func srcLine(src []byte, p token.Position) string { // Run to end of line in both directions if not at line start/end.