-
Notifications
You must be signed in to change notification settings - Fork 7
/
shiftgen.go
346 lines (300 loc) · 8.37 KB
/
shiftgen.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
// Command shiftgen generates method receivers functions for structs to implement
// shift Inserter and Updater interfaces. The implementations insert and update
// rows in mysql.
//
// Note shiftgen does not support generating GetMetadata functions for
// MetadataInserter or MetadataUpdater since it is orthogonal to inserting
// and updating domain entity rows.
//
// Usage:
// //go:generate shiftgen -table=model_table -inserter=InsertReq -updaters=UpdateReq,CompleteReq
package main
import (
"bytes"
"flag"
"go/ast"
"go/parser"
"go/token"
"io"
"log"
"os"
"path"
"reflect"
"regexp"
"strings"
"text/template"
"github.com/luno/jettison/errors"
"github.com/luno/jettison/j"
"golang.org/x/tools/imports"
)
// Tag is the shiftgen struct tag that should be used to override sql column names
// for struct fields (the default is snake case of the field name).
//
// Ex `shift:"custom_col_name"`.
const Tag = "shift"
const tagPrefix = "`" + Tag + ":"
// idFieldName is the name of the field in the Go struct used for the table's ID
// TODO: Support custom ID field name.
const idFieldName = "ID"
var (
updaters = flag.String("updaters", "",
"The struct types (comma seperated) to generate Update methods for")
inserter = flag.String("inserter", "",
"The struct type to generate a Insert method for")
inserters = flag.String("inserters", "",
"The ArcFSM struct types (comma seperated) to generate Insert methods for")
table = flag.String("table", "",
"The sql table name to insert and update")
statusField = flag.String("status_field", "status",
"The sql column in the table containing the status")
outFile = flag.String("out", "shift_gen.go",
"output filename")
quoteChar = flag.String("quote_char", "`",
"Character to use when quoting column names")
mermaid = flag.Bool("mermaid", true,
"Generate mermaid state machine diagram")
mermaidOut = flag.String("mermaid_out", "shift_gen.mmd",
"Output filename for mermaid state machine diagram")
)
var ErrIDTypeMismatch = errors.New("Inserters and updaters' ID fields should have matching types", j.C("ERR_3db87b866daeda57"))
type Field struct {
Name string
Col string
}
type Struct struct {
Table string
Type string
StatusField string
Fields []Field
CustomCreatedAt bool
CustomUpdatedAt bool
HasID bool
// IDType is the type of the ID field
IDType string
}
func (s Struct) IDZeroValue() string {
switch s.IDType {
case "string":
return `""`
case "int64":
return `0`
}
return ``
}
type Data struct {
Package string
GenSource string
Updaters []Struct
Inserters []Struct
}
func main() {
flag.Parse()
ii, err := parseInserters()
if err != nil {
log.Fatal(err)
}
uu := parseUpdaters()
pwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
filePath := path.Join(pwd, *outFile)
src, err := generateSrc(pwd, *table, ii, uu, *statusField, filePath)
if err != nil {
log.Fatal(err)
}
if err = os.WriteFile(filePath, src, 0o644); err != nil {
log.Fatal(errors.Wrap(err, "Error writing file"))
}
if *mermaid {
mermaidFilePath := path.Join(pwd, *mermaidOut)
mmd, err := generateMermaidDiagram(pwd)
if err != nil {
log.Fatal(err)
}
if err = os.WriteFile(mermaidFilePath, []byte(mmd), 0o644); err != nil {
log.Fatal(errors.Wrap(err, "Error writing file"))
}
}
}
func parseInserters() ([]string, error) {
if *inserter != "" && *inserters != "" {
return nil, errors.New("Either define inserter or inserters, not both")
}
var ii []string
if *inserter != "" {
ii = append(ii, *inserter)
} else if strings.TrimSpace(*inserters) != "" {
for _, i := range strings.Split(*inserters, ",") {
ii = append(ii, strings.TrimSpace(i))
}
}
return ii, nil
}
func parseUpdaters() []string {
var uu []string
if strings.TrimSpace(*updaters) != "" {
for _, u := range strings.Split(*updaters, ",") {
uu = append(uu, strings.TrimSpace(u))
}
}
return uu
}
func generateSrc(pkgPath, table string, inserters, updaters []string, statusField, filePath string) ([]byte, error) {
if table == "" {
return nil, errors.New("No table specified")
}
if len(inserters) == 0 && len(updaters) == 0 {
return nil, errors.New("No inserter or updaters specified")
}
fs := token.NewFileSet()
asts, err := parser.ParseDir(fs, pkgPath, nil, 0)
if err != nil {
return nil, err
}
data := Data{
GenSource: os.Getenv("GOFILE") + ":" + os.Getenv("GOLINE"),
}
ins := make(map[string]bool, len(inserters))
for _, i := range inserters {
ins[i] = true
}
ups := make(map[string]bool, len(updaters))
for _, u := range updaters {
ups[u] = true
}
for p, a := range asts {
var inspectErr error
ast.Inspect(a, func(n ast.Node) bool {
if inspectErr != nil {
return false
}
t, ok := n.(*ast.TypeSpec)
if !ok {
return true
}
typ := t.Name.Name
isU, firstU := ups[typ]
isI, firstI := ins[typ]
if !isU && !isI {
return true
}
if isU && !firstU {
log.Fatalf("Found multiple updater struct definitions: %s", typ)
}
if isI && !firstI {
log.Fatalf("Found multiple inserter struct definitions: %s", typ)
}
if data.Package != "" && data.Package != p {
inspectErr = errors.New("Struct types defined in separate packages")
}
data.Package = p
s, ok := t.Type.(*ast.StructType)
if !ok {
inspectErr = errors.New("Inserter/updater must be a struct type", j.MKV{"name": typ})
}
st := Struct{Type: typ, Table: table, StatusField: statusField, IDType: "int64"}
for _, f := range s.Fields.List {
if len(f.Names) == 0 {
inspectErr = errors.New("Inserter/updater, but has anonymous field (maybe shift.Reflect)", j.MKV{"name": typ})
}
if len(f.Names) != 1 {
inspectErr = errors.New("Inserter/updaters, but one field multiple names: %v", j.MKV{"name": typ, "field_names": f.Names})
}
name := f.Names[0].Name
if name == idFieldName {
st.HasID = true
if ti, ok := f.Type.(*ast.Ident); !ok {
inspectErr = errors.New("ID field should be of type int64 or string")
} else {
st.IDType = ti.Name
}
// Skip ID fields for updaters (since they are hardcoded)
continue
}
col := toSnakeCase(name)
if f.Tag != nil && strings.HasPrefix(f.Tag.Value, tagPrefix) {
col = reflect.StructTag(f.Tag.Value[1 : len(f.Tag.Value)-1]).Get(Tag) // Delete first and last quotation
}
if col == "created_at" {
st.CustomCreatedAt = true
}
if col == "updated_at" {
st.CustomUpdatedAt = true
}
field := Field{
Col: col,
Name: name,
}
st.Fields = append(st.Fields, field)
}
if isU {
if !st.HasID {
inspectErr = errors.New("Updater must contain ID field", j.MKV{"field": typ})
}
data.Updaters = append(data.Updaters, st)
ups[typ] = false
} else {
data.Inserters = append(data.Inserters, st)
ins[typ] = false
}
return true
})
if inspectErr != nil {
return nil, inspectErr
}
}
for in, missing := range ins {
if missing {
return nil, errors.New("Couldn't find inserter", j.MKV{"name": in})
}
}
for up, missing := range ups {
if missing {
return nil, errors.New("Couldn't find updater", j.MKV{"name": up})
}
}
if err = ensureMatchingIDType(data.Inserters, data.Updaters); err != nil {
return nil, err
}
var out bytes.Buffer
if err = execTpl(&out, tpl, data); err != nil {
return nil, errors.Wrap(err, "Failed executing template")
}
return imports.Process(filePath, out.Bytes(), nil)
}
func execTpl(out io.Writer, tpl string, data Data) error {
t := template.New("").Funcs(map[string]interface{}{
"col": quoteCol,
})
tp, err := t.Parse(tpl)
if err != nil {
return err
}
return tp.Execute(out, data)
}
func quoteCol(colName string) string {
return *quoteChar + colName + *quoteChar
}
// ensureMatchingIDType returns an error if any of the inserters or updates have
// a different type for their ID.
func ensureMatchingIDType(inserters, updaters []Struct) error {
var idType string
for _, s := range append(inserters, updaters...) {
if idType == "" {
idType = s.IDType
} else if idType != s.IDType {
return ErrIDTypeMismatch
}
}
return nil
}
var (
matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)")
matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])")
)
func toSnakeCase(col string) string {
snake := matchFirstCap.ReplaceAllString(col, "${1}_${2}")
snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}")
return strings.ToLower(snake)
}