github.com/Johnny2210/revive@v1.0.8-0.20210625134200-febf37ccd0f5/rule/imports-blacklist.go (about)

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