forked from golangci/golangci-lint
/
goimports.go
82 lines (65 loc) · 1.94 KB
/
goimports.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package golinters
import (
"sync"
goimportsAPI "github.com/golangci/gofmt/goimports"
"github.com/pkg/errors"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/imports"
"github.com/golangci/golangci-lint/pkg/config"
"github.com/golangci/golangci-lint/pkg/golinters/goanalysis"
"github.com/golangci/golangci-lint/pkg/lint/linter"
)
const goimportsName = "goimports"
func NewGoimports(settings *config.GoImportsSettings) *goanalysis.Linter {
var mu sync.Mutex
var resIssues []goanalysis.Issue
analyzer := &analysis.Analyzer{
Name: goimportsName,
Doc: goanalysis.TheOnlyanalyzerDoc,
Run: goanalysis.DummyRun,
}
return goanalysis.NewLinter(
goimportsName,
"In addition to fixing imports, goimports also formats your code in the same style as gofmt.",
[]*analysis.Analyzer{analyzer},
nil,
).WithContextSetter(func(lintCtx *linter.Context) {
imports.LocalPrefix = settings.LocalPrefixes
analyzer.Run = func(pass *analysis.Pass) (interface{}, error) {
issues, err := runGoiImports(lintCtx, pass)
if err != nil {
return nil, err
}
if len(issues) == 0 {
return nil, nil
}
mu.Lock()
resIssues = append(resIssues, issues...)
mu.Unlock()
return nil, nil
}
}).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue {
return resIssues
}).WithLoadMode(goanalysis.LoadModeSyntax)
}
func runGoiImports(lintCtx *linter.Context, pass *analysis.Pass) ([]goanalysis.Issue, error) {
fileNames := getFileNames(pass)
var issues []goanalysis.Issue
for _, f := range fileNames {
diff, err := goimportsAPI.Run(f)
if err != nil { // TODO: skip
return nil, err
}
if diff == nil {
continue
}
is, err := extractIssuesFromPatch(string(diff), lintCtx, goimportsName)
if err != nil {
return nil, errors.Wrapf(err, "can't extract issues from gofmt diff output %q", string(diff))
}
for i := range is {
issues = append(issues, goanalysis.NewIssue(&is[i], pass))
}
}
return issues, nil
}