github.com/songshiyun/revive@v1.1.5-0.20220323112655-f8433a19b3c5/rule/imports-blacklist.go (about)

     1  package rule
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/songshiyun/revive/lint"
     7  )
     8  
     9  // ImportsBlacklistRule lints given else constructs.
    10  type ImportsBlacklistRule struct {
    11  	blacklist map[string]bool
    12  }
    13  
    14  // Apply applies the rule to given file.
    15  func (r *ImportsBlacklistRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
    16  	var failures []lint.Failure
    17  
    18  	if file.IsTest() {
    19  		return failures // skip, test file
    20  	}
    21  
    22  	if r.blacklist == nil {
    23  		r.blacklist = make(map[string]bool, len(arguments))
    24  
    25  		for _, arg := range arguments {
    26  			argStr, ok := arg.(string)
    27  			if !ok {
    28  				panic(fmt.Sprintf("Invalid argument to the imports-blacklist rule. Expecting a string, got %T", arg))
    29  			}
    30  			// we add quotes if not present, because when parsed, the value of the AST node, will be quoted
    31  			if len(argStr) > 2 && argStr[0] != '"' && argStr[len(argStr)-1] != '"' {
    32  				argStr = fmt.Sprintf(`%q`, argStr)
    33  			}
    34  			r.blacklist[argStr] = true
    35  		}
    36  	}
    37  
    38  	for _, is := range file.AST.Imports {
    39  		path := is.Path
    40  		if path != nil && r.blacklist[path.Value] {
    41  			failures = append(failures, lint.Failure{
    42  				Confidence: 1,
    43  				Failure:    "should not use the following blacklisted import: " + path.Value,
    44  				Node:       is,
    45  				Category:   "imports",
    46  			})
    47  		}
    48  	}
    49  
    50  	return failures
    51  }
    52  
    53  // Name returns the rule name.
    54  func (r *ImportsBlacklistRule) Name() string {
    55  	return "imports-blacklist"
    56  }