-
Notifications
You must be signed in to change notification settings - Fork 0
/
importguard.go
86 lines (75 loc) · 1.71 KB
/
importguard.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
package importguard
import (
"encoding/json"
"go/ast"
"os"
"strconv"
"strings"
"sync"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
type config struct {
Allow map[string]map[string]struct{} `json:"allow"`
Deny map[string]map[string]struct{} `json:"deny"`
}
var (
conf config
once sync.Once
)
var Analyzer = &analysis.Analyzer{
Name: "importguard",
Doc: "importguard reports prohibited imports",
Run: run,
Requires: []*analysis.Analyzer{
inspect.Analyzer,
},
}
func parseConfig() error {
fp := os.Getenv("IMPORTGUARD_CONFIG")
if fp == "" {
return nil
}
b, err := os.ReadFile(fp)
if err != nil {
return err
}
return json.Unmarshal(b, &conf)
}
func run(pass *analysis.Pass) (any, error) {
once.Do(func() {
if err := parseConfig(); err != nil {
panic(err)
}
})
allowlist, aTarget := conf.Allow[pass.Pkg.Path()]
denylist, dTarget := conf.Deny[pass.Pkg.Path()]
if !aTarget && !dTarget {
return nil, nil
}
inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
nodeFilter := []ast.Node{
(*ast.ImportSpec)(nil),
}
inspect.Preorder(nodeFilter, func(n ast.Node) {
s := n.(*ast.ImportSpec)
path, _ := strconv.Unquote(s.Path.Value)
if _, exists := allowlist[path]; exists {
return
}
if _, exists := denylist[path]; exists || !isStandardImportPath(path) {
pass.Reportf(s.Pos(), "prohibited import package: %s", s.Path.Value)
}
})
return nil, nil
}
// copied from https://pkg.go.dev/cmd/go/internal/search#IsStandardImportPath
func isStandardImportPath(path string) bool {
i := strings.Index(path, "/")
if i < 0 {
i = len(path)
}
elem := path[:i]
return !strings.Contains(elem, ".")
}