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