-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsvgen.go
410 lines (367 loc) · 10.4 KB
/
csvgen.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
package main
import (
"fmt"
. "github.com/dave/jennifer/jen"
"github.com/karantin2020/cli"
"github.com/karantin2020/csvgen/parser"
"os"
"path/filepath"
"strings"
)
var (
// Config vars
pkg string
subpkg string
out string
fname string
parseEmpty bool
marshal bool
unmarshal bool
fInfo os.FileInfo
// Package vars
pkgCnt string
f *File
p = parser.Parser{AllStructs: true}
)
const fieldPrefix = "um"
func main() {
flags := cli.New("This app generates csv Marshall and Unmarshal functions", "0.1.2")
flags.StringVarP(&pkg, "pkg", "p", "", "output package")
flags.StringVarP(&subpkg, "subpkg", "s", "", "output subpkg name")
flags.StringVarP(&fname, "fname", "f", "", "input file")
flags.StringVarP(&out, "out", "o", "", "output file")
flags.BoolVarP(&parseEmpty, "parseempty", "e", false, "parse empty fields with values: '', 0, 0.0, false. Default: false")
flags.BoolVarP(&marshal, "marshal", "m", true, "generate MarshalCSV or not")
flags.BoolVarP(&unmarshal, "unmarshal", "u", true, "generate UnmarshalCSV or not")
flags.Parse()
pkgCnt = "main"
if pkg != "" {
pkgCnt = pkg
}
if subpkg != "" {
pkgCnt = subpkg
pkg = ""
}
if fname == "" {
fmt.Println("didn't pass source file to parse")
os.Exit(1)
}
var err error
if fname, err = filepath.Abs(fname); err != nil {
fmt.Println("Couldn't find Abs path of input.", err)
os.Exit(1)
}
if fInfo, err = os.Stat(fname); err != nil {
fmt.Println("Couldn't find source file to parse.", err)
os.Exit(1)
}
WriteString(pkgCnt)
}
// WriteString is high level function that parses source
// and generates output code
func WriteString(pkgCnt string) {
if err := p.Parse(fname, fInfo.IsDir()); err != nil {
return
}
if out == "" {
subpkg = ""
if fInfo.IsDir() {
out = filepath.Join(fname, p.PkgName+"_csvgen.go")
} else {
if s := strings.TrimSuffix(fname, ".go"); s == fname {
// return errors.New("Filename must end in '.go'")
fmt.Println("Filename must end in '.go'")
os.Exit(1)
} else {
out = s + "_csvgen.go"
}
}
pkgCnt = p.PkgName
} else {
if s := strings.TrimSuffix(out, ".go"); s == out {
out = out + ".go"
}
}
if subpkg != "" {
if _, err := os.Stat(subpkg); os.IsNotExist(err) {
fmt.Println(subpkg, "not exists. Trying to make directory")
if err := os.Mkdir(subpkg, os.ModePerm); err != nil {
fmt.Println("Couldn't make directory. Got an error:", err)
os.Exit(1)
}
}
}
f = NewFile(pkgCnt)
f.Comment("This code is generated by 'csvgen'")
f.Comment("Do not edit")
f.Line()
GenerateCode()
// fmt.Println(p.Error)
// fmt.Println(p.StructMap)
// fmt.Printf("%#v", f)
if err := f.Save(filepath.Join(subpkg, out)); err != nil {
fmt.Println("Couldn't save file. Got an error:", err)
os.Exit(1)
}
}
// GenerateCode generates code for every structure from input
func GenerateCode() {
for _, v := range p.Structs {
GenerateFuncs(v)
f.Line()
}
}
// GenerateFuncs processes every structure.
// Generated functions MarshalCSV and UnmarshalCSV process builtin types,
// call MarshalCSV and UnmarshalCSV for custom types
// and process pointer types assuming that pointers were initiated (memory is
// allocated).
// So the best way is to verify data structures before marshalling
// and unmarshalling for null pointers to prevent SEGFAULT
func GenerateFuncs(vstr parser.StructInfo) {
// func (pv *Type) UnmarshalCSV(in []string) error {
// if in == nil || len(in) < 2 {
// return errors.New("Invalid input to UnmarshalCSV")
// }
// unm_b, err := strconv.ParseBool(in[0])
// if err != nil {
// return err
// }
// pv.b = b
// unm_a, err := strconv.ParseInt(in[1], 10, 64)
// if err == nil {
// return err
// }
// this.a = a
// }
//
// // func (this Type) MarshalCSV() []string {
// out := []string{}
// out = append(out, strconv.FormatInt(int64(this.a), 10))
// out = append(out, strconv.FormatBool(this.b))
// ...marshal logic
// return out, nil
// }
var unmarshallBody []Code
var marshallBody []Code
chkError := If(
Id("in").Op("==").Id("nil").Op("||").Id("len").Call(Id("in")).Op("<").Lit(len(vstr.Fields)),
).Block(
Return().Qual("github.com/pkg/errors", "New").Call(Lit("Invalid input to *" + vstr.Name + " UnmarshalCSV")),
)
unmarshallBody = append(unmarshallBody, chkError)
unmarshallBody = append(unmarshallBody, Id("i").Op(":=").Lit(0))
marshallBody = append(marshallBody, Id("out").Op(":=").Index().String().Values())
for ik, istr := range vstr.Fields {
var g []Code
var j *Statement
star := ""
ttype := istr.Type
if istr.Type[0] == '*' {
star = "*"
ttype = istr.Type[1:]
}
unmarshallBody = append(unmarshallBody, nilCheck(star, istr.Name, istr.Type, false))
marshallBody = append(marshallBody, nilCheck(star, istr.Name, istr.Type, true))
switch ttype {
case "bool":
op := Qual("strconv", "ParseBool").Call(Id("in").Index(Id("i")))
g = parseField(star, istr.Name, ttype, op, "false")
j = marshalBody(Qual("strconv", "FormatBool").Call(Op(star).Id("pv").Op(".").Id(istr.Name)))
case "float32":
fallthrough
case "float64":
op := Qual("strconv", "ParseFloat").Call(List(Id("in").Index(Id("i")), Id(ttype[5:])))
g = parseField(star, istr.Name, ttype, op, "0.0")
j = marshalBody(Qual("strconv", "FormatFloat").
Call(Op("float64").Call(Op(star).Id("pv").Op(".").Id(istr.Name)),
LitRune('f'), Lit(-1), Id(ttype[5:])),
)
case "int":
fallthrough
case "int8":
fallthrough
case "int16":
fallthrough
case "int32":
fallthrough
case "int64":
bn := ttype[3:]
if bn == "" {
bn = "0"
}
op := Qual("strconv", "ParseInt").Call(List(Id("in").Index(Id("i")), Lit(10), Id(bn)))
g = parseField(star, istr.Name, ttype, op, "0")
j = marshalBody(Qual("strconv", "FormatInt").
Call(Op("int64").Call(Op(star).Id("pv").Op(".").Id(istr.Name)), Lit(10)),
)
case "uint":
fallthrough
case "uint8":
fallthrough
case "uint16":
fallthrough
case "uint32":
fallthrough
case "uint64":
bn := ttype[4:]
if bn == "" {
bn = "0"
}
op := Qual("strconv", "ParseUint").Call(List(Id("in").Index(Id("i")), Lit(10), Id(bn)))
g = parseField(star, istr.Name, ttype, op, "0")
j = marshalBody(Qual("strconv", "FormatUint").
Call(Op("uint64").Call(Op(star).Id("pv").Op(".").Id(istr.Name)), Lit(10)),
)
case "string":
g = []Code{
Op(star).Id("pv").Op(".").Id(istr.Name).Op("=").Id("in").Index(Id("i")),
}
j = marshalBody(Op(star).Id("pv").Op(".").Id(istr.Name))
default:
// By default generated code calls 'func (this *Type) UnmarshalCSV(s string) error'
g = []Code{
If(
Err().Op(":=").Id("pv").Op(".").Id(istr.Name).Op(".").Id("UnmarshalCSV").
Call(Id("in").Index(Id("i"))),
Err().Op("!=").Nil(),
).Block(
Return().Err(),
),
}
// By default generated code calls 'func (this Type) MarshalCSV() (string, error)'
j = If(
List(Id("mt"), Err()).Op(":=").Id("pv").Op(".").Id(istr.Name).Op(".").Id("MarshalCSV").
Call(),
Err().Op("!=").Nil(),
).Block(
Return(Id("out"), Err()),
).Else().Block(
marshalBody(Id("mt")),
)
}
unmarshallBody = append(unmarshallBody, g...)
marshallBody = append(marshallBody, j)
if ik != (len(vstr.Fields) - 1) {
unmarshallBody = append(unmarshallBody, Id("i").Op("++"))
} else {
unmarshallBody = append(unmarshallBody, Return().Id("nil"))
marshallBody = append(marshallBody, Return().List(Id("out"), Id("nil")))
}
}
if unmarshal {
f.Comment("UnmarshalCSV " + vstr.Name + " func")
f.Func().Params(
Id("pv").Op("*").Id(vstr.Name),
).Id("UnmarshalCSV").Params(
Id("in").Index().String(),
).Id("error").Block(
unmarshallBody...,
)
f.Line()
}
if marshal {
f.Comment("MarshalCSV " + vstr.Name + " func")
f.Func().Params(
Id("pv").Id(vstr.Name),
).Id("MarshalCSV").Params().
Parens(Index().String().Op(",").Id("error")).Block(
marshallBody...,
)
}
if unmarshal {
AddList(vstr)
}
}
func parseField(star string, fieldName string, fieldType string, op *Statement, defv string) []Code {
fldNm := fieldPrefix + strings.Title(fieldName)
parseBlock := []Code{
List(Id(fldNm), Err()).Op(":=").Add(op),
If(
Err().Op("!=").Nil(),
).Block(
Return().Err(),
),
}
var conv *Statement
// Check for float and int
if fieldType[len(fieldType)-2:] != "64" {
conv = Id(fieldType).Call(Id(fldNm))
} else {
conv = Id(fldNm)
}
parseBlock = append(parseBlock, Op(star).Id("pv").Op(".").Id(fieldName).Op("=").Add(conv))
// Parse empty string with type rules
// if in[i] == "" {
// pv.Pp = 0
// } else {
// ...
// }
if parseEmpty {
parseBlock = []Code{
If(
Id("in").Index(Id("i")).Op("==").Lit(""),
).Block(
Op(star).Id("pv").Op(".").Id(fieldName).Op("=").Id(defv),
).Else().Block(
parseBlock...,
),
}
}
return parseBlock
}
func marshalBody(typeRes *Statement) *Statement {
return Id("out").Op("=").Append(Id("out"), Add(typeRes))
}
func nilCheck(star string, iname, itype string, marshall bool) *Statement {
var s, t *Statement
if marshall {
t = List(Id("out"), Qual("github.com/pkg/errors", "New").Call(Lit("nil pointer found at "+iname+" "+itype)))
} else {
t = Qual("github.com/pkg/errors", "New").Call(Lit("nil pointer found at " + iname + " " + itype))
}
if star == "*" {
s = If(
Id("pv").Op(".").Id(iname).Op("==").Id("nil"),
).Block(
Return().Add(t),
)
} else {
s = Null()
}
return s
}
func AddList(vstr parser.StructInfo) {
// type FooList []Foo
// func (pl *FooList) Push(in []string) error {
// nf := Foo{}
// if err := nf.UnmarshalCSV(in); err != nil {
// return errors.Wrap(err, "Error in UnmarshalCSV Foo")
// }
// *pl = append(*pl, nf)
// return nil
// }
f.Line()
f.Comment(vstr.Name + "List csvparse.Pusher implementation")
f.Type().Id(vstr.Name + "List").Index().Id(vstr.Name)
f.Line()
f.Comment("Push function for " + vstr.Name + "List struct")
f.Func().Params(
Id("pl").Op("*").Id(vstr.Name+"List"),
).Id("Push").Params(Id("in").Index().String()).
Parens(Error()).Block(
Id("nf").Op(":=").Id(vstr.Name).Values(),
If(
Err().Op(":=").Id("nf").Op(".").Id("UnmarshalCSV").Call(Id("in")),
Err().Op("!=").Nil(),
).Block(
Return(Qual("github.com/pkg/errors", "Wrapf").Call(
Err(),
Lit("Error in UnmarshalCSV "+vstr.Name+" in line %#v "),
Id("in")),
),
),
Op("*").Id("pl").Op("=").Append(Op("*").Id("pl"), Id("nf")),
Return(Id("nil")),
)
}