Repository navigation
Expand file tree
/
Copy pathgotx.go
More file actions
88 lines (71 loc) · 1.73 KB
/
Copy pathgotx.go
File metadata and controls
88 lines (71 loc) · 1.73 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"bytes"
"go/ast"
"go/printer"
"go/token"
"go/types"
"golang.org/x/tools/go/analysis"
)
var Analyzer = &analysis.Analyzer{
Name: "gotx",
Doc: "reports references of a transaction's receiver type from inside the transaction",
Run: run,
}
func run(pass *analysis.Pass) (interface{}, error) {
for _, file := range pass.Files {
insideTransaction := false
var transactionReceiverType types.Type
var begTransactionPos token.Pos
var endTransactionPos token.Pos
ast.Inspect(file, func(n ast.Node) bool {
if !insideTransaction {
ce, ok := n.(*ast.CallExpr)
if !ok {
return true
}
se, ok := ce.Fun.(*ast.SelectorExpr)
if !ok {
return true
}
if !(se.Sel.Name == "InsideTx" || se.Sel.Name == "InsideTransaction") {
return true
}
insideTransaction = true
transactionReceiverType = pass.TypesInfo.TypeOf(se.X)
begTransactionPos = ce.Lparen
endTransactionPos = ce.Rparen
return true
}
if n == nil {
return true
}
if n.Pos() < begTransactionPos {
// Transaction block hasn't started yet
return true
}
if n.Pos() >= endTransactionPos {
// Transaction block ended
insideTransaction = false
return true
}
ident, ok := n.(*ast.Ident)
if !ok {
return true
}
if pass.TypesInfo.TypeOf(ident) == transactionReceiverType {
pass.Reportf(ident.Pos(), "transaction receiver's type used inside transaction - only the transaction type should be used %q",
render(pass.Fset, ident))
}
return true
})
}
return nil, nil
}
func render(fset *token.FileSet, x interface{}) string {
var buf bytes.Buffer
if err := printer.Fprint(&buf, fset, x); err != nil {
panic(err)
}
return buf.String()
}