Debian Codegraph @

depcheck/depcheck.go

raw symbols SCIP
1 /*
2 Copyright 2020 The Knative Authors
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 // Package depcheck defines a test utility for ensuring certain packages don't
18 // take on heavy dependencies.
19 package depcheck
20
21 import (
22 "fmt"
23 "sort"
24 "strings"
25 "testing"
26
27 "golang.org/x/tools/go/packages"
28 )
29
30 type node struct {
31 importpath string
32 consumers map[string]struct{}
33 }
34
35 type graph map[string]node
36
37 func (g graph) contains(name string) bool {
38 _, ok := g[name]
39 return ok
40 }
41
42 func (g graph) order() []string {
43 order := make(sort.StringSlice, 0, len(g))
44 for k := range g {
45 order = append(order, k)
46 }
47 order.Sort()
48 return order
49 }
50
51 // path constructs an examplary path that looks something like:
52 // knative.dev/pkg/apis/duck
53 // knative.dev/pkg/apis # Also: [knative.dev/pkg/kmeta knative.dev/pkg/tracker]
54 // k8s.io/api/core/v1
55 // See the failing example in the test file.
56 func (g graph) path(name string) []string {
57 n := g[name]
58 // Base case.
59 if len(n.consumers) == 0 {
60 return []string{name}
61 }
62 // Inductive step.
63 consumers := make(sort.StringSlice, 0, len(n.consumers))
64 for k := range n.consumers {
65 consumers = append(consumers, k)
66 }
67 consumers.Sort()
68 base := g.path(consumers[0])
69 if len(base) > 1 { // Don't decorate the first entry, which is always an entrypoint.
70 if len(consumers) > 1 {
71 // Attach other consumers to the last entry in base.
72 base = append(base[:len(base)-1], fmt.Sprintf("%s # Also: %v", consumers[0], consumers[1:]))
73 }
74 }
75 return append(base, name)
76 }
77
78 func buildGraph(importpath string, buildFlags ...string) (graph, error) {
79 g := make(graph, 1)
80 pkgs, err := packages.Load(&packages.Config{
81 Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedImports | packages.NeedDeps | packages.NeedModule,
82 BuildFlags: buildFlags,
83 }, importpath)
84 if err != nil {
85 return nil, err
86 }
87 packages.Visit(pkgs, func(pkg *packages.Package) bool {
88 g[pkg.PkgPath] = node{
89 importpath: pkg.PkgPath,
90 consumers: make(map[string]struct{}),
91 }
92 return pkg.Module != nil
93 }, func(pkg *packages.Package) {
94 for _, imp := range pkg.Imports {
95 if _, ok := g[imp.PkgPath]; ok {
96 g[imp.PkgPath].consumers[pkg.PkgPath] = struct{}{}
97 }
98 }
99 })
100 return g, nil
101 }
102
103 // CheckNoDependency checks that the given import paths (ip) does not
104 // depend (transitively) on certain banned imports.
105 func CheckNoDependency(ip string, banned []string, buildFlags ...string) error {
106 g, err := buildGraph(ip, buildFlags...)
107 if err != nil {
108 return fmt.Errorf("buildGraph(%q) = %w", ip, err)
109 }
110 for _, dip := range banned {
111 if g.contains(dip) {
112 return fmt.Errorf("%s depends on banned dependency %s\n%s", ip, dip,
113 strings.Join(g.path(dip), "\n"))
114 }
115 }
116 return nil
117 }
118
119 // AssertNoDependency checks that the given import paths (the keys) do not
120 // depend (transitively) on certain banned imports (the values)
121 func AssertNoDependency(t *testing.T, banned map[string][]string, buildFlags ...string) {
122 t.Helper()
123 for ip, banned := range banned {
124 t.Run(ip, func(t *testing.T) {
125 if err := CheckNoDependency(ip, banned, buildFlags...); err != nil {
126 t.Error("CheckNoDependency() =", err)
127 }
128 })
129 }
130 }
131
132 // CheckOnlyDependencies checks that the given import path only
133 // depends (transitively) on certain allowed imports.
134 // Note: while perhaps counterintuitive we allow the value to be a superset
135 // of the actual imports to that folks can use a constant that holds blessed
136 // import paths.
137 func CheckOnlyDependencies(ip string, allowed map[string]struct{}, buildFlags ...string) error {
138 g, err := buildGraph(ip, buildFlags...)
139 if err != nil {
140 return fmt.Errorf("buildGraph(%q) = %w", ip, err)
141 }
142 for _, name := range g.order() {
143 if _, ok := allowed[name]; !ok {
144 return fmt.Errorf("dependency %s of %s is not explicitly allowed\n%s", name, ip,
145 strings.Join(g.path(name), "\n"))
146 }
147 }
148 return nil
149 }
150
151 // AssertOnlyDependencies checks that the given import paths (the keys) only
152 // depend (transitively) on certain allowed imports (the values).
153 // Note: while perhaps counterintuitive we allow the value to be a superset
154 // of the actual imports to that folks can use a constant that holds blessed
155 // import paths.
156 func AssertOnlyDependencies(t *testing.T, allowed map[string][]string, buildFlags ...string) {
157 t.Helper()
158 for ip, allow := range allowed {
159 // Always include our own package in the set of allowed dependencies.
160 allowed := make(map[string]struct{}, len(allow)+1)
161 for _, x := range append(allow, ip) {
162 allowed[x] = struct{}{}
163 }
164 t.Run(ip, func(t *testing.T) {
165 if err := CheckOnlyDependencies(ip, allowed, buildFlags...); err != nil {
166 t.Error("CheckOnlyDependencies() =", err)
167 }
168 })
169 }
170 }