/
utils.go
394 lines (298 loc) · 8.48 KB
/
utils.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
// Copyright 2019 Aporeto Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"fmt"
"os"
"path"
"reflect"
"sort"
"strings"
"text/template"
"go.aporeto.io/elemental/cmd/elegen/static"
"go.aporeto.io/regolithe/spec"
)
// An Enum represents an enum.
type Enum struct {
Type string
Values map[string]string
AttributeName string
}
func makeTemplate(p string) (*template.Template, error) {
data, err := static.Asset(p)
if err != nil {
return nil, err
}
return template.New(path.Base(p)).Funcs(functions).Parse(string(data))
}
func writeFile(path string, data []byte) error {
f, err := os.Create(path)
if err != nil {
return fmt.Errorf("unable to write file: %s", f.Name())
}
defer f.Close() // nolint: errcheck
if _, err := f.Write(data); err != nil {
return fmt.Errorf("unable to write file: %s", f.Name())
}
return nil
}
func attributeTypeConverter(typ spec.AttributeType, subtype string) (string, string) {
switch typ {
case spec.AttributeTypeString, spec.AttributeTypeEnum:
return "string", ""
case spec.AttributeTypeFloat:
return "float64", ""
case spec.AttributeTypeBool:
return "bool", ""
case spec.AttributeTypeInt:
return "int", ""
case spec.AttributeTypeTime:
return "time.Time", "time"
case spec.AttributeTypeList:
if subtype == "" || subtype == "object" {
return "[]interface{}", ""
}
return "[]" + subtype, ""
default:
return "interface{}", ""
}
}
func attributeNameConverter(attrName string) string {
return strings.Title(attrName)
}
func attrToField(set spec.SpecificationSet, shadow bool, attr *spec.Attribute) string {
json := attr.Name
msgpack := attr.Name
bson := strings.ToLower(attr.Name)
if !attr.Exposed {
json = "-"
msgpack = "-"
}
if attr.Exposed && (attr.OmitEmpty || shadow) {
json += ",omitempty"
msgpack += ",omitempty"
}
if !attr.Stored {
bson = "-"
} else if attr.Identifier {
bson = "_" + bson
} else if shadow {
bson += ",omitempty"
}
descLines := strings.Split(attr.Description, "\n")
for i := 0; i < len(descLines); i++ {
descLines[i] = "// " + escapeBackticks(descLines[i])
}
var pointer string
if mode, ok := attr.Extensions["refMode"]; ok && mode == "pointer" {
pointer = "*"
}
var pointerShadow string
if shadow {
pointerShadow = "*"
}
var convertedType string
switch attr.Type {
case spec.AttributeTypeRef:
convertedType = pointerShadow + pointer + set.Specification(attr.SubType).Model().EntityName
case spec.AttributeTypeRefList:
remoteSpec := set.Specification(attr.SubType)
if remoteSpec.Model().Detached {
convertedType = pointerShadow + "[]" + pointer + remoteSpec.Model().EntityName
} else {
convertedType = pointerShadow + pointer + remoteSpec.Model().EntityNamePlural + "List"
}
case spec.AttributeTypeRefMap:
convertedType = pointerShadow + "map[string]" + pointer + set.Specification(attr.SubType).Model().EntityName
default:
convertedType = pointerShadow + attr.ConvertedType
}
return fmt.Sprintf(
"%s\n %s %s `json:\"%s\" msgpack:\"%s\" bson:\"%s\" mapstructure:\"%s,omitempty\"`\n\n",
strings.Join(descLines, "\n"),
attr.ConvertedName,
convertedType,
json,
msgpack,
bson,
strings.Replace(json, ",omitempty", "", 1),
)
}
func escapeBackticks(str string) string {
return strings.Replace(str, "`", "`+\"`\"+`", -1)
}
func buildEnums(s spec.Specification, version string) []Enum {
var enums []Enum // nolint
attributes := s.Attributes(version)
for _, attr := range attributes {
if attr.Type != spec.AttributeTypeEnum {
continue
}
attr.ConvertedType = fmt.Sprintf("%s%sValue", s.Model().EntityName, attr.ConvertedName)
values := map[string]string{}
for _, v := range attr.AllowedChoices {
k := fmt.Sprintf("%s%s%s", s.Model().EntityName, attr.ConvertedName, v)
values[k] = v
}
enums = append(enums, Enum{
Type: attr.ConvertedType,
Values: values,
AttributeName: attr.Name,
})
}
return enums
}
func shouldGenerateGetter(attr *spec.Attribute, publicMode bool) bool {
if publicMode {
return attr.Getter && attr.Exposed
}
return attr.Getter
}
func shouldGenerateSetter(attr *spec.Attribute, publicMode bool) bool {
if publicMode {
return attr.Setter && attr.Exposed
}
return attr.Setter
}
func shouldWriteInitializer(s spec.Specification, attrConvertedName string, version string, publicMode bool) bool {
var attr *spec.Attribute
for _, a := range s.Attributes(version) {
if a.ConvertedName == attrConvertedName {
attr = a
break
}
}
if publicMode {
return attr.Exposed
}
return true
}
func shouldWriteAttributeMap(attr *spec.Attribute, publicMode bool) bool {
if publicMode {
return attr.Exposed
}
return true
}
func shouldRegisterSpecification(s spec.Specification, publicMode bool) bool {
if s.Model().Detached {
return false
}
if publicMode {
return !s.Model().Private
}
return true
}
func shouldRegisterRelationship(set spec.SpecificationSet, entityName string, publicMode bool) bool {
var s spec.Specification
for _, i := range set.Specifications() {
if i.Model().EntityName == entityName {
s = i
}
}
if s.Model().Detached {
return false
}
if publicMode {
return !s.Model().Private
}
return true
}
func shouldRegisterInnerRelationship(set spec.SpecificationSet, restName string, publicMode bool) bool {
s := set.Specification(restName)
if s.Model().Detached {
return false
}
if publicMode {
return !s.Model().Private
}
return true
}
func writeInitializer(set spec.SpecificationSet, s spec.Specification, attr *spec.Attribute) string {
if attr.Initializer == "" &&
attr.DefaultValue == nil &&
attr.Type != spec.AttributeTypeList &&
attr.Type != spec.AttributeTypeRef &&
attr.Type != spec.AttributeTypeRefList &&
attr.Type != spec.AttributeTypeRefMap {
return ""
}
if ok1, ok2 := attr.Extensions["noInit"].(bool); ok2 && ok1 {
return ""
}
return fmt.Sprintf("%s: %s,", attr.ConvertedName, writeDefaultValue(set, s, attr))
}
func writeDefaultValue(set spec.SpecificationSet, s spec.Specification, attr *spec.Attribute) string {
if attr.Initializer != "" {
return attr.Initializer
}
var pointer string
var ref string
if mode, ok := attr.Extensions["refMode"]; ok && mode == "pointer" {
pointer = "*"
ref = "New"
}
switch attr.Type {
case spec.AttributeTypeList:
if attr.DefaultValue == nil {
return ref + attr.ConvertedType + "{}"
}
case spec.AttributeTypeRef:
return ref + set.Specification(attr.SubType).Model().EntityName + "()"
case spec.AttributeTypeRefList:
remoteSpec := set.Specification(attr.SubType)
if remoteSpec.Model().Detached {
return "[]" + pointer + remoteSpec.Model().EntityName + "{}"
}
return pointer + remoteSpec.Model().EntityNamePlural + "List{}"
case spec.AttributeTypeRefMap:
return "map[string]" + pointer + set.Specification(attr.SubType).Model().EntityName + "{}"
}
var prefix string
if attr.Type == spec.AttributeTypeEnum {
prefix = s.Model().EntityName + attr.ConvertedName
}
return crawl(reflect.ValueOf(attr.DefaultValue), prefix)
}
func crawl(val reflect.Value, prefix string) string {
switch val.Kind() {
case reflect.Bool:
if val.Bool() {
return "true"
}
return "false"
case reflect.String:
if prefix != "" {
return fmt.Sprintf(`%s%s`, prefix, val.String())
}
return fmt.Sprintf(`"%s"`, val.String())
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int8:
return fmt.Sprintf(`%d`, val.Int())
case reflect.Float32, reflect.Float64:
return fmt.Sprintf(`%f`, val.Float())
// case reflect.Map:
case reflect.Slice:
out := "[]" + val.Index(0).Elem().Kind().String() + "{\n"
for i := 0; i < val.Len(); i++ {
out += fmt.Sprintf("%s,\n", crawl(val.Index(i).Elem(), prefix))
}
out += "}"
return out
}
return ""
}
func sortAttributes(attrs []*spec.Attribute) []*spec.Attribute {
out := make([]*spec.Attribute, len(attrs))
copy(out, attrs)
sort.Slice(out, func(i int, j int) bool {
return strings.Compare(attrs[i].ConvertedName, attrs[j].ConvertedName) == -1
})
return out
}