Skip to content

Commit f8997e6

Browse files
committed
Whitelist regexp and fmt.Errorf global vars
1 parent 358ce7c commit f8997e6

File tree

2 files changed

+54
-2
lines changed

2 files changed

+54
-2
lines changed

pkg/golinters/gochecknoglobals.go

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,56 @@ func (lint Gochecknoglobals) checkFile(f *ast.File, fset *token.FileSet) []resul
6060
return res
6161
}
6262

63-
func isWhitelisted(i *ast.Ident) bool {
64-
return i.Name == "_" || i.Name == "version" || looksLikeError(i)
63+
type whitelistedExpression struct {
64+
Name string
65+
SelName string
66+
}
67+
68+
func isWhitelisted(v ast.Node) bool {
69+
switch i := v.(type) {
70+
case *ast.Ident:
71+
return i.Name == "_" || i.Name == "version" || looksLikeError(i)
72+
case *ast.CallExpr:
73+
if expr, ok := i.Fun.(*ast.SelectorExpr); ok {
74+
return isWhitelistedSelectorExpression(expr)
75+
}
76+
case *ast.CompositeLit:
77+
if expr, ok := i.Type.(*ast.SelectorExpr); ok {
78+
return isWhitelistedSelectorExpression(expr)
79+
}
80+
}
81+
82+
return false
83+
}
84+
85+
func isWhitelistedSelectorExpression(v *ast.SelectorExpr) bool {
86+
x, ok := v.X.(*ast.Ident)
87+
if !ok {
88+
return false
89+
}
90+
91+
whitelist := []whitelistedExpression{
92+
{
93+
Name: "errors",
94+
SelName: "New",
95+
},
96+
{
97+
Name: "fmt",
98+
SelName: "Errorf",
99+
},
100+
{
101+
Name: "regexp",
102+
SelName: "MustCompile",
103+
},
104+
}
105+
106+
for _, i := range whitelist {
107+
if x.Name == i.Name && v.Sel.Name == i.SelName {
108+
return true
109+
}
110+
}
111+
112+
return false
65113
}
66114

67115
// looksLikeError returns true if the AST identifier starts

test/testdata/gochecknoglobals.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,11 @@ import (
88

99
var noGlobalsVar int // ERROR "`noGlobalsVar` is a global variable"
1010
var ErrSomeType = errors.New("test that global erorrs aren't warned")
11+
var ErrFmt1 = fmt.Errorf("test that global errors made with fmt aren't warned")
12+
13+
//var re1 = regexp.MustComplile("/test that regexp aren't warned/")
1114

1215
func NoGlobals() {
16+
_ = ErrFmt1
1317
fmt.Print(noGlobalsVar)
1418
}

0 commit comments

Comments
 (0)