-
Notifications
You must be signed in to change notification settings - Fork 152
/
generate.go
317 lines (297 loc) · 7.66 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
package cmd
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"reflect"
"strings"
"github.com/dave/jennifer/jen"
"github.com/influxdata/flux/ast"
"github.com/influxdata/flux/internal/token"
"github.com/influxdata/flux/parser"
"github.com/pkg/errors"
"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 []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
}
var pkg *ast.Package
switch len(pkgs) {
case 0:
return nil
case 1:
for k := range pkgs {
pkg = pkgs[k]
}
default:
keys := make([]string, 0, len(pkgs))
for k := range pkgs {
keys = append(keys, k)
}
return fmt.Errorf("found multiple packages in the same directory: %s packages %v", dir, keys)
}
if ast.Check(pkg) > 0 {
return errors.Wrapf(ast.GetError(pkg), "failed to parse package %q", pkg.Package)
}
// Track go import path
goPath := path.Join(pkgName, dir)
if goPath != pkgName {
goPackages = append(goPackages, goPath)
}
// Assign import path
pkg.Path = fluxPath
// Write out the package
f := jen.NewFile(pkg.Package)
f.HeaderComment("// DO NOT EDIT: This file is autogenerated via the builtin command.")
f.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
}
f.Var().Id("pkgAST").Op("=").Add(v)
return f.Save(filepath.Join(dir, "flux_gen.go"))
})
if 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 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:
typ := v.Type()
s := indirectType(typ)
values := make(jen.Dict, v.NumField())
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
if !field.CanInterface() {
// Ignore private fields
continue
}
val, err := constructValue(field)
if err != nil {
return nil, err
}
values[jen.Id(typ.Field(i).Name)] = val
}
s.Values(values)
return s, 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())
}
}
// 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(""),
}