2018-01-25 21:34:38 +02:00
|
|
|
package rule
|
|
|
|
|
|
|
|
import (
|
|
|
|
"go/ast"
|
|
|
|
|
|
|
|
"github.com/mgechev/revive/lint"
|
|
|
|
)
|
|
|
|
|
2018-05-27 06:28:31 +02:00
|
|
|
// ContextAsArgumentRule lints given else constructs.
|
|
|
|
type ContextAsArgumentRule struct{}
|
2018-01-25 21:34:38 +02:00
|
|
|
|
|
|
|
// Apply applies the rule to given file.
|
2018-09-23 00:27:22 +02:00
|
|
|
func (r *ContextAsArgumentRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
|
2018-01-25 21:34:38 +02:00
|
|
|
var failures []lint.Failure
|
|
|
|
|
|
|
|
fileAst := file.AST
|
|
|
|
walker := lintContextArguments{
|
|
|
|
file: file,
|
|
|
|
fileAst: fileAst,
|
|
|
|
onFailure: func(failure lint.Failure) {
|
|
|
|
failures = append(failures, failure)
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
ast.Walk(walker, fileAst)
|
|
|
|
|
|
|
|
return failures
|
|
|
|
}
|
|
|
|
|
|
|
|
// Name returns the rule name.
|
2018-05-27 06:28:31 +02:00
|
|
|
func (r *ContextAsArgumentRule) Name() string {
|
|
|
|
return "context-as-argument"
|
2018-01-25 21:34:38 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type lintContextArguments struct {
|
|
|
|
file *lint.File
|
|
|
|
fileAst *ast.File
|
|
|
|
onFailure func(lint.Failure)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w lintContextArguments) Visit(n ast.Node) ast.Visitor {
|
|
|
|
fn, ok := n.(*ast.FuncDecl)
|
|
|
|
if !ok || len(fn.Type.Params.List) <= 1 {
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
// A context.Context should be the first parameter of a function.
|
|
|
|
// Flag any that show up after the first.
|
2021-05-26 00:09:05 +02:00
|
|
|
previousArgIsCtx := isPkgDot(fn.Type.Params.List[0].Type, "context", "Context")
|
2018-01-25 21:34:38 +02:00
|
|
|
for _, arg := range fn.Type.Params.List[1:] {
|
2021-05-26 00:09:05 +02:00
|
|
|
argIsCtx := isPkgDot(arg.Type, "context", "Context")
|
|
|
|
if argIsCtx && !previousArgIsCtx {
|
2018-01-25 21:34:38 +02:00
|
|
|
w.onFailure(lint.Failure{
|
2021-05-26 00:09:05 +02:00
|
|
|
Node: arg,
|
2018-01-25 21:34:38 +02:00
|
|
|
Category: "arg-order",
|
|
|
|
Failure: "context.Context should be the first parameter of a function",
|
|
|
|
Confidence: 0.9,
|
|
|
|
})
|
|
|
|
break // only flag one
|
|
|
|
}
|
2021-05-26 00:09:05 +02:00
|
|
|
previousArgIsCtx = argIsCtx
|
2018-01-25 21:34:38 +02:00
|
|
|
}
|
|
|
|
return w
|
|
|
|
}
|