-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy pathmain.go
251 lines (210 loc) · 4.56 KB
/
main.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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"go/format"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"text/template"
)
const Ext = ".tmpl"
type pathSpec struct {
in, out string
}
func (p *pathSpec) String() string { return p.in + " → " + p.out }
func (p *pathSpec) IsGoFile() bool { return filepath.Ext(p.out) == ".go" }
func parsePath(path string) (string, string) {
p := strings.IndexByte(path, '=')
if p == -1 {
if filepath.Ext(path) != Ext {
errExit("template file '%s' must have .tmpl extension", path)
}
return path, path[:len(path)-len(Ext)]
}
return path[:p], path[p+1:]
}
type data struct {
In interface{}
D listValue
}
func errExit(format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, format, a...)
fmt.Fprintln(os.Stderr)
os.Exit(1)
}
type listValue map[string]string
func (l listValue) String() string {
res := make([]string, 0, len(l))
for k, v := range l {
res = append(res, fmt.Sprintf("%s=%s", k, v))
}
return strings.Join(res, ", ")
}
func (l listValue) Set(v string) error {
nv := strings.Split(v, "=")
if len(nv) != 2 {
return fmt.Errorf("expected NAME=VALUE, got %s", v)
}
l[nv[0]] = nv[1]
return nil
}
func main() {
var (
dataArg = flag.String("data", "", "input JSON data")
gi = flag.Bool("i", false, "run goimports")
in = &data{D: make(listValue)}
)
flag.Var(&in.D, "d", "-d NAME=VALUE")
flag.Parse()
if *dataArg == "" {
errExit("data option is required")
}
if *gi {
if _, err := exec.LookPath("goimports"); err != nil {
errExit("failed to find goimports: %s", err.Error())
}
formatter = formatSource
} else {
formatter = format.Source
}
paths := flag.Args()
if len(paths) == 0 {
errExit("no tmpl files specified")
}
specs := make([]pathSpec, len(paths))
for i, p := range paths {
in, out := parsePath(p)
specs[i] = pathSpec{in: in, out: out}
}
in.In = readData(*dataArg)
process(in, specs)
}
func mustReadAll(path string) []byte {
data, err := ioutil.ReadFile(path)
if err != nil {
errExit(err.Error())
}
return data
}
func readData(path string) interface{} {
data := mustReadAll(path)
var v interface{}
if err := json.Unmarshal(StripComments(data), &v); err != nil {
errExit("invalid JSON data: %s", err.Error())
}
return v
}
func fileMode(path string) os.FileMode {
stat, err := os.Stat(path)
if err != nil {
errExit(err.Error())
}
return stat.Mode()
}
var funcs = template.FuncMap{
"lower": strings.ToLower,
"upper": strings.ToUpper,
}
func process(data interface{}, specs []pathSpec) {
for _, spec := range specs {
var (
t *template.Template
err error
)
t, err = template.New("gen").Funcs(funcs).Parse(string(mustReadAll(spec.in)))
if err != nil {
errExit("error processing template '%s': %s", spec.in, err.Error())
}
var buf bytes.Buffer
if spec.IsGoFile() {
// preamble
fmt.Fprintf(&buf, "// Code generated by %s. DO NOT EDIT.\n", spec.in)
fmt.Fprintln(&buf)
}
err = t.Execute(&buf, data)
if err != nil {
errExit("error executing template '%s': %s", spec.in, err.Error())
}
generated := buf.Bytes()
if spec.IsGoFile() {
generated, err = formatter(generated)
if err != nil {
errExit("error formatting '%s': %s", spec.in, err.Error())
}
}
ioutil.WriteFile(spec.out, generated, fileMode(spec.in))
}
}
var (
formatter func([]byte) ([]byte, error)
)
func formatSource(in []byte) ([]byte, error) {
r := bytes.NewReader(in)
cmd := exec.Command("goimports")
cmd.Stdin = r
out, err := cmd.Output()
if err != nil {
if ee, ok := err.(*exec.ExitError); ok {
return nil, fmt.Errorf("error running goimports: %s", string(ee.Stderr))
}
return nil, fmt.Errorf("error running goimports: %s", string(out))
}
return out, nil
}
func StripComments(raw []byte) []byte {
var (
quoted, esc bool
comment bool
)
buf := bytes.Buffer{}
for i := 0; i < len(raw); i++ {
b := raw[i]
if comment {
switch b {
case '/':
comment = false
j := bytes.IndexByte(raw[i+1:], '\n')
if j == -1 {
i = len(raw)
} else {
i += j // keep new line
}
case '*':
j := bytes.Index(raw[i+1:], []byte("*/"))
if j == -1 {
i = len(raw)
} else {
i += j + 2
comment = false
}
}
continue
}
if esc {
esc = false
continue
}
if b == '\\' && quoted {
esc = true
continue
}
if b == '"' || b == '\'' {
quoted = !quoted
}
if b == '/' && !quoted {
comment = true
continue
}
buf.WriteByte(b)
}
if quoted || esc || comment {
// unexpected state, so return raw bytes
return raw
}
return buf.Bytes()
}