Created
January 31, 2021 05:08
Custom analyzer which prevent using sync.Mutex as global variable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"go/ast" | |
"golang.org/x/tools/go/analysis" | |
) | |
var Analyzer = &analysis.Analyzer{ | |
Name: "globalmutex", | |
Doc: "declare global mutex has no effect in multi-process, do not use", | |
Run: run, | |
} | |
func run(pass *analysis.Pass) (interface{}, error) { | |
for _, f := range pass.Files { | |
for _, decl := range f.Decls { | |
if decl, ok := decl.(*ast.GenDecl); ok { | |
for _, spec := range decl.Specs { | |
if spec, ok := spec.(*ast.ValueSpec); ok { | |
for _, name := range spec.Names { | |
obj := pass.TypesInfo.Defs[name] | |
if obj == nil { | |
continue | |
} | |
if obj.Type().String() == "sync.Mutex" || obj.Type().String() == "*sync.Mutex" { | |
pass.Report(analysis.Diagnostic{ | |
Pos: name.Pos(), | |
End: 0, | |
Category: "", | |
Message: "do not use mutex in global scope, it doesn't supported in multi-process and parallel test", | |
SuggestedFixes: nil, | |
Related: nil, | |
}) | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
return nil, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment