summaryrefslogtreecommitdiff
path: root/cmd/cvet/code_smells.go
blob: f306d85840dfa92ffc4f934f8d52efc2f409f015 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

package main

import (
	"go/ast"

	"github.com/samber/lo"
	"golang.org/x/tools/go/analysis"
)

var codeSmellsAnalyzer = &analysis.Analyzer{
	Name: "logging",
	Doc:  "Logging best practices",
	Run:  run,
}

func isIdent(node ast.Node, name string) bool {
	if ident, ok := node.(*ast.Ident); ok {
		return ident.Name == name
	}
	return false
}

func isSelector(node ast.Node, left string, right string) bool {
	if selector, ok := node.(*ast.SelectorExpr); ok {
		return isIdent(selector.X, left) && isIdent(selector.Sel, right)
	}
	return false
}

func visit(pass *analysis.Pass) func(node ast.Node) bool {
	return func(node ast.Node) bool {
		switch node := node.(type) {
		case *ast.CallExpr:
			checkLogUsage(pass, node)
		case *ast.FuncDecl:
			if isQueryFunc(node) {
				checkQueryFunc(pass, node)
			}
			if isCommandFunc(node) {
				checkCommandFunc(pass, node)
			}
			if field, ok := lo.Find(node.Type.Params.List, func(field *ast.Field) bool {
				return isSelector(field.Type, "context", "Context")
			}); ok {
				if field != node.Type.Params.List[0] {
					pass.Reportf(node.Pos(), "context.Context must be the first parameter")
				}
				if field.Names[0].Name != "ctx" {
					pass.Reportf(node.Pos(), "context.Context parameter must be named ctx")
				}
			}
		case *ast.BlockStmt:
			checkLogBeforePanic(pass, node)
		}
		return true
	}
}

func run(pass *analysis.Pass) (interface{}, error) {
	for _, file := range pass.Files {
		ast.Inspect(file, visit(pass))
	}
	return nil, nil //nolint:nilnil
}