/
flags.go
308 lines (258 loc) · 8.61 KB
/
flags.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package graph
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"path"
"strings"
"github.com/spf13/cobra"
"k8s.io/klog"
"github.com/gonum/graph/simple"
)
// GraphOptions contains values necessary to create a dependency graph.
type GraphOptions struct {
// Packages is the caculated list of traversed go packages to use to create the graph
Packages *PackageList
// Roots is a list of go-import paths containing the total set of traversed
// packages, from the given set of Entrypoints.
Roots []string
// Excludes are package go-import paths to ignore while traversing a directory structure
Excludes []string
// Filters are package go-import paths. Any package paths nested under these are truncated.
Filters []string
// BuildTags match files containing conditional compilation flags to be included during package traversal
BuildTags []string
}
func (o *GraphOptions) Complete() error {
return nil
}
func (o *GraphOptions) Validate() error {
if o.Packages == nil || len(o.Packages.Packages) == 0 {
return errors.New("a list of Go Packages is required in order to build the graph")
}
return nil
}
// BuildGraph receives a list of Go packages and constructs a dependency graph from it.\
// Each package's ImportPath and non-transitive (immediate) imports are
// filtered and aggregated. A package is filtered based on whether its ImportPath
// matches an accepted pattern defined in the set of validPackages.
// Any core library dependencies (fmt, strings, etc.) are not added to the graph.
// Any packages whose import path is contained within a list of "excludes" are not added to the graph.
// Returns a directed graph and a map of package import paths to node ids, or an error.
func (o *GraphOptions) BuildGraph() (*MutableDirectedGraph, error) {
g := NewMutableDirectedGraph(o.Roots)
// contains the subset of packages from the set of given packages (and their immediate dependencies)
// that will actually be included in our graph - any packages in the excludes slice, or that do not
// do not match the baseRepoRegex pattern will be filtered out from this collection.
filteredPackages := []Package{}
// add nodes to graph
for _, pkg := range o.Packages.Packages {
if isExcludedPath(pkg.ImportPath, o.Excludes) {
continue
}
if !isValidPackagePath(pkg.ImportPath) {
continue
}
n := &Node{
Id: g.NewNodeID(),
UniqueName: pkg.ImportPath,
}
err := g.AddNode(n)
if err != nil {
return nil, err
}
filteredPackages = append(filteredPackages, pkg)
}
// add edges
for _, pkg := range filteredPackages {
from, exists := g.NodeByName(pkg.ImportPath)
if !exists {
return nil, fmt.Errorf("expected node for package %q was not found in graph", pkg.ImportPath)
}
for _, dependency := range append(pkg.Imports, pkg.TestImports...) {
if isExcludedPath(dependency, o.Excludes) {
continue
}
if !isValidPackagePath(dependency) {
continue
}
to, exists := g.NodeByName(dependency)
if !exists {
// if a package imports a dependency that we did not visit
// while traversing the code tree, ignore it, as it is not
// required for the root repository to build.
klog.V(1).Infof("Skipping unvisited (missing) dependency %q, which is imported by package %q", dependency, pkg.ImportPath)
continue
}
if g.HasEdgeFromTo(from, to) {
continue
}
g.SetEdge(simple.Edge{F: from, T: to})
}
}
// filter graph if any filters are specified
if len(o.Filters) > 0 {
var err error
g, err = FilterPackages(g, o.Filters)
if err != nil {
return nil, err
}
}
g.PruneOrphans()
return g, nil
}
type GraphFlags struct {
Filter string
Exclude string
Openshift bool
RepoImportPath string
Entrypoints []string
BuildTags []string
}
// calculate roots receives a set of entrypoints and traverses through
// the directory tree, returning a list of all reachable go packages.
// Excludes the vendor tree.
// Returns the list of calculated import paths or an error.
func (o *GraphFlags) calculateRoots(excludes []string) ([]string, error) {
packages, err := getPackageMetadata(
o.Entrypoints,
excludes,
o.BuildTags,
)
if err != nil {
return nil, err
}
roots := []string{}
for _, pkg := range packages.Packages {
roots = append(roots, pkg.ImportPath)
}
return roots, nil
}
func (o *GraphFlags) ToOptions(out, errout io.Writer) (*GraphOptions, error) {
opts := &GraphOptions{
BuildTags: o.BuildTags,
}
if len(o.RepoImportPath) == 0 {
return nil, errors.New("the go-import path for the repository must be specified via --root")
}
if len(o.Entrypoints) == 0 {
return nil, errors.New("at least one entrypoint path must be provided")
}
if o.Openshift && (len(o.Exclude) > 0 || len(o.Filter) > 0) {
return nil, errors.New("--exclude or --filter are mutually exclusive with --openshift")
}
// sanitize user-provided entrypoints
o.Entrypoints = ensureEntrypointPrefix(o.Entrypoints, o.RepoImportPath)
// set openshift defaults
if o.Openshift {
opts.Excludes = getOpenShiftExcludes()
filters, err := getOpenShiftFilters()
if err != nil {
return nil, err
}
opts.Filters = filters
} else {
if len(o.Exclude) > 0 {
f, err := ioutil.ReadFile(o.Exclude)
if err != nil {
return nil, err
}
err = json.Unmarshal(f, &opts.Excludes)
if err != nil {
return nil, err
}
}
if len(o.Filter) > 0 {
f, err := ioutil.ReadFile(o.Filter)
if err != nil {
return nil, err
}
err = json.Unmarshal(f, &opts.Filters)
if err != nil {
return nil, err
}
}
}
// calculate go package info from given set of entrypoints
packages, err := getPackageMetadata(
ensureVendorEntrypoint(o.Entrypoints, o.RepoImportPath),
opts.Excludes,
opts.BuildTags,
)
if err != nil {
return nil, err
}
opts.Packages = packages
// calculate non-vendor trees
roots, err := o.calculateRoots(opts.Excludes)
if err != nil {
return nil, err
}
opts.Roots = roots
return opts, nil
}
func (o *GraphFlags) AddFlags(cmd *cobra.Command) {
cmd.Flags().BoolVar(&o.Openshift, "openshift", o.Openshift, "generate and use OpenShift-specific lists of excluded packages and filters.")
cmd.Flags().StringVar(&o.RepoImportPath, "root", o.RepoImportPath, "Go import-path of repository to analyze (e.g. github.com/openshift/origin)")
cmd.Flags().StringSliceVar(&o.Entrypoints, "entry", o.Entrypoints, "filepaths for packages within the specified --root relative to the repo's import path (e.g. ./cmd/...). Paths ending in an ellipsis (...) are traversed recursively.")
cmd.Flags().StringSliceVar(&o.BuildTags, "tag", o.BuildTags, "list of build tags (not matching target system) of files to include during Go package traversal.")
cmd.Flags().StringVarP(&o.Exclude, "exclude", "e", "", "optional path to json file containing a list of import-paths of packages within the specified repository to recursively exclude.")
cmd.Flags().StringVarP(&o.Filter, "filter", "c", "", "optional path to json file containing a list of import-paths of packages to collapse sub-packages into.")
}
func isExcludedPath(path string, excludes []string) bool {
for _, exclude := range excludes {
if strings.HasPrefix(path, exclude) {
return true
}
}
return false
}
// ensureEntrypointPrefix receives a list of paths and ensures
// that each path is prefixed by the repo's go-import path:
// ["./cmd"] -> ["github.com/openshift/origin/cmd"]
func ensureEntrypointPrefix(entrypoints []string, prefix string) []string {
for idx, entry := range entrypoints {
if strings.HasPrefix(entry, prefix) {
continue
}
entrypoints[idx] = path.Join(prefix, entry)
}
return entrypoints
}
// ensureVendorEntrypoint receives a list of paths and ensures that
// at least one of those paths is a go-import path to the repo's vendor directory
func ensureVendorEntrypoint(entrypoints []string, prefix string) []string {
hasVendor := false
for _, entry := range entrypoints {
if strings.HasSuffix(path.Clean(entry), "/vendor") {
hasVendor = true
break
}
}
if !hasVendor {
vendor := ensureEntrypointPrefix([]string{"vendor"}, prefix)
vendor = ensureEntrypointEllipsis(vendor)
entrypoints = append(entrypoints, vendor[0])
}
return entrypoints
}
// ensureEntrypointEllipsis receives a list of paths
// and ensures that each path ends in an ellipsis (...).
func ensureEntrypointEllipsis(entypoints []string) []string {
parsedRoots := []string{}
for _, entry := range entypoints {
if strings.HasSuffix(entry, "...") {
parsedRoots = append(parsedRoots, entry)
continue
}
slash := ""
if string(entry[len(entry)-1]) != "/" {
slash = "/"
}
entry = strings.Join([]string{entry, slash, "..."}, "")
parsedRoots = append(parsedRoots, entry)
}
return parsedRoots
}