forked from achiku/prmdg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
214 lines (194 loc) · 5.27 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
package main
import (
"bytes"
"fmt"
"go/format"
"io"
"log"
"os"
"os/exec"
"sort"
schema "github.com/lestrrat-go/jsschema"
"github.com/lestrrat-go/jsval"
"github.com/pkg/errors"
kingpin "gopkg.in/alecthomas/kingpin.v2"
)
var (
app = kingpin.New("prmdg", "prmd generated JSON Hyper Schema to Go")
pkg = app.Flag("package", "package name for Go file").Default("main").Short('p').String()
fp = app.Flag("file", "path JSON Schema").Required().Short('f').String()
op = app.Flag("output", "path to Go output file").Short('o').String()
structCmd = app.Command("struct", "generate struct file")
jsValCmd = app.Command(
"jsval", "generate validator file using github.com/lestrrat-go/go-jsval")
validatorCmd = app.Command(
"validator", "generate validator file using github.com/go-playground/validator")
scValidator = structCmd.Flag("validate-tag", "add `validate` tag to struct").Bool()
scUseTitle = structCmd.Flag("use-title", "use title tag in request/response struct name").Bool()
scNullable = structCmd.Flag("nullable", "use github.com/guregu/null for null value").Bool()
version string
)
func init() {
kingpin.Version(version)
}
func main() {
cmd := kingpin.MustParse(app.Parse(os.Args[1:]))
var (
in io.Reader
out io.Writer
err error
)
if *op != "" {
out, err = os.Create(*op)
if err != nil {
app.Errorf("failed to create output file %s: %s", *op, err)
}
} else {
out = os.Stdout
}
in, err = os.Open(*fp)
if err != nil {
app.Errorf("failed to open input file %s: %s", *fp, err)
}
switch cmd {
case structCmd.FullCommand():
if err := generateStructFile(pkg, in, out, *scValidator, *scUseTitle, *scNullable); err != nil {
app.Errorf("failed to generate struct file: %s", err)
}
case jsValCmd.FullCommand():
if err := generateJsValValidatorFile(pkg, in, out); err != nil {
app.Errorf("failed to generate jsval validator file: %s", err)
}
case validatorCmd.FullCommand():
if err := generateValidatorFile(pkg, in, out); err != nil {
app.Errorf("failed to generate validator file: %s", err)
}
}
if *op != "" {
params := []string{"-w", *op}
if err := exec.Command("goimports", params...).Run(); err != nil {
app.Errorf("failed to goimports: %s", err)
}
}
}
func generateValidatorFile(pkg *string, fp io.Reader, op io.Writer) error {
sc, err := schema.Read(fp)
if err != nil {
log.Printf("%s", err)
return errors.Wrapf(err, "failed to read %s", fp)
}
parser := NewParser(sc, *pkg)
vals, err := parser.ParseValidators()
if err != nil {
return err
}
var src []byte
src = append(src, []byte(fmt.Sprintf("package %s\n\n", *pkg))...)
ss, err := format.Source(vals.Render())
if err != nil {
return err
}
src = append(src, ss...)
if _, err := op.Write(src); err != nil {
return err
}
return nil
}
func generateStructFile(pkg *string, fp io.Reader, op io.Writer, val, useTitle, nullable bool) error {
sc, err := schema.Read(fp)
if err != nil {
return errors.Wrapf(err, "failed to read %s", fp)
}
parser := NewParser(sc, *pkg)
resources, err := parser.ParseResources()
if err != nil {
return err
}
links, err := parser.ParseActions(resources)
if err != nil {
return err
}
var src []byte
src = append(src, []byte(fmt.Sprintf("package %s\n\n", *pkg))...)
var resKeys []string
for key := range resources {
resKeys = append(resKeys, key)
}
stOpt := FormatOption{
Validator: val,
Schema: false,
UseTitle: useTitle,
UseNull: nullable,
}
sort.Strings(resKeys)
for _, k := range resKeys {
res := resources[k]
ss, err := format.Source(res.Struct(stOpt))
if err != nil {
return errors.Wrapf(err, "failed to format resource: %s: %s", res.Name, res.Title)
}
src = append(src, ss...)
}
var linkKeys []string
for key := range links {
linkKeys = append(linkKeys, key)
}
sort.Strings(linkKeys)
for _, k := range linkKeys {
actions := links[k]
for _, action := range actions {
var reqOpt FormatOption
switch {
case action.Method == "GET" || action.Encoding == "application/x-www-form-urlencoded":
reqOpt = FormatOption{
Validator: val,
Schema: true,
UseTitle: useTitle,
UseNull: nullable,
}
default:
reqOpt = FormatOption{
Validator: val,
Schema: false,
UseTitle: useTitle,
UseNull: nullable,
}
}
req, err := format.Source(action.RequestStruct(reqOpt))
if err != nil {
return errors.Wrapf(err, "failed to format request struct: %s, %s", k, action.Href)
}
src = append(src, req...)
resp, err := format.Source(action.ResponseStruct(reqOpt))
if err != nil {
return errors.Wrapf(err, "failed to format response struct: %s, %s", k, action.Href)
}
src = append(src, resp...)
}
}
if _, err := op.Write(src); err != nil {
return err
}
return nil
}
func generateJsValValidatorFile(pkg *string, fp io.Reader, op io.Writer) error {
sc, err := schema.Read(fp)
if err != nil {
return errors.Wrapf(err, "failed to read %s", fp)
}
parser := NewParser(sc, *pkg)
validators, err := parser.ParseJsValValidators()
if err != nil {
return err
}
generator := jsval.NewGenerator()
var src bytes.Buffer
fmt.Fprintf(&src, "package %s\n", *pkg)
if err := generator.Process(&src, validators...); err != nil {
return err
}
if _, err := op.Write(src.Bytes()); err != nil {
return err
}
return nil
}