This repository has been archived by the owner on Jun 3, 2023. It is now read-only.
forked from OpenPeeDeeP/depguard
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
depguard.go
58 lines (52 loc) · 1.56 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
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
func NewAnalyzer(settings *LinterSettings) (*analysis.Analyzer, error) {
s, err := settings.Compile()
if err != nil {
return nil, err
}
analyzer := NewCoreAnalyzer(s)
return analyzer, nil
}
func NewCoreAnalyzer(settings CoreSettings) *analysis.Analyzer {
return &analysis.Analyzer{
Name: "depguard",
Doc: "Go linter that checks if package imports are in a list of acceptable packages",
Run: settings.Run,
RunDespiteErrors: false,
}
}
func (s CoreSettings) 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, "\"")
}