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

     1  package rule
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/mgechev/revive/lint"
     8  )
     9  
    10  // ForbidImportsRule finds unwanted imports
    11  type ForbidImportsRule struct{}
    12  
    13  // Name returns the rule name
    14  func (f *ForbidImportsRule) Name() string {
    15  	return "forbidden-imports"
    16  }
    17  
    18  // Apply applies the rule to given file.
    19  func (f *ForbidImportsRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
    20  	var failures []lint.Failure
    21  
    22  	const (
    23  		message  = "forbidden import: %v"
    24  		category = "import"
    25  	)
    26  
    27  	forbiddenImports := make([]string, len(arguments))
    28  	if len(arguments) >= 1 {
    29  		for idx, arg := range arguments {
    30  			forbiddenImports[idx] = arg.(string)
    31  		}
    32  	}
    33  
    34  	for _, forbiddenImport := range forbiddenImports {
    35  		for _, imp := range file.AST.Imports {
    36  			importName := strings.ReplaceAll(imp.Path.Value, "\"", "")
    37  			if strings.EqualFold(importName, forbiddenImport) {
    38  				failures = append(failures, lint.Failure{Failure: fmt.Sprintf(message, importName), Category: category, Node: imp, Confidence: 1})
    39  			}
    40  		}
    41  
    42  	}
    43  
    44  	return failures
    45  }