1
0
mirror of https://github.com/mgechev/revive.git synced 2024-11-30 08:57:07 +02:00
revive/rule/max-public-structs.go

82 lines
1.6 KiB
Go
Raw Normal View History

2018-02-02 20:32:03 +02:00
package rule
import (
"go/ast"
"strings"
2022-04-10 09:06:59 +02:00
"sync"
2018-02-02 20:32:03 +02:00
"github.com/mgechev/revive/lint"
)
// MaxPublicStructsRule lints given else constructs.
2021-10-17 20:34:48 +02:00
type MaxPublicStructsRule struct {
max int64
2022-04-10 09:06:59 +02:00
sync.Mutex
2021-10-17 20:34:48 +02:00
}
2018-02-02 20:32:03 +02:00
2022-04-10 09:06:59 +02:00
func (r *MaxPublicStructsRule) configure(arguments lint.Arguments) {
r.Lock()
2021-10-17 20:34:48 +02:00
if r.max < 1 {
checkNumberOfArguments(1, arguments, r.Name())
2021-10-17 20:34:48 +02:00
max, ok := arguments[0].(int64) // Alt. non panicking version
if !ok {
panic(`invalid value passed as argument number to the "max-public-structs" rule`)
}
r.max = max
}
2022-04-10 09:06:59 +02:00
r.Unlock()
}
// Apply applies the rule to given file.
func (r *MaxPublicStructsRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
r.configure(arguments)
2018-02-02 20:32:03 +02:00
var failures []lint.Failure
2018-02-02 20:32:03 +02:00
fileAst := file.AST
2022-04-10 09:06:59 +02:00
2018-02-02 20:32:03 +02:00
walker := &lintMaxPublicStructs{
fileAst: fileAst,
onFailure: func(failure lint.Failure) {
failures = append(failures, failure)
},
}
ast.Walk(walker, fileAst)
2021-10-17 20:34:48 +02:00
if walker.current > r.max {
2018-02-02 20:32:03 +02:00
walker.onFailure(lint.Failure{
Failure: "you have exceeded the maximum number of public struct declarations",
Confidence: 1,
Node: fileAst,
Category: "style",
})
}
return failures
}
// Name returns the rule name.
func (r *MaxPublicStructsRule) Name() string {
return "max-public-structs"
}
type lintMaxPublicStructs struct {
current int64
fileAst *ast.File
onFailure func(lint.Failure)
}
func (w *lintMaxPublicStructs) Visit(n ast.Node) ast.Visitor {
switch v := n.(type) {
case *ast.TypeSpec:
name := v.Name.Name
first := string(name[0])
if strings.ToUpper(first) == first {
w.current++
}
}
return w
}