-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerator.go
404 lines (336 loc) · 11.1 KB
/
generator.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
package elasticsearch2go
import (
"bytes"
"encoding/json"
"fmt"
"log"
"os"
"sort"
"strings"
"text/template"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
type Property struct {
Type string `json:"type"`
Properties map[string]Property `json:"properties,omitempty"`
}
type Mappings struct {
Properties map[string]Property `json:"properties"`
}
type ElasticsearchMapping struct {
Mappings Mappings `json:"mappings"`
}
// generatorOptions defines the optional parameters for the GenerateDatamodel function.
type GeneratorOptions struct {
InitClassName *string
TypeMappingPath *string
ExceptionFieldPath *string
ExceptionTypePath *string
SkipFieldPath *string
FieldCommentPath *string
TmplPath *string
}
const structTemplateWithWrapper = `// Code generated by github.com/taniiicom/elasticsearch2go. DO NOT EDIT.
// Code generated by github.com/taniiicom/elasticsearch2go. DO NOT EDIT.
// Code generated by github.com/taniiicom/elasticsearch2go. DO NOT EDIT.
package {{.PackageName}}
type {{.InitClassName}} struct {
{{.StructName}}
}
{{.StructDefinitions}}
`
const structTemplateWithoutWrapper = `// Code generated by github.com/taniiicom/elasticsearch2go. DO NOT EDIT.
// Code generated by github.com/taniiicom/elasticsearch2go. DO NOT EDIT.
// Code generated by github.com/taniiicom/elasticsearch2go. DO NOT EDIT.
package {{.PackageName}}
{{.StructDefinitions}}
`
type Field struct {
FieldName string
FieldType string
JSONName string
FieldComment string
}
type StructData struct {
PackageName string
InitClassName string
StructName string
StructDefinitions string
}
// GoTypeMap holds the mapping from Elasticsearch types to Go types.
var GoTypeMap map[string]string
var FieldExceptions map[string]string
var TypeExceptions map[string]string
var SkipFields map[string]bool
var FieldComments map[string]string
// StructNameTracker to avoid generating duplicate struct names
var StructNameTracker map[string]bool
func GenerateDatamodel(inputPath, outputPath, packageName, structName string, opts *GeneratorOptions) error {
// check for required fields
if inputPath == "" || outputPath == "" || structName == "" || packageName == "" {
return fmt.Errorf("inputPath, outputPath, structName, and packageName must be specified")
}
// initialize StructNameTracker
StructNameTracker = make(map[string]bool)
// load custom type mapping if provided
if opts != nil && opts.TypeMappingPath != nil && *opts.TypeMappingPath != "" {
loadTypeMapping(*opts.TypeMappingPath)
} else {
// default mapping
GoTypeMap = map[string]string{
"integer": "*uint64",
"float": "*float64",
"boolean": "bool",
"text": "*string",
"keyword": "*string",
"date": "*time.Time",
"geo_point": "*GeoPoint",
"object": "*map[string]interface{}",
"nested": "[]interface{}",
}
}
// load field exceptions if provided
if opts != nil && opts.ExceptionFieldPath != nil && *opts.ExceptionFieldPath != "" {
loadFieldExceptions(*opts.ExceptionFieldPath)
} else {
FieldExceptions = make(map[string]string)
}
// load type exceptions if provided
if opts != nil && opts.ExceptionTypePath != nil && *opts.ExceptionTypePath != "" {
loadTypeExceptions(*opts.ExceptionTypePath)
} else {
TypeExceptions = make(map[string]string)
}
// load skip fields if provided
if opts != nil && opts.SkipFieldPath != nil && *opts.SkipFieldPath != "" {
loadSkipFields(*opts.SkipFieldPath)
} else {
SkipFields = make(map[string]bool)
}
// load field comments if provided
if opts != nil && opts.FieldCommentPath != nil && *opts.FieldCommentPath != "" {
loadFieldComments(*opts.FieldCommentPath)
} else {
FieldComments = make(map[string]string)
}
// load custom template if provided
var tmpl *template.Template
var err error
if opts != nil && opts.TmplPath != nil && *opts.TmplPath != "" {
tmpl, err = template.ParseFiles(*opts.TmplPath)
if err != nil {
return fmt.Errorf("Failed to load template file %s: %v", *opts.TmplPath, err)
}
} else {
// choose default template based on the presence of InitClassName
if opts != nil && opts.InitClassName != nil && *opts.InitClassName != "" {
tmpl, err = template.New("structWithWrapper").Parse(structTemplateWithWrapper)
} else {
tmpl, err = template.New("structWithoutWrapper").Parse(structTemplateWithoutWrapper)
}
if err != nil {
return fmt.Errorf("Error parsing template: %v", err)
}
}
return processFile(inputPath, outputPath, packageName, structName, opts, tmpl)
}
func processFile(inputPath, outputPath, packageName, structName string, opts *GeneratorOptions, tmpl *template.Template) error {
data, err := os.ReadFile(inputPath)
if err != nil {
return fmt.Errorf("Failed to read file %s: %v", inputPath, err)
}
var esMapping ElasticsearchMapping
err = json.Unmarshal(data, &esMapping)
if err != nil {
return fmt.Errorf("Error unmarshalling JSON from file %s: %v", inputPath, err)
}
structDefinitions := generateStructDefinitions(structName, esMapping.Mappings.Properties)
var initClassName string
if opts != nil && opts.InitClassName != nil {
initClassName = *opts.InitClassName
}
structData := StructData{
PackageName: packageName,
InitClassName: initClassName,
StructName: structName,
StructDefinitions: structDefinitions,
}
var buf bytes.Buffer
err = tmpl.Execute(&buf, structData)
if err != nil {
return fmt.Errorf("Error executing template: %v", err)
}
err = os.WriteFile(outputPath, buf.Bytes(), 0644)
if err != nil {
return fmt.Errorf("Failed to write output file %s: %v", outputPath, err)
}
fmt.Printf("Generated Go struct for %s and saved to %s\n", inputPath, outputPath)
return nil
}
func generateStructDefinitions(structName string, properties map[string]Property) string {
var structDefs strings.Builder
generateStruct(&structDefs, structName, properties)
return structDefs.String()
}
func generateStruct(structDefs *strings.Builder, structName string, properties map[string]Property) {
// check if the struct has already been generated
if _, exists := StructNameTracker[structName]; exists {
return
}
// mark this struct as generated
StructNameTracker[structName] = true
fields := []Field{}
nestedStructs := []string{}
for name, prop := range properties {
// skip fields that are in the SkipFields map
if _, skip := SkipFields[name]; skip {
continue
}
fieldName := mapElasticsearchFieldToGoField(name)
var fieldType string
if prop.Type == "object" || prop.Type == "nested" {
// check if the type has a custom exception
if customType, exists := TypeExceptions[name]; exists {
var nestedStructName string
fieldType = customType
if strings.HasPrefix(fieldType, "*") {
nestedStructName = fieldType[1:] // "*" を取り除く
} else if strings.HasPrefix(fieldType, "[]") {
nestedStructName = fieldType[2:] // "[]" を取り除く
} else {
nestedStructName = fieldType
}
nestedStructs = append(nestedStructs, generateStructDefinitions(nestedStructName, prop.Properties))
} else {
nestedStructName := toPascalCase(name)
fieldType = "*" + nestedStructName
nestedStructs = append(nestedStructs, generateStructDefinitions(nestedStructName, prop.Properties))
}
} else {
fieldType = mapElasticsearchTypeToGoType(name, prop.Type)
}
fieldComment := mapElasticsearchFieldToComment(name)
fields = append(fields, Field{
FieldName: fieldName,
FieldType: fieldType,
JSONName: name,
FieldComment: fieldComment,
})
}
// sort fields alphabetically
sort.Slice(fields, func(i, j int) bool {
return fields[i].FieldName < fields[j].FieldName
})
// generate struct definition
structDefs.WriteString(fmt.Sprintf("type %s struct {\n", structName))
for _, field := range fields {
if field.FieldComment != "" {
structDefs.WriteString(fmt.Sprintf("\t%s %s `json:\"%s\"` // %s\n", field.FieldName, field.FieldType, field.JSONName, field.FieldComment))
} else {
structDefs.WriteString(fmt.Sprintf("\t%s %s `json:\"%s\"`\n", field.FieldName, field.FieldType, field.JSONName))
}
}
structDefs.WriteString("}\n\n")
// append nested structs
for _, nestedStruct := range nestedStructs {
structDefs.WriteString(nestedStruct)
}
}
func mapElasticsearchTypeToGoType(name, esType string) string {
// check if the type has a custom exception
if customType, exists := TypeExceptions[name]; exists {
return customType
}
goType, exists := GoTypeMap[esType]
if !exists {
goType = "interface{}"
}
return goType
}
func mapElasticsearchFieldToGoField(esFieldName string) string {
// check if the field has a custom exception
if customFieldName, exists := FieldExceptions[esFieldName]; exists {
return customFieldName
}
return toPascalCase(esFieldName)
}
func mapElasticsearchFieldToComment(esFieldName string) string {
// check if the field has a custom comment
if comment, exists := FieldComments[esFieldName]; exists {
return comment
}
return ""
}
func loadTypeMapping(filePath string) {
data, err := os.ReadFile(filePath)
if err != nil {
log.Fatalf("Failed to read type mapping file %s: %v", filePath, err)
}
err = json.Unmarshal(data, &GoTypeMap)
if err != nil {
log.Fatalf("Error unmarshalling JSON from type mapping file %s: %v", filePath, err)
}
}
func loadFieldExceptions(filePath string) {
data, err := os.ReadFile(filePath)
if err != nil {
log.Fatalf("Failed to read field exception file %s: %v", filePath, err)
}
err = json.Unmarshal(data, &FieldExceptions)
if err != nil {
log.Fatalf("Error unmarshalling JSON from field exception file %s: %v", filePath, err)
}
}
func loadTypeExceptions(filePath string) {
data, err := os.ReadFile(filePath)
if err != nil {
log.Fatalf("Failed to read type exception file %s: %v", filePath, err)
}
err = json.Unmarshal(data, &TypeExceptions)
if err != nil {
log.Fatalf("Error unmarshalling JSON from type exception file %s: %v", filePath, err)
}
}
func loadSkipFields(filePath string) {
data, err := os.ReadFile(filePath)
if err != nil {
log.Fatalf("Failed to read skip fields file %s: %v", filePath, err)
}
err = json.Unmarshal(data, &SkipFields)
if err != nil {
log.Fatalf("Error unmarshalling JSON from skip fields file %s: %v", filePath, err)
}
}
func loadFieldComments(filePath string) {
data, err := os.ReadFile(filePath)
if err != nil {
log.Fatalf("Failed to read field comments file %s: %v", filePath, err)
}
err = json.Unmarshal(data, &FieldComments)
if err != nil {
log.Fatalf("Error unmarshalling JSON from field comments file %s: %v", filePath, err)
}
}
func toCamelCase(s string) string {
caser := cases.Title(language.Und) // or: `language.English`
parts := strings.Split(s, "_")
for i, part := range parts {
parts[i] = caser.String(part)
}
parts[0] = strings.ToLower(parts[0])
return strings.Join(parts, "")
}
func toPascalCase(s string) string {
caser := cases.Title(language.Und)
parts := strings.Split(s, "_")
for i, part := range parts {
parts[i] = caser.String(part)
}
return strings.Join(parts, "")
}
// GeoPoint struct for handling geo_point type in Elasticsearch
type GeoPoint struct {
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
}