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.

argument-limit.go 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package rule
  2. import (
  3. "fmt"
  4. "go/ast"
  5. "github.com/mgechev/revive/lint"
  6. )
  7. // ArgumentsLimitRule lints given else constructs.
  8. type ArgumentsLimitRule struct{}
  9. // Apply applies the rule to given file.
  10. func (r *ArgumentsLimitRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
  11. if len(arguments) != 1 {
  12. panic(`invalid configuration for "argument-limit"`)
  13. }
  14. total, ok := arguments[0].(int64) // Alt. non panicking version
  15. if !ok {
  16. panic(`invalid value passed as argument number to the "argument-list" rule`)
  17. }
  18. var failures []lint.Failure
  19. walker := lintArgsNum{
  20. total: int(total),
  21. onFailure: func(failure lint.Failure) {
  22. failures = append(failures, failure)
  23. },
  24. }
  25. ast.Walk(walker, file.AST)
  26. return failures
  27. }
  28. // Name returns the rule name.
  29. func (r *ArgumentsLimitRule) Name() string {
  30. return "argument-limit"
  31. }
  32. type lintArgsNum struct {
  33. total int
  34. onFailure func(lint.Failure)
  35. }
  36. func (w lintArgsNum) Visit(n ast.Node) ast.Visitor {
  37. node, ok := n.(*ast.FuncDecl)
  38. if ok {
  39. num := 0
  40. for _, l := range node.Type.Params.List {
  41. for range l.Names {
  42. num++
  43. }
  44. }
  45. if num > w.total {
  46. w.onFailure(lint.Failure{
  47. Confidence: 1,
  48. Failure: fmt.Sprintf("maximum number of arguments per function exceeded; max %d but got %d", w.total, num),
  49. Node: node.Type,
  50. })
  51. return w
  52. }
  53. }
  54. return w
  55. }