Skip to content

Whitelist regexp and fmt.Errorf global vars #718

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 50 additions & 2 deletions pkg/golinters/gochecknoglobals.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,56 @@ func (lint Gochecknoglobals) checkFile(f *ast.File, fset *token.FileSet) []resul
return res
}

func isWhitelisted(i *ast.Ident) bool {
return i.Name == "_" || i.Name == "version" || looksLikeError(i)
type whitelistedExpression struct {
Name string
SelName string
}

func isWhitelisted(v ast.Node) bool {
switch i := v.(type) {
case *ast.Ident:
return i.Name == "_" || i.Name == "version" || looksLikeError(i)
case *ast.CallExpr:
if expr, ok := i.Fun.(*ast.SelectorExpr); ok {
return isWhitelistedSelectorExpression(expr)
}
case *ast.CompositeLit:
if expr, ok := i.Type.(*ast.SelectorExpr); ok {
return isWhitelistedSelectorExpression(expr)
}
}

return false
}

func isWhitelistedSelectorExpression(v *ast.SelectorExpr) bool {
x, ok := v.X.(*ast.Ident)
if !ok {
return false
}

whitelist := []whitelistedExpression{
{
Name: "errors",
SelName: "New",
},
{
Name: "fmt",
SelName: "Errorf",
},
{
Name: "regexp",
SelName: "MustCompile",
},
}

for _, i := range whitelist {
if x.Name == i.Name && v.Sel.Name == i.SelName {
return true
}
}

return false
}

// looksLikeError returns true if the AST identifier starts
Expand Down
4 changes: 4 additions & 0 deletions test/testdata/gochecknoglobals.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ import (

var noGlobalsVar int // ERROR "`noGlobalsVar` is a global variable"
var ErrSomeType = errors.New("test that global erorrs aren't warned")
var ErrFmt1 = fmt.Errorf("test that global errors made with fmt aren't warned")

//var re1 = regexp.MustComplile("/test that regexp aren't warned/")

func NoGlobals() {
_ = ErrFmt1
fmt.Print(noGlobalsVar)
}