forked from tools/godep
-
Notifications
You must be signed in to change notification settings - Fork 3
/
pkg.go
70 lines (64 loc) · 1.23 KB
/
pkg.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
package main
import (
"encoding/json"
"io"
"log"
"os"
"os/exec"
)
type Package struct {
Dir string
Root string
ImportPath string
Deps []string
Standard bool
TestImports []string
Error struct {
Err string
}
}
// MustLoadPackages is like LoadPackages but it calls log.Fatal
// if an error occurs.
func MustLoadPackages(name ...string) []*Package {
p, err := LoadPackages(name...)
if err != nil {
log.Fatal(err)
}
return p
}
// LoadPackages loads the named packages using go list -json.
// Unlike the go tool, an empty argument list is treated as
// an empty list; "." must be given explicitly if desired.
func LoadPackages(name ...string) (a []*Package, err error) {
if len(name) == 0 {
return nil, nil
}
args := []string{"list", "-e", "-json"}
cmd := exec.Command("go", append(args, name...)...)
r, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
cmd.Stderr = os.Stderr
err = cmd.Start()
if err != nil {
return nil, err
}
d := json.NewDecoder(r)
for {
info := new(Package)
err = d.Decode(info)
if err == io.EOF {
break
}
if err != nil {
info.Error.Err = err.Error()
}
a = append(a, info)
}
err = cmd.Wait()
if err != nil {
return nil, err
}
return a, nil
}