1
0
mirror of https://github.com/mgechev/revive.git synced 2025-07-07 00:35:38 +02:00
Files
revive/rule/max_public_structs.go

93 lines
1.9 KiB
Go
Raw Normal View History

2018-02-02 13:32:03 -05:00
package rule
import (
"errors"
"fmt"
2018-02-02 13:32:03 -05:00
"go/ast"
"strings"
"github.com/mgechev/revive/lint"
)
2024-12-01 17:44:41 +02:00
// MaxPublicStructsRule lints the number of public structs in a file.
2021-10-17 20:34:48 +02:00
type MaxPublicStructsRule struct {
max int64
}
2018-02-02 13:32:03 -05:00
const defaultMaxPublicStructs = 5
// Configure validates the rule configuration, and configures the rule accordingly.
//
// Configuration implements the [lint.ConfigurableRule] interface.
func (r *MaxPublicStructsRule) Configure(arguments lint.Arguments) error {
2024-10-01 12:14:02 +02:00
if len(arguments) < 1 {
r.max = defaultMaxPublicStructs
return nil
2024-10-01 12:14:02 +02:00
}
err := checkNumberOfArguments(1, arguments, r.Name())
if err != nil {
return err
}
2024-10-01 12:14:02 +02:00
maxStructs, ok := arguments[0].(int64) // Alt. non panicking version
if !ok {
return errors.New(`invalid value passed as argument number to the "max-public-structs" rule`)
2024-10-01 12:14:02 +02:00
}
r.max = maxStructs
return nil
2022-04-10 09:06:59 +02:00
}
// Apply applies the rule to given file.
func (r *MaxPublicStructsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
var failures []lint.Failure
if r.max < 1 {
return failures
}
2018-02-02 13:32:03 -05:00
fileAst := file.AST
2022-04-10 09:06:59 +02:00
2018-02-02 13:32:03 -05: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 13:32:03 -05:00
walker.onFailure(lint.Failure{
Failure: fmt.Sprintf("you have exceeded the maximum number (%d) of public struct declarations", r.max),
2018-02-02 13:32:03 -05:00
Confidence: 1,
Node: fileAst,
Category: lint.FailureCategoryStyle,
2018-02-02 13:32:03 -05:00
})
}
return failures
}
// Name returns the rule name.
2022-04-10 11:55:13 +02:00
func (*MaxPublicStructsRule) Name() string {
2018-02-02 13:32:03 -05:00
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 {
if v, ok := n.(*ast.TypeSpec); ok {
2018-02-02 13:32:03 -05:00
name := v.Name.Name
first := string(name[0])
if strings.ToUpper(first) == first {
w.current++
}
}
return w
}