2018-09-30 21:29:11 +02:00
|
|
|
package rule
|
|
|
|
|
|
|
|
import (
|
|
|
|
"go/ast"
|
2018-10-03 10:01:41 +02:00
|
|
|
|
|
|
|
"github.com/mgechev/revive/lint"
|
2018-09-30 21:29:11 +02:00
|
|
|
)
|
|
|
|
|
2018-10-03 10:01:41 +02:00
|
|
|
// WaitGroupByValueRule lints sync.WaitGroup passed by copy in functions.
|
|
|
|
type WaitGroupByValueRule struct{}
|
2018-09-30 21:29:11 +02:00
|
|
|
|
|
|
|
// Apply applies the rule to given file.
|
2022-04-10 11:55:13 +02:00
|
|
|
func (*WaitGroupByValueRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
|
2018-09-30 21:29:11 +02:00
|
|
|
var failures []lint.Failure
|
|
|
|
|
|
|
|
onFailure := func(failure lint.Failure) {
|
|
|
|
failures = append(failures, failure)
|
|
|
|
}
|
|
|
|
|
2018-10-03 10:01:41 +02:00
|
|
|
w := lintWaitGroupByValueRule{onFailure: onFailure}
|
2018-09-30 21:29:11 +02:00
|
|
|
ast.Walk(w, file.AST)
|
|
|
|
return failures
|
|
|
|
}
|
|
|
|
|
|
|
|
// Name returns the rule name.
|
2022-04-10 11:55:13 +02:00
|
|
|
func (*WaitGroupByValueRule) Name() string {
|
2018-10-03 10:01:41 +02:00
|
|
|
return "waitgroup-by-value"
|
2018-09-30 21:29:11 +02:00
|
|
|
}
|
|
|
|
|
2018-10-03 10:01:41 +02:00
|
|
|
type lintWaitGroupByValueRule struct {
|
2018-09-30 21:29:11 +02:00
|
|
|
onFailure func(lint.Failure)
|
|
|
|
}
|
|
|
|
|
2018-10-03 10:01:41 +02:00
|
|
|
func (w lintWaitGroupByValueRule) Visit(node ast.Node) ast.Visitor {
|
2018-09-30 21:29:11 +02:00
|
|
|
// look for function declarations
|
|
|
|
fd, ok := node.(*ast.FuncDecl)
|
|
|
|
if !ok {
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check all function's parameters
|
|
|
|
for _, field := range fd.Type.Params.List {
|
|
|
|
if !w.isWaitGroup(field.Type) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
w.onFailure(lint.Failure{
|
|
|
|
Confidence: 1,
|
|
|
|
Node: field,
|
|
|
|
Failure: "sync.WaitGroup passed by value, the function will get a copy of the original one",
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-10-03 10:01:41 +02:00
|
|
|
func (lintWaitGroupByValueRule) isWaitGroup(ft ast.Expr) bool {
|
2018-09-30 21:29:11 +02:00
|
|
|
se, ok := ft.(*ast.SelectorExpr)
|
|
|
|
if !ok {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
x, _ := se.X.(*ast.Ident)
|
|
|
|
sel := se.Sel.Name
|
|
|
|
return x.Name == "sync" && sel == "WaitGroup"
|
|
|
|
}
|