-
Notifications
You must be signed in to change notification settings - Fork 6
/
analyzer.go
115 lines (101 loc) · 2.52 KB
/
analyzer.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package layer
import (
"encoding/json"
"strconv"
"strings"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
)
/**
* define layer graph by JSON array.
* For example, the sample graph of "The Clean Architecture" is below:
* https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html
* [
* "external_interfaces",
* "web",
* "devices",
* "db",
* "ui",
* [
* "controllers",
* "gateways",
* "presenters",
* [
* "use_cases",
* [
* "entity"
* ]
* ]
* ]
* ]
*/
var jsonString = `[ "external","db","ui", [ "controllers", [ "usecases", [ "entity" ] ] ] ]` // -jsonlayer flag
func init() {
Analyzer.Flags.StringVar(&jsonString, "jsonlayer", jsonString, "jsonlayer defines layer hierarchy by JSON array")
}
// Analyzer confirms whether the packages follow to the layer structure.
var Analyzer = &analysis.Analyzer{
Name: "layer",
Doc: Doc,
Run: run,
Requires: []*analysis.Analyzer{
inspect.Analyzer,
},
}
// Doc defines analysis messages. this message is shown by "layer help" command.
const Doc = "layer checks whether there are dependencies that illegal cross-border the layer structure. The layer structure is defined as a JSON array using the -jsonlayer option."
func run(pass *analysis.Pass) (interface{}, error) {
l := &Layer{}
if err := json.Unmarshal([]byte(jsonString), l); err != nil {
return nil, err
}
currentPackage := pass.Pkg.Path()
found:
for ; l.Inside != nil; l = l.Inside {
for _, ln := range l.Packages {
if strings.Contains(currentPackage, ln) {
break found
}
}
}
if l.Inside == nil || l.Inside.Inside == nil {
return nil, nil
}
il := l.Inside.Inside
for _, f := range pass.Files {
if strings.HasSuffix(pass.Fset.File(f.Pos()).Name(), "_test.go") {
continue
}
for _, i := range f.Imports {
path, err := strconv.Unquote(i.Path.Value)
if err != nil {
return nil, err
}
// TODO: ignore standard packages.
// memo: https://github.com/golang/go/blob/6cba4dbf80012c272cb04bd878dfba251d9bb05c/src/cmd/go/internal/modload/build.go#L30
if invalid(il, path) {
pass.Reportf(i.Pos(), "%s must not import %s", currentPackage, path)
}
}
}
return nil, nil
}
func invalid(l *Layer, path string) bool {
for {
if include(l, path) {
return true
}
if l.Inside == nil {
return false
}
l = l.Inside
}
}
func include(l *Layer, name string) bool {
for _, p := range l.Packages {
if strings.Contains(name, p) {
return true
}
}
return false
}