github.com/chenfeining/golangci-lint@v1.0.2-0.20230730162517-14c6c67868df/pkg/golinters/gomoddirectives.go (about) 1 package golinters 2 3 import ( 4 "sync" 5 6 "github.com/ldez/gomoddirectives" 7 "golang.org/x/tools/go/analysis" 8 9 "github.com/chenfeining/golangci-lint/pkg/config" 10 "github.com/chenfeining/golangci-lint/pkg/golinters/goanalysis" 11 "github.com/chenfeining/golangci-lint/pkg/lint/linter" 12 "github.com/chenfeining/golangci-lint/pkg/result" 13 ) 14 15 const goModDirectivesName = "gomoddirectives" 16 17 // NewGoModDirectives returns a new gomoddirectives linter. 18 func NewGoModDirectives(settings *config.GoModDirectivesSettings) *goanalysis.Linter { 19 var issues []goanalysis.Issue 20 var once sync.Once 21 22 var opts gomoddirectives.Options 23 if settings != nil { 24 opts.ReplaceAllowLocal = settings.ReplaceLocal 25 opts.ReplaceAllowList = settings.ReplaceAllowList 26 opts.RetractAllowNoExplanation = settings.RetractAllowNoExplanation 27 opts.ExcludeForbidden = settings.ExcludeForbidden 28 } 29 30 analyzer := &analysis.Analyzer{ 31 Name: goanalysis.TheOnlyAnalyzerName, 32 Doc: goanalysis.TheOnlyanalyzerDoc, 33 Run: goanalysis.DummyRun, 34 } 35 36 return goanalysis.NewLinter( 37 goModDirectivesName, 38 "Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod.", 39 []*analysis.Analyzer{analyzer}, 40 nil, 41 ).WithContextSetter(func(lintCtx *linter.Context) { 42 analyzer.Run = func(pass *analysis.Pass) (any, error) { 43 once.Do(func() { 44 results, err := gomoddirectives.Analyze(opts) 45 if err != nil { 46 lintCtx.Log.Warnf("running %s failed: %s: "+ 47 "if you are not using go modules it is suggested to disable this linter", goModDirectivesName, err) 48 return 49 } 50 51 for _, p := range results { 52 issues = append(issues, goanalysis.NewIssue(&result.Issue{ 53 FromLinter: goModDirectivesName, 54 Pos: p.Start, 55 Text: p.Reason, 56 }, pass)) 57 } 58 }) 59 60 return nil, nil 61 } 62 }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { 63 return issues 64 }).WithLoadMode(goanalysis.LoadModeSyntax) 65 }