github.com/chenfeining/golangci-lint@v1.0.2-0.20230730162517-14c6c67868df/pkg/result/processors/base_rule.go (about)

     1  package processors
     2  
     3  import (
     4  	"regexp"
     5  
     6  	"github.com/chenfeining/golangci-lint/pkg/fsutils"
     7  	"github.com/chenfeining/golangci-lint/pkg/logutils"
     8  	"github.com/chenfeining/golangci-lint/pkg/result"
     9  )
    10  
    11  type BaseRule struct {
    12  	Text       string
    13  	Source     string
    14  	Path       string
    15  	PathExcept string
    16  	Linters    []string
    17  }
    18  
    19  type baseRule struct {
    20  	text       *regexp.Regexp
    21  	source     *regexp.Regexp
    22  	path       *regexp.Regexp
    23  	pathExcept *regexp.Regexp
    24  	linters    []string
    25  }
    26  
    27  func (r *baseRule) isEmpty() bool {
    28  	return r.text == nil && r.source == nil && r.path == nil && r.pathExcept == nil && len(r.linters) == 0
    29  }
    30  
    31  func (r *baseRule) match(issue *result.Issue, files *fsutils.Files, log logutils.Log) bool {
    32  	if r.isEmpty() {
    33  		return false
    34  	}
    35  	if r.text != nil && !r.text.MatchString(issue.Text) {
    36  		return false
    37  	}
    38  	if r.path != nil && !r.path.MatchString(files.WithPathPrefix(issue.FilePath())) {
    39  		return false
    40  	}
    41  	if r.pathExcept != nil && r.pathExcept.MatchString(issue.FilePath()) {
    42  		return false
    43  	}
    44  	if len(r.linters) != 0 && !r.matchLinter(issue) {
    45  		return false
    46  	}
    47  
    48  	// the most heavyweight checking last
    49  	if r.source != nil && !r.matchSource(issue, files.LineCache, log) {
    50  		return false
    51  	}
    52  
    53  	return true
    54  }
    55  
    56  func (r *baseRule) matchLinter(issue *result.Issue) bool {
    57  	for _, linter := range r.linters {
    58  		if linter == issue.FromLinter {
    59  			return true
    60  		}
    61  	}
    62  
    63  	return false
    64  }
    65  
    66  func (r *baseRule) matchSource(issue *result.Issue, lineCache *fsutils.LineCache, log logutils.Log) bool { //nolint:interfacer
    67  	sourceLine, errSourceLine := lineCache.GetLine(issue.FilePath(), issue.Line())
    68  	if errSourceLine != nil {
    69  		log.Warnf("Failed to get line %s:%d from line cache: %s", issue.FilePath(), issue.Line(), errSourceLine)
    70  		return false // can't properly match
    71  	}
    72  
    73  	return r.source.MatchString(sourceLine)
    74  }