forked from torbiak/gopl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathancestors.go
76 lines (70 loc) · 1.6 KB
/
ancestors.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
// ex10.4 lists go packages that transitively depend on the given packages.
package main
import (
"bufio"
"bytes"
"fmt"
"log"
"os"
"os/exec"
"sort"
"strings"
)
func logCommandError(context string, err error) {
ee, ok := err.(*exec.ExitError)
if !ok {
log.Fatalf("%s: %s", context, err)
}
log.Printf("%s: %s", context, err)
os.Stderr.Write(ee.Stderr)
os.Exit(1)
}
// packages returns a slice of package import paths corresponding to slice of
// package patterns.
// See 'go help packages' for different ways of specifying packages.
func packages(patterns []string) []string {
args := []string{"list", "-f={{.ImportPath}}"}
for _, pkg := range patterns {
args = append(args, pkg)
}
out, err := exec.Command("go", args...).Output()
if err != nil {
logCommandError("resolve packages", err)
}
return strings.Fields(string(out))
}
func ancestors(packageNames []string) []string {
targets := make(map[string]bool)
for _, pkg := range packageNames {
targets[pkg] = true
}
args := []string{"list", `-f={{.ImportPath}} {{join .Deps " "}}`, "..."}
out, err := exec.Command("go", args...).Output()
if err != nil {
logCommandError("find ancestors", err)
}
var pkgs []string
s := bufio.NewScanner(bytes.NewReader(out))
for s.Scan() {
fields := strings.Fields(s.Text())
pkg := fields[0]
deps := fields[1:]
for _, dep := range deps {
if targets[dep] {
pkgs = append(pkgs, pkg)
break
}
}
}
return pkgs
}
func main() {
if len(os.Args) < 2 {
os.Exit(0)
}
pkgs := ancestors(packages(os.Args[1:]))
sort.StringSlice(pkgs).Sort()
for _, pkg := range pkgs {
fmt.Println(pkg)
}
}