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.

max-public-structs.go 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package rule
  2. import (
  3. "go/ast"
  4. "strings"
  5. "github.com/mgechev/revive/lint"
  6. )
  7. // MaxPublicStructsRule lints given else constructs.
  8. type MaxPublicStructsRule struct{}
  9. // Apply applies the rule to given file.
  10. func (r *MaxPublicStructsRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
  11. var failures []lint.Failure
  12. fileAst := file.AST
  13. walker := &lintMaxPublicStructs{
  14. fileAst: fileAst,
  15. onFailure: func(failure lint.Failure) {
  16. failures = append(failures, failure)
  17. },
  18. }
  19. ast.Walk(walker, fileAst)
  20. max, ok := arguments[0].(int64) // Alt. non panicking version
  21. if !ok {
  22. panic(`invalid value passed as argument number to the "max-public-structs" rule`)
  23. }
  24. if walker.current > max {
  25. walker.onFailure(lint.Failure{
  26. Failure: "you have exceeded the maximum number of public struct declarations",
  27. Confidence: 1,
  28. Node: fileAst,
  29. Category: "style",
  30. })
  31. }
  32. return failures
  33. }
  34. // Name returns the rule name.
  35. func (r *MaxPublicStructsRule) Name() string {
  36. return "max-public-structs"
  37. }
  38. type lintMaxPublicStructs struct {
  39. current int64
  40. fileAst *ast.File
  41. onFailure func(lint.Failure)
  42. }
  43. func (w *lintMaxPublicStructs) Visit(n ast.Node) ast.Visitor {
  44. switch v := n.(type) {
  45. case *ast.TypeSpec:
  46. name := v.Name.Name
  47. first := string(name[0])
  48. if strings.ToUpper(first) == first {
  49. w.current++
  50. }
  51. break
  52. }
  53. return w
  54. }