-
Notifications
You must be signed in to change notification settings - Fork 90
/
main.go
277 lines (237 loc) · 6.84 KB
/
main.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
package main
import (
"flag"
"fmt"
"go/build"
"log"
"os"
"sort"
"strings"
)
var (
pkgs map[string]*build.Package
erroredPkgs map[string]bool
ids map[string]string
ignored = map[string]bool{
"C": true,
}
ignoredPrefixes []string
onlyPrefixes []string
ignoreStdlib = flag.Bool("nostdlib", false, "ignore packages in the Go standard library")
ignoreVendor = flag.Bool("novendor", false, "ignore packages in the vendor directory")
stopOnError = flag.Bool("stoponerror", true, "stop on package import errors")
withGoroot = flag.Bool("withgoroot", false, "show dependencies of packages in the Go standard library")
ignorePrefixes = flag.String("ignoreprefixes", "", "a comma-separated list of prefixes to ignore")
ignorePackages = flag.String("ignorepackages", "", "a comma-separated list of packages to ignore")
onlyPrefix = flag.String("onlyprefixes", "", "a comma-separated list of prefixes to include")
tagList = flag.String("tags", "", "a comma-separated list of build tags to consider satisfied during the build")
horizontal = flag.Bool("horizontal", false, "lay out the dependency graph horizontally instead of vertically")
withTests = flag.Bool("withtests", false, "include test packages")
maxLevel = flag.Int("maxlevel", 256, "max level of go dependency graph")
buildTags []string
buildContext = build.Default
)
func init() {
flag.BoolVar(ignoreStdlib, "s", false, "(alias for -nostdlib) ignore packages in the Go standard library")
flag.StringVar(ignorePrefixes, "p", "", "(alias for -ignoreprefixes) a comma-separated list of prefixes to ignore")
flag.StringVar(ignorePackages, "i", "", "(alias for -ignorepackages) a comma-separated list of packages to ignore")
flag.StringVar(onlyPrefix, "o", "", "(alias for -onlyprefixes) a comma-separated list of prefixes to include")
flag.BoolVar(withTests, "t", false, "(alias for -withtests) include test packages")
flag.IntVar(maxLevel, "l", 256, "(alias for -maxlevel) maximum level of the go dependency graph")
flag.BoolVar(withGoroot, "d", false, "(alias for -withgoroot) show dependencies of packages in the Go standard library")
}
func main() {
pkgs = make(map[string]*build.Package)
erroredPkgs = make(map[string]bool)
ids = make(map[string]string)
flag.Parse()
args := flag.Args()
if len(args) < 1 {
log.Fatal("need one package name to process")
}
if *ignorePrefixes != "" {
ignoredPrefixes = strings.Split(*ignorePrefixes, ",")
}
if *onlyPrefix != "" {
onlyPrefixes = strings.Split(*onlyPrefix, ",")
}
if *ignorePackages != "" {
for _, p := range strings.Split(*ignorePackages, ",") {
ignored[p] = true
}
}
if *tagList != "" {
buildTags = strings.Split(*tagList, ",")
}
buildContext.BuildTags = buildTags
cwd, err := os.Getwd()
if err != nil {
log.Fatalf("failed to get cwd: %s", err)
}
for _, a := range args {
if err := processPackage(cwd, a, 0, "", *stopOnError); err != nil {
log.Fatal(err)
}
}
fmt.Println("digraph godep {")
if *horizontal {
fmt.Println(`rankdir="LR"`)
}
fmt.Print(`splines=ortho
nodesep=0.4
ranksep=0.8
node [shape="box",style="rounded,filled"]
edge [arrowsize="0.5"]
`)
// sort packages
pkgKeys := []string{}
for k := range pkgs {
pkgKeys = append(pkgKeys, k)
}
sort.Strings(pkgKeys)
for _, pkgName := range pkgKeys {
pkg := pkgs[pkgName]
pkgId := getId(pkgName)
if isIgnored(pkg) {
continue
}
var color string
switch {
case pkg.Goroot:
color = "palegreen"
case len(pkg.CgoFiles) > 0:
color = "darkgoldenrod1"
case isVendored(pkg.ImportPath):
color = "palegoldenrod"
case hasBuildErrors(pkg):
color = "red"
default:
color = "paleturquoise"
}
fmt.Printf("%s [label=\"%s\" color=\"%s\" URL=\"%s\" target=\"_blank\"];\n", pkgId, pkgName, color, pkgDocsURL(pkgName))
// Don't render imports from packages in Goroot
if pkg.Goroot && !*withGoroot {
continue
}
for _, imp := range getImports(pkg) {
impPkg := pkgs[imp]
if impPkg == nil || isIgnored(impPkg) {
continue
}
impId := getId(imp)
fmt.Printf("%s -> %s;\n", pkgId, impId)
}
}
fmt.Println("}")
}
func pkgDocsURL(pkgName string) string {
return "https://godoc.org/" + pkgName
}
func processPackage(root string, pkgName string, level int, importedBy string, stopOnError bool) error {
if level++; level > *maxLevel {
return nil
}
if ignored[pkgName] {
return nil
}
pkg, buildErr := buildContext.Import(pkgName, root, 0)
if buildErr != nil {
if stopOnError {
return fmt.Errorf("failed to import %s (imported at level %d by %s):\n%s", pkgName, level, importedBy, buildErr)
}
}
if isIgnored(pkg) {
return nil
}
importPath := normalizeVendor(pkgName)
if buildErr != nil {
erroredPkgs[importPath] = true
}
pkgs[importPath] = pkg
// Don't worry about dependencies for stdlib packages
if pkg.Goroot && !*withGoroot {
return nil
}
for _, imp := range getImports(pkg) {
if _, ok := pkgs[imp]; !ok {
if err := processPackage(pkg.Dir, imp, level, pkgName, stopOnError); err != nil {
return err
}
}
}
return nil
}
func getImports(pkg *build.Package) []string {
allImports := pkg.Imports
if *withTests {
allImports = append(allImports, pkg.TestImports...)
allImports = append(allImports, pkg.XTestImports...)
}
var imports []string
found := make(map[string]struct{})
for _, imp := range allImports {
if imp == normalizeVendor(pkg.ImportPath) {
// Don't draw a self-reference when foo_test depends on foo.
continue
}
if _, ok := found[imp]; ok {
continue
}
found[imp] = struct{}{}
imports = append(imports, imp)
}
return imports
}
func deriveNodeID(packageName string) string {
//TODO: improve implementation?
id := "\"" + packageName + "\""
return id
}
func getId(name string) string {
id, ok := ids[name]
if !ok {
id = deriveNodeID(name)
ids[name] = id
}
return id
}
func hasPrefixes(s string, prefixes []string) bool {
for _, p := range prefixes {
if strings.HasPrefix(s, p) {
return true
}
}
return false
}
func isIgnored(pkg *build.Package) bool {
if len(onlyPrefixes) > 0 && !hasPrefixes(normalizeVendor(pkg.ImportPath), onlyPrefixes) {
return true
}
if *ignoreVendor && isVendored(pkg.ImportPath) {
return true
}
return ignored[normalizeVendor(pkg.ImportPath)] || (pkg.Goroot && *ignoreStdlib) || hasPrefixes(normalizeVendor(pkg.ImportPath), ignoredPrefixes)
}
func hasBuildErrors(pkg *build.Package) bool {
if len(erroredPkgs) == 0 {
return false
}
v, ok := erroredPkgs[normalizeVendor(pkg.ImportPath)]
if !ok {
return false
}
return v
}
func debug(args ...interface{}) {
fmt.Fprintln(os.Stderr, args...)
}
func debugf(s string, args ...interface{}) {
fmt.Fprintf(os.Stderr, s, args...)
}
func isVendored(path string) bool {
return strings.Contains(path, "/vendor/")
}
func normalizeVendor(path string) string {
pieces := strings.Split(path, "vendor/")
return pieces[len(pieces)-1]
}