選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

context-keys-type.go 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package rule
  2. import (
  3. "fmt"
  4. "go/ast"
  5. "go/types"
  6. "github.com/mgechev/revive/lint"
  7. )
  8. // ContextKeysType lints given else constructs.
  9. type ContextKeysType struct{}
  10. // Apply applies the rule to given file.
  11. func (r *ContextKeysType) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
  12. var failures []lint.Failure
  13. fileAst := file.AST
  14. walker := lintContextKeyTypes{
  15. file: file,
  16. fileAst: fileAst,
  17. onFailure: func(failure lint.Failure) {
  18. failures = append(failures, failure)
  19. },
  20. }
  21. file.Pkg.TypeCheck()
  22. ast.Walk(walker, fileAst)
  23. return failures
  24. }
  25. // Name returns the rule name.
  26. func (r *ContextKeysType) Name() string {
  27. return "context-keys-type"
  28. }
  29. type lintContextKeyTypes struct {
  30. file *lint.File
  31. fileAst *ast.File
  32. onFailure func(lint.Failure)
  33. }
  34. func (w lintContextKeyTypes) Visit(n ast.Node) ast.Visitor {
  35. switch n := n.(type) {
  36. case *ast.CallExpr:
  37. checkContextKeyType(w, n)
  38. }
  39. return w
  40. }
  41. func checkContextKeyType(w lintContextKeyTypes, x *ast.CallExpr) {
  42. f := w.file
  43. sel, ok := x.Fun.(*ast.SelectorExpr)
  44. if !ok {
  45. return
  46. }
  47. pkg, ok := sel.X.(*ast.Ident)
  48. if !ok || pkg.Name != "context" {
  49. return
  50. }
  51. if sel.Sel.Name != "WithValue" {
  52. return
  53. }
  54. // key is second argument to context.WithValue
  55. if len(x.Args) != 3 {
  56. return
  57. }
  58. key := f.Pkg.TypesInfo.Types[x.Args[1]]
  59. if ktyp, ok := key.Type.(*types.Basic); ok && ktyp.Kind() != types.Invalid {
  60. w.onFailure(lint.Failure{
  61. Confidence: 1,
  62. Node: x,
  63. Category: "content",
  64. Failure: fmt.Sprintf("should not use basic type %s as key in context.WithValue", key.Type),
  65. })
  66. }
  67. }