|
| 1 | +package golinters |
| 2 | + |
| 3 | +import ( |
| 4 | + "sync" |
| 5 | + |
| 6 | + "github.com/daixiang0/gci/pkg/gci" |
| 7 | + "github.com/pkg/errors" |
| 8 | + "golang.org/x/tools/go/analysis" |
| 9 | + |
| 10 | + "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" |
| 11 | + "github.com/golangci/golangci-lint/pkg/lint/linter" |
| 12 | +) |
| 13 | + |
| 14 | +const gciName = "gci" |
| 15 | + |
| 16 | +func NewGci() *goanalysis.Linter { |
| 17 | + var mu sync.Mutex |
| 18 | + var resIssues []goanalysis.Issue |
| 19 | + |
| 20 | + analyzer := &analysis.Analyzer{ |
| 21 | + Name: gciName, |
| 22 | + Doc: goanalysis.TheOnlyanalyzerDoc, |
| 23 | + } |
| 24 | + return goanalysis.NewLinter( |
| 25 | + gciName, |
| 26 | + "Gci control golang package import order and make it always deterministic.", |
| 27 | + []*analysis.Analyzer{analyzer}, |
| 28 | + nil, |
| 29 | + ).WithContextSetter(func(lintCtx *linter.Context) { |
| 30 | + localFlag := lintCtx.Settings().Gci.LocalPrefixes |
| 31 | + goimportsFlag := lintCtx.Settings().Goimports.LocalPrefixes |
| 32 | + if localFlag == "" && goimportsFlag != "" { |
| 33 | + localFlag = goimportsFlag |
| 34 | + } |
| 35 | + |
| 36 | + analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { |
| 37 | + var fileNames []string |
| 38 | + for _, f := range pass.Files { |
| 39 | + pos := pass.Fset.PositionFor(f.Pos(), false) |
| 40 | + fileNames = append(fileNames, pos.Filename) |
| 41 | + } |
| 42 | + |
| 43 | + var issues []goanalysis.Issue |
| 44 | + |
| 45 | + for _, f := range fileNames { |
| 46 | + diff, err := gci.Run(f, &gci.FlagSet{LocalFlag: localFlag}) |
| 47 | + if err != nil { |
| 48 | + return nil, err |
| 49 | + } |
| 50 | + if diff == nil { |
| 51 | + continue |
| 52 | + } |
| 53 | + |
| 54 | + is, err := extractIssuesFromPatch(string(diff), lintCtx.Log, lintCtx, gciName) |
| 55 | + if err != nil { |
| 56 | + return nil, errors.Wrapf(err, "can't extract issues from gci diff output %q", string(diff)) |
| 57 | + } |
| 58 | + |
| 59 | + for i := range is { |
| 60 | + issues = append(issues, goanalysis.NewIssue(&is[i], pass)) |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + if len(issues) == 0 { |
| 65 | + return nil, nil |
| 66 | + } |
| 67 | + |
| 68 | + mu.Lock() |
| 69 | + resIssues = append(resIssues, issues...) |
| 70 | + mu.Unlock() |
| 71 | + |
| 72 | + return nil, nil |
| 73 | + } |
| 74 | + }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { |
| 75 | + return resIssues |
| 76 | + }).WithLoadMode(goanalysis.LoadModeSyntax) |
| 77 | +} |
0 commit comments