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.

get-return.go 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package rule
  2. import (
  3. "fmt"
  4. "go/ast"
  5. "strings"
  6. "github.com/mgechev/revive/lint"
  7. )
  8. // GetReturnRule lints given else constructs.
  9. type GetReturnRule struct{}
  10. // Apply applies the rule to given file.
  11. func (r *GetReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
  12. var failures []lint.Failure
  13. onFailure := func(failure lint.Failure) {
  14. failures = append(failures, failure)
  15. }
  16. w := lintReturnRule{onFailure}
  17. ast.Walk(w, file.AST)
  18. return failures
  19. }
  20. // Name returns the rule name.
  21. func (r *GetReturnRule) Name() string {
  22. return "get-return"
  23. }
  24. type lintReturnRule struct {
  25. onFailure func(lint.Failure)
  26. }
  27. func isGetter(name string) bool {
  28. if strings.HasPrefix(strings.ToUpper(name), "GET") {
  29. if len(name) > 3 {
  30. c := name[3]
  31. return !(c >= 'a' && c <= 'z')
  32. }
  33. }
  34. return false
  35. }
  36. func hasResults(rs *ast.FieldList) bool {
  37. return rs != nil && len(rs.List) > 0
  38. }
  39. func (w lintReturnRule) Visit(node ast.Node) ast.Visitor {
  40. fd, ok := node.(*ast.FuncDecl)
  41. if !ok {
  42. return w
  43. }
  44. if !isGetter(fd.Name.Name) {
  45. return w
  46. }
  47. if !hasResults(fd.Type.Results) {
  48. w.onFailure(lint.Failure{
  49. Confidence: 0.8,
  50. Node: fd,
  51. Category: "logic",
  52. Failure: fmt.Sprintf("function '%s' seems to be a getter but it does not return any result", fd.Name.Name),
  53. })
  54. }
  55. return w
  56. }