-
Notifications
You must be signed in to change notification settings - Fork 16
/
depguard.go
95 lines (85 loc) · 2.66 KB
/
depguard.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
83
84
85
86
87
88
89
90
91
92
93
94
95
package depguard
import (
"fmt"
"go/ast"
"path/filepath"
"strings"
"golang.org/x/tools/go/analysis"
)
// NewAnalyzer creates a new analyzer from the settings passed in.
// This can fail if the passed in LinterSettings does not compile.
// Use NewUncompiledAnalyzer if you need control when the compile happens.
func NewAnalyzer(settings *LinterSettings) (*analysis.Analyzer, error) {
s, err := settings.compile()
if err != nil {
return nil, err
}
analyzer := newAnalyzer(s.run)
return analyzer, nil
}
type UncompiledAnalyzer struct {
Analyzer *analysis.Analyzer
settings *LinterSettings
}
// NewUncompiledAnalyzer creates a new analyzer from the settings passed in.
// This can never error unlike NewAnalyzer.
// It is advised to call the Compile method on the returned Analyzer before running.
func NewUncompiledAnalyzer(settings *LinterSettings) *UncompiledAnalyzer {
return &UncompiledAnalyzer{
Analyzer: newAnalyzer(settings.run),
settings: settings,
}
}
// Compile the settings ahead of time so each subsuquent run of the analyzer doesn't
// need to do this work.
func (ua *UncompiledAnalyzer) Compile() error {
s, err := ua.settings.compile()
if err != nil {
return err
}
ua.Analyzer.Run = s.run
return nil
}
func (settings LinterSettings) run(pass *analysis.Pass) (interface{}, error) {
s, err := settings.compile()
if err != nil {
return nil, err
}
return s.run(pass)
}
func newAnalyzer(run func(*analysis.Pass) (interface{}, error)) *analysis.Analyzer {
return &analysis.Analyzer{
Name: "depguard",
Doc: "Go linter that checks if package imports are in a list of acceptable packages",
URL: "https://github.com/OpenPeeDeeP/depguard",
Run: run,
RunDespiteErrors: false,
}
}
func (s linterSettings) run(pass *analysis.Pass) (interface{}, error) {
for _, file := range pass.Files {
// For Windows need to replace separator with '/'
fileName := filepath.ToSlash(pass.Fset.Position(file.Pos()).Filename)
lists := s.whichLists(fileName)
for _, imp := range file.Imports {
for _, l := range lists {
if allowed, sugg := l.importAllowed(rawBasicLit(imp.Path)); !allowed {
diag := analysis.Diagnostic{
Pos: imp.Pos(),
End: imp.End(),
Message: fmt.Sprintf("import '%s' is not allowed from list '%s'", rawBasicLit(imp.Path), l.name),
}
if sugg != "" {
diag.Message = fmt.Sprintf("%s: %s", diag.Message, sugg)
diag.SuggestedFixes = append(diag.SuggestedFixes, analysis.SuggestedFix{Message: sugg})
}
pass.Report(diag)
}
}
}
}
return nil, nil
}
func rawBasicLit(lit *ast.BasicLit) string {
return strings.Trim(lit.Value, "\"")
}