Skip to content
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

Add allowed-expressions flag #46

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
58 changes: 46 additions & 12 deletions checknoglobals/check_no_globals.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package checknoglobals

import (
"flag"
"fmt"
"go/ast"
"go/token"
Expand All @@ -18,6 +19,10 @@ type allowedExpression struct {
SelName string
}

type config struct {
AllowedExpression []allowedExpression
}

const Doc = `check that no global variables exist

This analyzer checks for global variables and errors on any found.
Expand All @@ -36,40 +41,46 @@ func Analyzer() *analysis.Analyzer {
Name: "gochecknoglobals",
Doc: Doc,
Run: checkNoGlobals,
Flags: options(),
RunDespiteErrors: true,
}
}

func isAllowed(cm ast.CommentMap, v ast.Node, ti *types.Info) bool {
func options() flag.FlagSet {
options := flag.NewFlagSet("", flag.ExitOnError)
options.String(
"allowed-expressions", "",
"comma separated list of expressions to exclude from analysis. Ex. regex.MustCompile,promauto.NewHistorgamVec",
)
return *options
}

func isAllowed(conf *config, cm ast.CommentMap, v ast.Node, ti *types.Info) bool {
switch i := v.(type) {
case *ast.GenDecl:
return hasEmbedComment(cm, i)
case *ast.Ident:
return i.Name == "_" || i.Name == "version" || isError(i, ti) || identHasEmbedComment(cm, i)
case *ast.CallExpr:
if expr, ok := i.Fun.(*ast.SelectorExpr); ok {
return isAllowedSelectorExpression(expr)
return isAllowedSelectorExpression(conf, expr)
}
case *ast.CompositeLit:
if expr, ok := i.Type.(*ast.SelectorExpr); ok {
return isAllowedSelectorExpression(expr)
return isAllowedSelectorExpression(conf, expr)
}
}

return false
}

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

allowList := []allowedExpression{
{Name: "regexp", SelName: "MustCompile"},
}

for _, i := range allowList {
for _, i := range conf.AllowedExpression {
if x.Name == i.Name && v.Sel.Name == i.SelName {
return true
}
Expand Down Expand Up @@ -128,7 +139,30 @@ func hasEmbedComment(cm ast.CommentMap, n ast.Node) bool {
return false
}

func parseAllowedExpressions(s string) []allowedExpression {
exprs := []allowedExpression{}
for _, str := range strings.Split(s, ",") {
name, sel, found := strings.Cut(str, ".")
if found {
exprs = append(exprs, allowedExpression{
Name: name,
SelName: sel,
})
}
}
return exprs
}

func checkNoGlobals(pass *analysis.Pass) (interface{}, error) {
conf := &config{
AllowedExpression: []allowedExpression{
{Name: "regexp", SelName: "MustCompile"},
},
}
if f := pass.Analyzer.Flags.Lookup("allowed-expressions"); f != nil {
conf.AllowedExpression = parseAllowedExpressions(f.Value.String())
}

for _, file := range pass.Files {
filename := pass.Fset.Position(file.Pos()).Filename
if !strings.HasSuffix(filename, ".go") {
Expand All @@ -145,15 +179,15 @@ func checkNoGlobals(pass *analysis.Pass) (interface{}, error) {
if genDecl.Tok != token.VAR {
continue
}
if isAllowed(fileCommentMap, genDecl, pass.TypesInfo) {
if isAllowed(conf, fileCommentMap, genDecl, pass.TypesInfo) {
continue
}
for _, spec := range genDecl.Specs {
valueSpec := spec.(*ast.ValueSpec)
onlyAllowedValues := false

for _, vn := range valueSpec.Values {
if isAllowed(fileCommentMap, vn, pass.TypesInfo) {
if isAllowed(conf, fileCommentMap, vn, pass.TypesInfo) {
onlyAllowedValues = true
continue
}
Expand All @@ -167,7 +201,7 @@ func checkNoGlobals(pass *analysis.Pass) (interface{}, error) {
}

for _, vn := range valueSpec.Names {
if isAllowed(fileCommentMap, vn, pass.TypesInfo) {
if isAllowed(conf, fileCommentMap, vn, pass.TypesInfo) {
continue
}

Expand Down
28 changes: 28 additions & 0 deletions checknoglobals/check_no_globals_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,34 @@ func TestCheckNoGlobals(t *testing.T) {
}
}

func TestCheckNoGlobalsAllowedExpressions(t *testing.T) {
testdata := analysistest.TestData()
flags := flag.NewFlagSet("", flag.ExitOnError)
flags.Bool("t", true, "")
flags.String("allowed-expressions", "", "")

analyzer := Analyzer()
analyzer.Flags = *flags

dir := "12"
t.Run(dir, func(t *testing.T) {
analyzer.Flags.Set("allowed-expressions", "template.Must,sync.Once")

t.Run(dir, func(t *testing.T) {
analysistest.Run(t, testdata, analyzer, dir)
})
})

dir = "13"
t.Run(dir, func(t *testing.T) {
analyzer.Flags.Set("allowed-expressions", "invalid.,expression,http. Client")

t.Run(dir, func(t *testing.T) {
analysistest.Run(t, testdata, analyzer, dir)
})
})
}

func BenchmarkRun(b *testing.B) {
analyzer := Analyzer()
flags := flag.NewFlagSet("", flag.ExitOnError)
Expand Down
15 changes: 15 additions & 0 deletions checknoglobals/testdata/src/12/code.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package code

import (
"html/template"
"net/http"
"sync"
)

// HTMLTemplate is excluded by the flag, so should be OK
var HTMLTemplate = template.Must(template.New("").Parse(""))

// sync.Once is excluded by the flag, so should be OK
var once = sync.Once{}

var HTTPClient = http.Client{} // want "HTTPClient is a global variable"
7 changes: 7 additions & 0 deletions checknoglobals/testdata/src/13/code.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package code

import (
"net/http"
)

var HTTPClient = http.Client{} // want "HTTPClient is a global variable"
7 changes: 6 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
module 4d63.com/gochecknoglobals

go 1.15
go 1.18

require golang.org/x/tools v0.5.0

require (
golang.org/x/mod v0.7.0 // indirect
golang.org/x/sys v0.4.0 // indirect
)
27 changes: 0 additions & 27 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,34 +1,7 @@
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.7.0 h1:LapD9S96VoQRhi/GrNTqeBJFrUjs5UHCAtTlgwA5oZA=
golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18=
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.4.0/go.mod h1:9P2UbLfCdcvo3p/nzKvsmas4TnlujnuoV9hGgYzW1lQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.5.0 h1:+bSpV5HIeWkuvgaMfI3UmKRThoTA5ODJTUd8T17NO+4=
golang.org/x/tools v0.5.0/go.mod h1:N+Kgy78s5I24c24dU8OfWNEotWjutIs8SnJvn5IDq+k=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=