forked from google/godepq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
godepq.go
226 lines (197 loc) · 5.6 KB
/
godepq.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
/*
Copyright (c) 2013-2016 the Godepq Authors
Use of this source code is governed by a MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
package main
import (
"errors"
"flag"
"fmt"
"go/build"
"os"
"regexp"
"github.com/google/godepq/deps"
)
var (
// TODO: add support for multiple from / to packages
from = flag.String("from", "", "root package")
to = flag.String("to", "", "target package for querying dependency paths")
toRegex = flag.String("toregex", "", "target package regex for querying dependency paths")
ignore = flag.String("ignore", "", "regular expression for packages to ignore")
include = flag.String("include", "", "regular expression for packages to include (excluding packages matching -ignore)")
includeTests = flag.Bool("include-tests", false, "whether to include test imports")
includeStdlib = flag.Bool("include-stdlib", false, "whether to include go standard library imports")
allPaths = flag.Bool("all-paths", false, "whether to include all paths in the result")
output = flag.String("o", "list", "{list: print path(s), dot: export dot graph}")
showLinesOfCode = flag.Bool("show-loc", false, "show lines of code per package")
)
func main() {
flag.Parse()
err := run()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
func run() error {
err := validateFlags()
if err != nil {
return err
}
wd, err := os.Getwd()
if err != nil {
return err
}
fromPkg, baseDir, err := resolveSource(*from, wd)
if err != nil {
return err
}
var toPkg deps.Package
if *to != "" {
toPkg, err = deps.Resolve(*to, wd, build.Default)
if err != nil {
return err
}
}
builder := deps.Builder{
Roots: []deps.Package{fromPkg},
IncludeTests: *includeTests,
IncludeStdlib: *includeStdlib,
BuildContext: build.Default,
BaseDir: baseDir,
}
if *ignore != "" {
ignoreRegexp, err := regexp.Compile(*ignore)
if err != nil {
return err
}
builder.Ignored = []*regexp.Regexp{ignoreRegexp}
}
if *include != "" {
includeRegexp, err := regexp.Compile(*include)
if err != nil {
return err
}
builder.Included = []*regexp.Regexp{includeRegexp}
}
graph, err := builder.Build()
if err != nil {
return err
}
var result deps.Graph
var endCond func(deps.Package) bool
if toPkg != "" {
endCond = func(pkg deps.Package) bool {
return pkg == toPkg
}
} else if *toRegex != "" {
r := regexp.MustCompile(*toRegex)
endCond = func(pkg deps.Package) bool {
return r.MatchString(string(pkg))
}
}
if endCond != nil {
if *allPaths {
result = graph.Forward.AllPathsCond(fromPkg, endCond)
} else {
path := graph.Forward.SomePathCond(fromPkg, endCond)
result = deps.NewGraph()
result.AddPath(path)
}
} else {
result = graph.Forward
}
if result == nil || len(result) == 0 {
dst := string(toPkg)
if *toRegex != "" {
dst = *toRegex
}
fmt.Fprintf(os.Stderr, "No path found from %q to %q\n", fromPkg, dst)
os.Exit(1)
}
switch *output {
case "list":
if *showLinesOfCode {
printListWithLOC(fromPkg, result, graph.Info)
} else {
printList(fromPkg, result)
}
return nil
case "dot":
if *showLinesOfCode {
printDotWithLOC(fromPkg, result, graph.Info)
} else {
printDot(fromPkg, result)
}
return nil
default:
return fmt.Errorf("Unknown output format %q", *output)
}
}
func validateFlags() error {
if *from == "" {
return errors.New("-from must be set")
}
if *allPaths && *to == "" && *toRegex == "" {
return errors.New("-all-paths requires a -to package")
}
if *to != "" && *toRegex != "" {
return errors.New("only one of -to and -toregex may be set")
}
if *toRegex != "" {
if _, err := regexp.Compile(*toRegex); err != nil {
return fmt.Errorf("invalid -toregex: %v", err)
}
}
if len(flag.Args()) != 0 {
return fmt.Errorf("unexpected positional arguments: %v", flag.Args())
}
if *ignore != "" && *ignore == *include {
return errors.New("-include can not be the same as -ignore")
}
return nil
}
func printList(root deps.Package, paths deps.Graph) {
fmt.Println("Packages:")
for _, pkg := range paths.List(root) {
fmt.Printf(" %s\n", pkg)
}
}
func printListWithLOC(root deps.Package, paths deps.Graph, pkgInfo map[deps.Package]*deps.DependencyInfo) {
totalLOC := 0
fmt.Println("Packages:")
for _, pkg := range paths.List(root) {
fmt.Printf("%s (%d)\n", pkg, pkgInfo[pkg].LOC)
totalLOC += pkgInfo[pkg].LOC
}
fmt.Printf("\nTotal Lines Of Code: %d\n", totalLOC)
}
func printDot(root deps.Package, paths deps.Graph) {
labelFn := func(pkg deps.Package) string {
return fmt.Sprintf("%s", pkg)
}
fmt.Println(paths.Dot(root, labelFn))
}
func printDotWithLOC(root deps.Package, paths deps.Graph, pkgInfo map[deps.Package]*deps.DependencyInfo) {
labelFn := func(pkg deps.Package) string {
return fmt.Sprintf("%s (%d)", pkg, pkgInfo[pkg].LOC)
}
fmt.Println(paths.Dot(root, labelFn))
}
// resolveSource resolves the import path, and determines the base directory to resolve future
// imports from.
// If the resolved import is vendored, then future imports should use the same vendored sources.
// Otherwise, future imports should be resolved with the source's vendor directory.
func resolveSource(importPath, workingDir string) (deps.Package, string, error) {
pkg, err := build.Default.Import(importPath, workingDir, build.FindOnly)
if err != nil {
return "", "", fmt.Errorf("unable to resolve %q: %v", importPath, err)
}
src, vendored := deps.StripVendor(deps.Package(pkg.ImportPath))
if vendored {
return src, workingDir, nil
}
return src, pkg.Dir, nil
}