-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
459 lines (407 loc) · 11.3 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
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
package main
import (
"encoding/json"
"fmt"
goast "go/ast"
"go/format"
"go/parser"
"go/token"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"github.com/spf13/pflag"
"github.com/ccbrown/api-fu/graphql"
"github.com/ccbrown/api-fu/graphql/ast"
"github.com/ccbrown/api-fu/graphql/schema"
"github.com/ccbrown/api-fu/graphql/schema/introspection"
)
type generateState struct {
output string
schema *schema.Schema
wrapper string
outputStructCount int
outputEnums map[string]struct{}
requiresJSONImport bool
}
func fieldName(name string) string {
ret := name
if strings.HasPrefix(ret, "__") {
ret = ret[2:] + "__"
}
return strings.Title(ret)
}
func (s *generateState) generateType(t schema.Type, selections []ast.Selection, nonNull bool, fragTypes map[string]string) (string, error) {
if t, ok := t.(*schema.NonNullType); ok {
return s.generateType(t.Type, selections, true, fragTypes)
}
ret := "interface{}"
switch t := t.(type) {
case *schema.ScalarType:
switch t {
case schema.BooleanType:
ret = "bool"
case schema.IntType:
ret = "int"
case schema.FloatType:
ret = "float64"
case schema.StringType:
ret = "string"
case schema.IDType:
ret = "string"
default:
ret = t.Name
}
if !nonNull {
ret = "*" + ret
}
case *schema.ListType:
gen, err := s.generateType(t.Type, selections, false, fragTypes)
if err != nil {
return "", err
}
ret = "[]" + gen
case *schema.EnumType:
if _, ok := s.outputEnums[t.Name]; !ok {
s.output += "type " + t.Name + " string\n\nconst (\n"
for k := range t.Values {
parts := strings.Split(k, "_")
for i, part := range parts {
parts[i] = strings.Title(strings.ToLower(part))
}
s.output += t.Name + strings.Join(parts, "") + " " + t.Name + " = \"" + k + "\"\n"
}
s.output += ")\n\n"
s.outputEnums[t.Name] = struct{}{}
}
ret = t.Name
if !nonNull {
ret = "*" + ret
}
case *schema.ObjectType, *schema.InterfaceType, *schema.UnionType:
fields := map[string]string{}
hasTypename := false
for _, sel := range selections {
if field, ok := sel.(*ast.Field); ok {
if field.Name.Name == "__typename" {
hasTypename = true
break
}
}
}
// type => field names
typeConditions := map[string][]string{}
for _, sel := range selections {
switch sel := sel.(type) {
case *ast.FragmentSpread:
if !hasTypename {
if _, ok := t.(*schema.ObjectType); !ok {
return "", fmt.Errorf("__typename is required by fragment spread")
}
}
name := sel.FragmentName.Name
fields[name] = "*" + name + "Fragment `json:\"-\"`"
typeConditions[fragTypes[name]] = append(typeConditions[fragTypes[name]], name)
case *ast.InlineFragment:
if !hasTypename {
if _, ok := t.(*schema.ObjectType); !ok {
return "", fmt.Errorf("__typename is required by inline fragment")
}
}
cond := s.schema.NamedTypes()[sel.TypeCondition.Name.Name]
gen, err := s.generateType(cond, sel.SelectionSet.Selections, false, fragTypes)
if err != nil {
return "", err
}
fields[cond.TypeName()] = gen + " `json:\"-\"`"
typeConditions[cond.TypeName()] = append(typeConditions[cond.TypeName()], cond.TypeName())
case *ast.Field:
var selections []ast.Selection
if sel.SelectionSet != nil {
selections = sel.SelectionSet.Selections
}
k := sel.Name.Name
if sel.Alias != nil {
k = sel.Alias.Name
}
if sel.Name.Name == "__typename" {
fields[k] = "string"
} else {
var err error
switch t := t.(type) {
case *schema.ObjectType:
fields[k], err = s.generateType(t.Fields[sel.Name.Name].Type, selections, false, fragTypes)
case *schema.InterfaceType:
fields[k], err = s.generateType(t.Fields[sel.Name.Name].Type, selections, false, fragTypes)
}
if err != nil {
return "", err
}
}
}
}
parts := make([]string, 0, len(fields))
for k, v := range fields {
name := fieldName(k)
jsonTag := ""
if !strings.EqualFold(name, k) {
jsonTag = " `json:\"" + k + "\"`"
}
parts = append(parts, name+" "+v+jsonTag+"\n")
}
sort.Strings(parts)
ret = "struct {\n" + strings.Join(parts, "") + "}"
if len(typeConditions) > 0 {
s.requiresJSONImport = true
tName := t.(schema.NamedType).TypeName()
name := "sel" + tName + strconv.Itoa(s.outputStructCount)
s.output += `
type ` + name + ` ` + ret + `
func (s *` + name + `) UnmarshalJSON(b []byte) error {
var base ` + ret + `
if err := json.Unmarshal(b, &base); err != nil {
return err
}
*s = base
`
for typeCond, fields := range typeConditions {
isKnown := typeCond == tName
if obj, ok := t.(*schema.ObjectType); ok && !isKnown {
for _, iface := range obj.ImplementedInterfaces {
if iface.Name == typeCond {
isKnown = true
break
}
}
}
if isKnown {
for _, field := range fields {
s.output += `if err := json.Unmarshal(b, &s.` + fieldName(field) + `); err != nil {
return err
}
`
}
continue
}
typeCondType := s.schema.NamedTypes()[typeCond]
var okTypes []string
switch t := typeCondType.(type) {
case *schema.InterfaceType:
for _, t := range s.schema.InterfaceImplementations(t.Name) {
okTypes = append(okTypes, t.Name)
}
case *schema.ObjectType:
okTypes = []string{t.Name}
}
for _, field := range fields {
s.output += `switch base.Typename__ {
case "` + strings.Join(okTypes, `", "`) + `":
if err := json.Unmarshal(b, &s.` + fieldName(field) + `); err != nil {
return err
}
}
`
}
}
s.output += "return nil\n}\n\n"
ret = name
s.outputStructCount++
}
if !nonNull {
ret = "*" + ret
}
}
return ret, nil
}
func generateTypeDef(name, original string) string {
ret := "type " + name + " " + original + "\n\n"
if !strings.ContainsAny(original, "* \n") {
ret += `
func (t *` + name + `) UnmarshalJSON(b []byte) error {
return (*` + original + `)(t).UnmarshalJSON(b)
}
`
}
return ret
}
func (s *generateState) processQuery(q string) []error {
var ret []error
doc, errs := graphql.ParseAndValidate(q, s.schema, nil)
if len(errs) > 0 {
for _, err := range errs {
ret = append(ret, err)
}
return ret
}
fragTypes := map[string]string{}
for _, op := range doc.Definitions {
if def, ok := op.(*ast.FragmentDefinition); ok {
fragTypes[def.Name.Name] = def.TypeCondition.Name.Name
}
}
for _, op := range doc.Definitions {
switch op := op.(type) {
case *ast.OperationDefinition:
t := s.schema.QueryType()
if op.OperationType != nil {
switch op.OperationType.Value {
case "mutation":
t = s.schema.MutationType()
case "subscription":
t = s.schema.SubscriptionType()
}
}
if op.Name != nil {
gen, err := s.generateType(t, op.SelectionSet.Selections, true, fragTypes)
if err != nil {
ret = append(ret, err)
continue
}
s.output += generateTypeDef(op.Name.Name+"Data", gen)
}
case *ast.FragmentDefinition:
if op.Name != nil {
gen, err := s.generateType(s.schema.NamedTypes()[op.TypeCondition.Name.Name], op.SelectionSet.Selections, true, fragTypes)
if err != nil {
ret = append(ret, err)
continue
}
s.output += generateTypeDef(op.Name.Name+"Fragment", gen)
}
}
}
return ret
}
func (s *generateState) processFile(path string) []error {
source, err := ioutil.ReadFile(path)
if err != nil {
return []error{err}
}
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "", source, 0)
if err != nil {
return []error{fmt.Errorf("parse error: %w", err)}
}
var errs []error
goast.Inspect(f, func(node goast.Node) bool {
switch node := node.(type) {
case *goast.CallExpr:
if ident, ok := node.Fun.(*goast.Ident); !ok || ident.Name != s.wrapper {
return true
} else if len(node.Args) != 1 {
errs = append(errs, fmt.Errorf("%v: expected 1 argument to %v", fset.Position(node.Lparen), s.wrapper))
} else if lit, ok := node.Args[0].(*goast.BasicLit); !ok || lit.Kind != token.STRING {
errs = append(errs, fmt.Errorf("%v: %v argument must be a string literal", fset.Position(node.Args[0].Pos()), s.wrapper))
} else if q, err := strconv.Unquote(lit.Value); err != nil {
errs = append(errs, fmt.Errorf("%v: error parsing argument: %w", fset.Position(node.Args[0].Pos()), err))
} else {
for _, err := range s.processQuery(q) {
errs = append(errs, fmt.Errorf("%v: %w", fset.Position(node.Args[0].Pos()), err))
}
}
}
return true
})
return errs
}
func Generate(schema *schema.Schema, pkg string, inputGlobs []string, wrapper, jsonPackage string) (string, []error) {
state := &generateState{
schema: schema,
wrapper: wrapper,
outputEnums: map[string]struct{}{},
}
var errs []error
for _, glob := range inputGlobs {
matches, err := filepath.Glob(glob)
if err != nil {
errs = append(errs, err)
continue
}
for _, match := range matches {
for _, err := range state.processFile(match) {
errs = append(errs, fmt.Errorf("%v: %w", match, err))
}
}
}
if len(errs) > 0 {
return "", errs
}
tmp := state.output
state.output = "package " + pkg + "\n\n"
if state.requiresJSONImport {
if !strings.HasSuffix(jsonPackage, "/json") {
state.output += fmt.Sprintf("import json %#v\n\n", jsonPackage)
} else {
state.output += fmt.Sprintf("import %#v\n\n", jsonPackage)
}
}
state.output += tmp
out, err := format.Source([]byte(state.output))
if err != nil {
return "", []error{fmt.Errorf("error formatting result: %w", err)}
}
return string(out), nil
}
func LoadSchema(path string) (*schema.Schema, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
var result struct {
Data struct {
Schema introspection.SchemaData `json:"__schema"`
}
}
if err := json.NewDecoder(f).Decode(&result); err != nil {
return nil, err
}
def, err := result.Data.Schema.GetSchemaDefinition()
if err != nil {
return nil, err
}
ret, err := schema.New(def)
if err != nil {
return nil, err
}
for k, v := range introspection.MetaFields {
ret.QueryType().Fields[k] = v
}
return ret, nil
}
func Run(w io.Writer, args ...string) []error {
flags := pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)
pkg := flags.String("pkg", "", "the package name of the generated output")
input := flags.StringArrayP("input", "i", nil, "the input files to search")
schemaPath := flags.String("schema", "", "the path to the schema json file")
wrapper := flags.String("wrapper", "gql", "the wrapper name to look for")
json := flags.String("json", "encoding/json", "the json encoding package to import")
flags.Parse(args)
if *pkg == "" {
return []error{fmt.Errorf("the --pkg flag is required")}
}
if *schemaPath == "" {
return []error{fmt.Errorf("the --schema flag is required")}
}
schema, err := LoadSchema(*schemaPath)
if err != nil {
return []error{fmt.Errorf("error loading schema: %w", err)}
}
output, errs := Generate(schema, *pkg, *input, *wrapper, *json)
if len(errs) > 0 {
return errs
}
fmt.Fprint(w, output)
return nil
}
func main() {
if errs := Run(os.Stdout, os.Args[1:]...); len(errs) > 0 {
for _, err := range errs {
fmt.Fprintln(os.Stderr, err.Error())
}
os.Exit(1)
}
}