You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

context-as-argument.go 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package rule
  2. import (
  3. "go/ast"
  4. "github.com/mgechev/revive/lint"
  5. )
  6. // ContextAsArgumentRule lints given else constructs.
  7. type ContextAsArgumentRule struct{}
  8. // Apply applies the rule to given file.
  9. func (r *ContextAsArgumentRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
  10. var failures []lint.Failure
  11. fileAst := file.AST
  12. walker := lintContextArguments{
  13. file: file,
  14. fileAst: fileAst,
  15. onFailure: func(failure lint.Failure) {
  16. failures = append(failures, failure)
  17. },
  18. }
  19. ast.Walk(walker, fileAst)
  20. return failures
  21. }
  22. // Name returns the rule name.
  23. func (r *ContextAsArgumentRule) Name() string {
  24. return "context-as-argument"
  25. }
  26. type lintContextArguments struct {
  27. file *lint.File
  28. fileAst *ast.File
  29. onFailure func(lint.Failure)
  30. }
  31. func (w lintContextArguments) Visit(n ast.Node) ast.Visitor {
  32. fn, ok := n.(*ast.FuncDecl)
  33. if !ok || len(fn.Type.Params.List) <= 1 {
  34. return w
  35. }
  36. // A context.Context should be the first parameter of a function.
  37. // Flag any that show up after the first.
  38. for _, arg := range fn.Type.Params.List[1:] {
  39. if isPkgDot(arg.Type, "context", "Context") {
  40. w.onFailure(lint.Failure{
  41. Node: fn,
  42. Category: "arg-order",
  43. Failure: "context.Context should be the first parameter of a function",
  44. Confidence: 0.9,
  45. })
  46. break // only flag one
  47. }
  48. }
  49. return w
  50. }