github.com/songshiyun/revive@v1.1.5-0.20220323112655-f8433a19b3c5/rule/max-public-structs.go (about)

     1  package rule
     2  
     3  import (
     4  	"go/ast"
     5  	"strings"
     6  
     7  	"github.com/songshiyun/revive/lint"
     8  )
     9  
    10  // MaxPublicStructsRule lints given else constructs.
    11  type MaxPublicStructsRule struct {
    12  	max int64
    13  }
    14  
    15  // Apply applies the rule to given file.
    16  func (r *MaxPublicStructsRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
    17  	if r.max < 1 {
    18  		checkNumberOfArguments(1, arguments, r.Name())
    19  
    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  		r.max = max
    25  	}
    26  
    27  	var failures []lint.Failure
    28  
    29  	fileAst := file.AST
    30  	walker := &lintMaxPublicStructs{
    31  		fileAst: fileAst,
    32  		onFailure: func(failure lint.Failure) {
    33  			failures = append(failures, failure)
    34  		},
    35  	}
    36  
    37  	ast.Walk(walker, fileAst)
    38  
    39  	if walker.current > r.max {
    40  		walker.onFailure(lint.Failure{
    41  			Failure:    "you have exceeded the maximum number of public struct declarations",
    42  			Confidence: 1,
    43  			Node:       fileAst,
    44  			Category:   "style",
    45  		})
    46  	}
    47  
    48  	return failures
    49  }
    50  
    51  // Name returns the rule name.
    52  func (r *MaxPublicStructsRule) Name() string {
    53  	return "max-public-structs"
    54  }
    55  
    56  type lintMaxPublicStructs struct {
    57  	current   int64
    58  	fileAst   *ast.File
    59  	onFailure func(lint.Failure)
    60  }
    61  
    62  func (w *lintMaxPublicStructs) Visit(n ast.Node) ast.Visitor {
    63  	switch v := n.(type) {
    64  	case *ast.TypeSpec:
    65  		name := v.Name.Name
    66  		first := string(name[0])
    67  		if strings.ToUpper(first) == first {
    68  			w.current++
    69  		}
    70  	}
    71  	return w
    72  }