-
Notifications
You must be signed in to change notification settings - Fork 1
/
generator.go
142 lines (121 loc) · 2.42 KB
/
generator.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
package main
import (
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"text/template"
"golang.org/x/tools/go/packages"
)
var ErrWrongPackageCount = errors.New("Must be part of only one package")
type Generator struct {
Path string
Filename string
Package string
GenStructs []string
MapEncoding bool
}
type templateData struct {
Path string
Filebase string
Package string
GenStructs []string
PkgPath string
MapEncoding bool
}
func (g Generator) GenerateCborTypes() error {
fpath := filepath.Join(g.Path, g.Filename)
pkgs, err := packages.Load(&packages.Config{}, "file="+fpath)
if err != nil {
return err
}
if len(pkgs) != 1 {
return ErrWrongPackageCount
}
tdata := templateData{
Path: g.Path,
Package: g.Package,
Filebase: strings.TrimSuffix(g.Filename, ".go"),
PkgPath: pkgs[0].PkgPath,
GenStructs: g.GenStructs,
MapEncoding: g.MapEncoding,
}
rt, err := template.New("run_cbor_gen").Parse(runTemplate)
if err != nil {
return err
}
mt, err := template.New("main").Parse(mainTemplate)
if err != nil {
return err
}
dir, err := ioutil.TempDir(".", "gen")
if err != nil {
return err
}
defer os.RemoveAll(dir) // clean up
f, err := os.OpenFile(filepath.Join(dir, "main.go"), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
err = mt.Execute(f, tdata)
if err != nil {
return err
}
f.Close()
tmp, err := ioutil.TempFile(".", "*.go")
if err != nil {
return err
}
defer os.Remove(tmp.Name())
err = rt.Execute(tmp, tdata)
if err != nil {
return err
}
tmp.Close()
cmd := exec.Command("go", "run", filepath.Join(dir, "main.go"))
output, err := cmd.Output()
fmt.Println(string(output))
return err
}
var (
runTemplate = `
package {{.Package}}
import (
cborgen "github.com/whyrusleeping/cbor-gen"
)
func RunCborGen() error {
genName := "{{.Path}}/{{.Filebase}}_cbor_gen.go"
{{ if .MapEncoding }}
if err := cborgen.WriteMapEncodersToFile(
{{ else }}
if err := cborgen.WriteTupleEncodersToFile(
{{ end }}
genName,
"{{.Package}}",
{{range .GenStructs}}
{{.}}{},
{{end}}
); err != nil {
return err
}
return nil
}
`
mainTemplate = `
package main
import (
"fmt"
"os"
{{.Package}} "{{.PkgPath}}"
)
func main() {
fmt.Print("Generating Cbor Marshal/Unmarshal...")
if err := {{.Package}}.RunCborGen(); err != nil {
fmt.Println("Failed: ")
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Done.")
}
`
)