github.com/vanstinator/golangci-lint@v0.0.0-20240223191551-cc572f00d9d1/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/vanstinator/golangci-lint/pkg/config"
     8  	"github.com/vanstinator/golangci-lint/pkg/golinters/goanalysis"
     9  	"github.com/vanstinator/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  				ListMode: rule.ListMode,
    19  				Files:    rule.Files,
    20  				Allow:    rule.Allow,
    21  			}
    22  
    23  			// because of bug with Viper parsing (split on dot) we use a list of struct instead of a map.
    24  			// https://github.com/spf13/viper/issues/324
    25  			// https://github.com/vanstinator/golangci-lint/issues/3749#issuecomment-1492536630
    26  
    27  			deny := map[string]string{}
    28  			for _, r := range rule.Deny {
    29  				deny[r.Pkg] = r.Desc
    30  			}
    31  			list.Deny = deny
    32  
    33  			conf[s] = list
    34  		}
    35  	}
    36  
    37  	a := depguard.NewUncompiledAnalyzer(&conf)
    38  
    39  	return goanalysis.NewLinter(
    40  		a.Analyzer.Name,
    41  		a.Analyzer.Doc,
    42  		[]*analysis.Analyzer{a.Analyzer},
    43  		nil,
    44  	).WithContextSetter(func(lintCtx *linter.Context) {
    45  		err := a.Compile()
    46  		if err != nil {
    47  			lintCtx.Log.Errorf("create analyzer: %v", err)
    48  		}
    49  	}).WithLoadMode(goanalysis.LoadModeSyntax)
    50  }