-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathgen.go
More file actions
75 lines (67 loc) · 1.63 KB
/
gen.go
File metadata and controls
75 lines (67 loc) · 1.63 KB
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
package json
import (
"bytes"
"context"
ejson "encoding/json"
"fmt"
"google.golang.org/protobuf/encoding/protojson"
"github.com/sqlc-dev/sqlc/internal/plugin"
)
func parseOptions(req *plugin.CodeGenRequest) (*plugin.JSONCode, error) {
if req.Settings == nil {
return new(plugin.JSONCode), nil
}
if req.Settings.Codegen != nil {
if len(req.Settings.Codegen.Options) != 0 {
var options *plugin.JSONCode
dec := ejson.NewDecoder(bytes.NewReader(req.Settings.Codegen.Options))
dec.DisallowUnknownFields()
if err := dec.Decode(&options); err != nil {
return options, fmt.Errorf("unmarshalling options: %s", err)
}
return options, nil
}
}
if req.Settings.Json != nil {
return req.Settings.Json, nil
}
return new(plugin.JSONCode), nil
}
func Generate(ctx context.Context, req *plugin.CodeGenRequest) (*plugin.CodeGenResponse, error) {
options, err := parseOptions(req)
if err != nil {
return nil, err
}
indent := " "
if options.Indent != "" {
indent = options.Indent
}
filename := "codegen_request.json"
if options.Filename != "" {
filename = options.Filename
}
// The output of protojson has randomized whitespace
// https://github.com/golang/protobuf/issues/1082
m := &protojson.MarshalOptions{
EmitUnpopulated: true,
Indent: "",
UseProtoNames: true,
}
data, err := m.Marshal(req)
if err != nil {
return nil, err
}
var rm ejson.RawMessage = data
blob, err := ejson.MarshalIndent(rm, "", indent)
if err != nil {
return nil, err
}
return &plugin.CodeGenResponse{
Files: []*plugin.File{
{
Name: filename,
Contents: append(blob, '\n'),
},
},
}, nil
}