forked from dominikh/go-tools
-
Notifications
You must be signed in to change notification settings - Fork 1
/
rdeps.go
78 lines (72 loc) · 1.6 KB
/
rdeps.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
// rdeps scans GOPATH for all reverse dependencies of a set of Go
// packages.
//
// rdeps will not sort its output, and the order of the output is
// undefined. Pipe its output through sort if you need stable output.
package main
import (
"bufio"
"flag"
"fmt"
"go/build"
"os"
"github.com/kisielk/gotool"
"golang.org/x/tools/go/buildutil"
"golang.org/x/tools/refactor/importgraph"
)
func main() {
var tags buildutil.TagsFlag
flag.Var(&tags, "tags", "List of build tags")
stdin := flag.Bool("stdin", false, "Read packages from stdin instead of the command line")
recursive := flag.Bool("r", false, "Print reverse dependencies recursively")
flag.Parse()
ctx := build.Default
ctx.BuildTags = tags
var args []string
if *stdin {
s := bufio.NewScanner(os.Stdin)
for s.Scan() {
args = append(args, s.Text())
}
} else {
args = flag.Args()
}
if len(args) == 0 {
return
}
wd, err := os.Getwd()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
pkgs := gotool.ImportPaths(args)
for i, pkg := range pkgs {
bpkg, err := ctx.Import(pkg, wd, build.FindOnly)
if err != nil {
continue
}
pkgs[i] = bpkg.ImportPath
}
_, reverse, errors := importgraph.Build(&ctx)
_ = errors
seen := map[string]bool{}
var printRDeps func(pkg string)
printRDeps = func(pkg string) {
for rdep := range reverse[pkg] {
if seen[rdep] {
continue
}
seen[rdep] = true
fmt.Println(rdep)
if *recursive {
printRDeps(rdep)
}
}
}
for _, pkg := range pkgs {
printRDeps(pkg)
}
for pkg, err := range errors {
fmt.Fprintf(os.Stderr, "error in package %s: %s\n", pkg, err)
}
}