|
| 1 | +package golinters |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "go/ast" |
| 7 | + "go/token" |
| 8 | + "strings" |
| 9 | + |
| 10 | + "github.com/golangci/golangci-lint/pkg/lint/linter" |
| 11 | + "github.com/golangci/golangci-lint/pkg/result" |
| 12 | +) |
| 13 | + |
| 14 | +type Gochecknoglobals struct{} |
| 15 | + |
| 16 | +func (Gochecknoglobals) Name() string { |
| 17 | + return "gochecknoglobals" |
| 18 | +} |
| 19 | + |
| 20 | +func (Gochecknoglobals) Desc() string { |
| 21 | + return "Checks that no globals are present in Go code" |
| 22 | +} |
| 23 | + |
| 24 | +func (lint Gochecknoglobals) Run(ctx context.Context, lintCtx *linter.Context) ([]result.Issue, error) { |
| 25 | + var res []result.Issue |
| 26 | + for _, f := range lintCtx.ASTCache.GetAllValidFiles() { |
| 27 | + res = append(res, lint.checkFile(f.F, f.Fset)...) |
| 28 | + } |
| 29 | + |
| 30 | + return res, nil |
| 31 | +} |
| 32 | + |
| 33 | +func (lint Gochecknoglobals) checkFile(f *ast.File, fset *token.FileSet) []result.Issue { |
| 34 | + var res []result.Issue |
| 35 | + for _, decl := range f.Decls { |
| 36 | + genDecl, ok := decl.(*ast.GenDecl) |
| 37 | + if !ok { |
| 38 | + continue |
| 39 | + } |
| 40 | + if genDecl.Tok != token.VAR { |
| 41 | + continue |
| 42 | + } |
| 43 | + |
| 44 | + for _, spec := range genDecl.Specs { |
| 45 | + valueSpec := spec.(*ast.ValueSpec) |
| 46 | + for _, vn := range valueSpec.Names { |
| 47 | + if isWhitelisted(vn) { |
| 48 | + continue |
| 49 | + } |
| 50 | + |
| 51 | + res = append(res, result.Issue{ |
| 52 | + Pos: fset.Position(genDecl.TokPos), |
| 53 | + Text: fmt.Sprintf("%s is a global variable", formatCode(vn.Name, nil)), |
| 54 | + FromLinter: lint.Name(), |
| 55 | + }) |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + return res |
| 61 | +} |
| 62 | + |
| 63 | +func isWhitelisted(i *ast.Ident) bool { |
| 64 | + return i.Name == "_" || looksLikeError(i) |
| 65 | +} |
| 66 | + |
| 67 | +// looksLikeError returns true if the AST identifier starts |
| 68 | +// with 'err' or 'Err', or false otherwise. |
| 69 | +// |
| 70 | +// TODO: https://github.com/leighmcculloch/gochecknoglobals/issues/5 |
| 71 | +func looksLikeError(i *ast.Ident) bool { |
| 72 | + prefix := "err" |
| 73 | + if i.IsExported() { |
| 74 | + prefix = "Err" |
| 75 | + } |
| 76 | + return strings.HasPrefix(i.Name, prefix) |
| 77 | +} |
0 commit comments