-
Notifications
You must be signed in to change notification settings - Fork 90
/
get.go
70 lines (56 loc) · 1.37 KB
/
get.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 (
"go/parser"
"go/token"
"os"
"os/exec"
"strings"
"github.com/clipperhouse/typewriter"
)
// get runs `go get` for required typewriters, either default or specified in _gen.go
func get(c config, args ...string) error {
imports, err := getTypewriterImports(c)
if err != nil {
return err
}
// we just want the paths
var imps []string
for imp := range imports {
imps = append(imps, imp.Path)
}
get := []string{"get"}
get = append(get, args...)
get = append(get, imps...)
cmd := exec.Command("go", get...)
cmd.Stdout = c.out
cmd.Stderr = c.out
if err := cmd.Run(); err != nil {
return err
}
return nil
}
func getTypewriterImports(c config) (typewriter.ImportSpecSet, error) {
imports := typewriter.NewImportSpecSet()
// check for existence of custom file
if src, err := os.Open(c.customName); err == nil {
defer src.Close()
// custom file exists, parse its imports
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "", src, parser.ImportsOnly)
if err != nil {
return imports, err
}
// convert ast imports into ImportSpecs
for _, v := range f.Imports {
imp := typewriter.ImportSpec{
Name: v.Name.Name,
Path: strings.Trim(v.Path.Value, `"`), // lose the quotes
}
imports.Add(imp)
}
} else {
// doesn't exist, use standard (clone it)
imports = stdImports.Clone()
}
return imports, nil
}