github.com/chenfeining/golangci-lint@v1.0.2-0.20230730162517-14c6c67868df/pkg/golinters/depguard.go (about)

     1  package golinters
     2  
     3  import (
     4  	"github.com/OpenPeeDeeP/depguard/v2"
     5  	"golang.org/x/tools/go/analysis"
     6  
     7  	"github.com/chenfeining/golangci-lint/pkg/config"
     8  	"github.com/chenfeining/golangci-lint/pkg/golinters/goanalysis"
     9  	"github.com/chenfeining/golangci-lint/pkg/lint/linter"
    10  )
    11  
    12  func NewDepguard(settings *config.DepGuardSettings) *goanalysis.Linter {
    13  	conf := depguard.LinterSettings{}
    14  
    15  	if settings != nil {
    16  		for s, rule := range settings.Rules {
    17  			list := &depguard.List{
    18  				Files: rule.Files,
    19  				Allow: rule.Allow,
    20  			}
    21  
    22  			// because of bug with Viper parsing (split on dot) we use a list of struct instead of a map.
    23  			// https://github.com/spf13/viper/issues/324
    24  			// https://github.com/chenfeining/golangci-lint/issues/3749#issuecomment-1492536630
    25  
    26  			deny := map[string]string{}
    27  			for _, r := range rule.Deny {
    28  				deny[r.Pkg] = r.Desc
    29  			}
    30  			list.Deny = deny
    31  
    32  			conf[s] = list
    33  		}
    34  	}
    35  
    36  	a := depguard.NewUncompiledAnalyzer(&conf)
    37  
    38  	return goanalysis.NewLinter(
    39  		a.Analyzer.Name,
    40  		a.Analyzer.Doc,
    41  		[]*analysis.Analyzer{a.Analyzer},
    42  		nil,
    43  	).WithContextSetter(func(lintCtx *linter.Context) {
    44  		err := a.Compile()
    45  		if err != nil {
    46  			lintCtx.Log.Errorf("create analyzer: %v", err)
    47  		}
    48  	}).WithLoadMode(goanalysis.LoadModeSyntax)
    49  }