github.com/elek/golangci-lint@v1.42.2-0.20211208090441-c05b7fcb3a9a/pkg/result/processors/base_rule.go (about)

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