-
Notifications
You must be signed in to change notification settings - Fork 152
/
generate.go
444 lines (418 loc) · 11.6 KB
/
generate.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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
package cmd
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"reflect"
"strings"
"time"
"github.com/dave/jennifer/jen"
"github.com/influxdata/flux/ast"
"github.com/influxdata/flux/codes"
"github.com/influxdata/flux/internal/errors"
"github.com/influxdata/flux/internal/token"
"github.com/influxdata/flux/parser"
"github.com/spf13/cobra"
)
// generateCmd represents the generate command
var generateCmd = &cobra.Command{
Use: "generate",
Short: "Generate Go source from Flux source",
Long: `This utility creates Go sources files from Flux source files.
The process is to parse directories recursively and within each directory
write out a single file with the Flux AST representation of the directory source.
`,
RunE: generate,
}
var (
pkgName,
rootDir,
importFile,
ignoreFile string
)
func init() {
rootCmd.AddCommand(generateCmd)
generateCmd.Flags().StringVar(&pkgName, "go-pkg", "", "The fully qualified Go package name of the root package.")
generateCmd.Flags().StringVar(&rootDir, "root-dir", ".", "The root level directory for all packages.")
generateCmd.Flags().StringVar(&importFile, "import-file", "builtin_gen.go", "Location relative to root-dir to place a file to import all generated packages.")
generateCmd.Flags().StringVar(&ignoreFile, "ignoreFile-file", ".fluxignore", "Location relative to root-dir of file containing packages to ignore one per line.")
}
func generate(cmd *cobra.Command, args []string) error {
ignored, err := readIgnoreFile(ignoreFile)
if err != nil {
return err
}
var goPackages, testPackages []string
err = walkDirs(rootDir, func(dir string) error {
// Determine the absolute flux package path
fluxPath, err := filepath.Rel(rootDir, dir)
if err != nil {
return err
}
if contains(fluxPath, ignored) {
return nil
}
fset := new(token.FileSet)
pkgs, err := parser.ParseDir(fset, dir)
if err != nil {
return err
}
// Annotate the packages with the absolute flux package path.
for _, pkg := range pkgs {
pkg.Path = fluxPath
}
var fluxPkg, testPkg *ast.Package
switch len(pkgs) {
case 0:
return nil
case 1:
for k, v := range pkgs {
if strings.HasSuffix(k, "_test") {
testPkg = v
} else {
fluxPkg = v
}
}
case 2:
for k, v := range pkgs {
if strings.HasSuffix(k, "_test") {
testPkg = v
continue
}
fluxPkg = v
}
if fluxPkg == nil {
return fmt.Errorf("cannot have two Flux test packages in the same directory")
}
if testPkg == nil {
return fmt.Errorf("cannot have two distinct non-test Flux packages in the same directory")
}
default:
keys := make([]string, 0, len(pkgs))
for k := range pkgs {
keys = append(keys, k)
}
return fmt.Errorf("found more than 2 flux packages in directory %s; packages %v", dir, keys)
}
if fluxPkg != nil {
if ast.Check(fluxPkg) > 0 {
return errors.Wrapf(ast.GetError(fluxPkg), codes.Inherit, "failed to parse package %q", fluxPkg.Package)
}
// Assign import path
fluxPkg.Path = fluxPath
// Track go import path
goPath := path.Join(pkgName, dir)
if goPath != pkgName {
goPackages = append(goPackages, goPath)
}
// Write the ast file
if err := generateFluxASTFile(dir, fluxPkg); err != nil {
return err
}
}
if testPkg != nil {
if ast.Check(testPkg) > 0 {
return errors.Wrapf(ast.GetError(testPkg), codes.Inherit, "failed to parse test package %q", testPkg.Package)
}
// Validate test package file use _test.flux suffix for the file name
for _, f := range testPkg.Files {
if !strings.HasSuffix(f.Name, "_test.flux") {
return fmt.Errorf("flux test files must use the _test.flux suffix in their file name, found %q", path.Join(dir, f.Name))
}
}
// Track go import path
importPath := path.Join(pkgName, dir)
if importPath != pkgName {
testPackages = append(testPackages, importPath)
}
// Generate test AST file using non *_test package name since this is Go code that needs to be part of the normal build.
if err := generateTestASTFile(dir, strings.TrimSuffix(testPkg.Package, "_test"), []*ast.Package{testPkg}); err != nil {
return err
}
}
return nil
})
if err != nil {
return err
}
if err := generateTestPkgList(testPackages); err != nil {
return err
}
// Write the import file
f := jen.NewFile(path.Base(pkgName))
f.HeaderComment("// DO NOT EDIT: This file is autogenerated via the builtin command.")
f.Anon(goPackages...)
return f.Save(filepath.Join(rootDir, importFile))
}
func generateFluxASTFile(dir string, pkg *ast.Package) error {
file := jen.NewFile(pkg.Package)
file.HeaderComment("// DO NOT EDIT: This file is autogenerated via the builtin command.")
file.Func().Id("init").Call().Block(
jen.Qual("github.com/influxdata/flux", "RegisterPackage").
Call(jen.Id("pkgAST")),
)
// Construct a value using reflection for the pkg AST
v, err := constructValue(reflect.ValueOf(pkg))
if err != nil {
return err
}
file.Var().Id("pkgAST").Op("=").Add(v)
return file.Save(filepath.Join(dir, "flux_gen.go"))
}
func generateTestPkgList(imports []string) error {
stmts := make([]jen.Code, len(imports)+2)
// var pkgs []*ast.Package
stmts[0] = jen.
Var().
Id("pkgs").
Index().
Op("*").
Qual("github.com/influxdata/flux/ast", "Package")
for i, path := range imports {
// pkgs = append(pkgs, <imported_package>.FluxTestPackages...)
stmts[i+1] = jen.Id("pkgs").Op("=").Id("append").Call(
jen.Id("pkgs"), jen.Qual(path, "FluxTestPackages").Op("..."),
)
}
// return pkgs
stmts[len(stmts)-1] = jen.Return(jen.Id("pkgs"))
file := jen.NewFile(path.Base(pkgName))
file.HeaderComment("// DO NOT EDIT: This file is autogenerated via the builtin command.")
// var FluxTestPackages = func() []*ast.Package {
// statements ...
// }
file.
Var().
Id("FluxTestPackages").
Op("=").
Func().
Params().
Index().
Op("*").
Qual("github.com/influxdata/flux/ast", "Package").
Block(stmts...).
Call()
return file.Save(filepath.Join(rootDir, "test_packages.go"))
}
func generateTestASTFile(dir, pkg string, pkgs []*ast.Package) error {
file := jen.NewFile(pkg)
file.HeaderComment("// DO NOT EDIT: This file is autogenerated via the builtin command.")
v, err := constructValue(reflect.ValueOf(pkgs))
if err != nil {
return err
}
file.Var().Id("FluxTestPackages").Op("=").Add(v)
return file.Save(filepath.Join(dir, "flux_test_gen.go"))
}
func readIgnoreFile(fn string) ([]string, error) {
f, err := os.Open(fn)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
var ignored []string
for scanner.Scan() {
ignored = append(ignored, strings.TrimSpace(scanner.Text()))
}
return ignored, scanner.Err()
}
func contains(s string, list []string) bool {
for _, l := range list {
if s == l {
return true
}
}
return false
}
func walkDirs(path string, f func(dir string) error) error {
files, err := ioutil.ReadDir(path)
if err != nil {
return err
}
if err := f(path); err != nil {
return err
}
for _, file := range files {
if file.IsDir() {
if err := walkDirs(filepath.Join(path, file.Name()), f); err != nil {
return err
}
}
}
return nil
}
// indirectType returns a code statement that represents the type expression
// for the given type.
func indirectType(typ reflect.Type) *jen.Statement {
switch typ.Kind() {
case reflect.Map:
c := jen.Index(indirectType(typ.Key()))
c.Add(indirectType(typ.Elem()))
return c
case reflect.Ptr:
c := jen.Op("*")
c.Add(indirectType(typ.Elem()))
return c
case reflect.Array, reflect.Slice:
c := jen.Index()
c.Add(indirectType(typ.Elem()))
return c
default:
return jen.Qual(typ.PkgPath(), typ.Name())
}
}
// constructValue returns a Code value for the given value.
func constructValue(v reflect.Value) (jen.Code, error) {
switch v.Kind() {
case reflect.Array:
s := indirectType(v.Type())
values := make([]jen.Code, v.Len())
for i := 0; i < v.Len(); i++ {
val, err := constructValue(v.Index(i))
if err != nil {
return nil, err
}
values[i] = val
}
s.Values(values...)
return s, nil
case reflect.Slice:
if v.IsNil() {
return jen.Nil(), nil
}
s := indirectType(v.Type())
values := make([]jen.Code, v.Len())
for i := 0; i < v.Len(); i++ {
val, err := constructValue(v.Index(i))
if err != nil {
return nil, err
}
values[i] = val
}
s.Values(values...)
return s, nil
case reflect.Interface:
if v.IsNil() {
return jen.Nil(), nil
}
return constructValue(v.Elem())
case reflect.Ptr:
if v.IsNil() {
return jen.Nil(), nil
}
s := jen.Op("&")
val, err := constructValue(reflect.Indirect(v))
if err != nil {
return nil, err
}
return s.Add(val), nil
case reflect.Map:
if v.IsNil() {
return jen.Nil(), nil
}
s := indirectType(v.Type())
keys := v.MapKeys()
values := make(jen.Dict, v.Len())
for _, k := range keys {
key, err := constructValue(k)
if err != nil {
return nil, err
}
val, err := constructValue(v.MapIndex(k))
if err != nil {
return nil, err
}
values[key] = val
}
s.Values(values)
return s, nil
case reflect.Struct:
switch v.Type().Name() {
case "DateTimeLiteral":
lit := v.Interface().(ast.DateTimeLiteral)
fmtTime := lit.Value.Format(time.RFC3339Nano)
return constructStructValue(v, map[string]*jen.Statement{
"Value": jen.Qual("github.com/influxdata/flux/internal/parser", "MustParseTime").Call(jen.Lit(fmtTime)),
})
case "RegexpLiteral":
lit := v.Interface().(ast.RegexpLiteral)
regexString := lit.Value.String()
return constructStructValue(v, map[string]*jen.Statement{
"Value": jen.Qual("regexp", "MustCompile").Call(jen.Lit(regexString)),
})
}
return constructStructValue(v, nil)
case reflect.Bool,
reflect.Int,
reflect.Int8,
reflect.Int16,
reflect.Int32,
reflect.Int64,
reflect.Uint,
reflect.Uint8,
reflect.Uint16,
reflect.Uint32,
reflect.Uint64,
reflect.Uintptr,
reflect.Float32,
reflect.Float64,
reflect.Complex64,
reflect.Complex128,
reflect.String:
typ := types[v.Kind()]
cv := v.Convert(typ)
return jen.Lit(cv.Interface()), nil
default:
return nil, fmt.Errorf("unsupport value kind %v", v.Kind())
}
}
func constructStructValue(v reflect.Value, replace map[string]*jen.Statement) (*jen.Statement, error) {
typ := v.Type()
s := indirectType(typ)
values := make(jen.Dict, v.NumField())
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
name := typ.Field(i).Name
if !field.CanInterface() {
// Ignore private fields
continue
}
if s, ok := replace[name]; ok {
values[jen.Id(name)] = s
continue
}
val, err := constructValue(field)
if err != nil {
return nil, err
}
values[jen.Id(name)] = val
}
return s.Values(values), nil
}
// types is map of reflect.Kind to reflect.Type for the primitive types
var types = map[reflect.Kind]reflect.Type{
reflect.Bool: reflect.TypeOf(false),
reflect.Int: reflect.TypeOf(int(0)),
reflect.Int8: reflect.TypeOf(int8(0)),
reflect.Int16: reflect.TypeOf(int16(0)),
reflect.Int32: reflect.TypeOf(int32(0)),
reflect.Int64: reflect.TypeOf(int64(0)),
reflect.Uint: reflect.TypeOf(uint(0)),
reflect.Uint8: reflect.TypeOf(uint8(0)),
reflect.Uint16: reflect.TypeOf(uint16(0)),
reflect.Uint32: reflect.TypeOf(uint32(0)),
reflect.Uint64: reflect.TypeOf(uint64(0)),
reflect.Uintptr: reflect.TypeOf(uintptr(0)),
reflect.Float32: reflect.TypeOf(float32(0)),
reflect.Float64: reflect.TypeOf(float64(0)),
reflect.Complex64: reflect.TypeOf(complex64(0)),
reflect.Complex128: reflect.TypeOf(complex128(0)),
reflect.String: reflect.TypeOf(""),
}