-
Notifications
You must be signed in to change notification settings - Fork 0
/
fields.go
371 lines (288 loc) · 7.42 KB
/
fields.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
package jsonstruct
import (
"fmt"
"math/big"
"reflect"
"sort"
"strings"
)
const jsonRawMessage = "*json.RawMessage"
// Field represents a single struct field.
type Field struct {
goName string
originalName string
rawValue any
optional bool
isJSONRaw bool
}
func NewField() *Field {
return &Field{}
}
func (f *Field) SetName(originalName string) *Field {
f.goName = GetGoName(originalName)
f.originalName = originalName
return f
}
func (f *Field) SetValue(value any) *Field {
f.rawValue = value
return f
}
func (f *Field) SetOptional() *Field {
f.optional = true
return f
}
func (f *Field) SetJSONRaw() *Field {
f.isJSONRaw = true
return f
}
// Name returns the name of this field as it will be rendered in the final struct.
func (f Field) Name() string {
return f.goName
}
func (f Field) OriginalName() string {
return f.originalName
}
// Tag returns the JSON tag as it will be rendered in the final struct.
func (f Field) Tag() string {
if f.originalName == f.Name() {
return ""
}
if f.optional {
return fmt.Sprintf("`json:\"%s,omitempty\"`", f.originalName)
}
return fmt.Sprintf("`json:\"%s\"`", f.originalName)
}
// Type returns the type of the field as it will be rendered in the final struct.
func (f Field) Type() string {
if f.rawValue == nil || f.isJSONRaw {
return jsonRawMessage
}
switch f.rawValue.(type) {
case int64:
return "int64"
case *big.Int:
return "*big.Int"
case float64:
return "float64"
case *big.Float:
return "*big.Float"
case string:
return "string"
case bool:
return "bool"
}
if f.IsSlice() {
return f.SliceType()
}
if f.IsStruct() {
return fmt.Sprintf("*%s", f.goName)
}
return "any"
}
// SliceType returns the type of the slice this field represents.
func (f Field) SliceType() string {
// rawVal := reflect.ValueOf(f.rawValue)
rawType := reflect.TypeOf(f.rawValue)
if rawType.Kind() != reflect.Slice {
return ""
}
// we have a field that represents a struct, whose slice type is its name
if f.IsStructSlice() {
return fmt.Sprintf("[]*%s", f.Name())
}
return getSliceType(f.rawValue)
}
func getSliceType(input any) string {
var (
rawVal = reflect.ValueOf(input)
// rawType = reflect.TypeOf(input)
sliceType string
)
// walk the array's elements and figure out if they're all typed the same
for i := 0; i < rawVal.Len(); i++ {
var itemType string
idxVal := rawVal.Index(i)
kind := idxVal.Type().Kind()
if kind == reflect.Pointer || kind == reflect.Interface {
idxVal = idxVal.Elem()
}
if !idxVal.IsValid() {
sliceType = jsonRawMessage
break
}
idxType := idxVal.Type()
kind = idxType.Kind()
if kind == reflect.Slice {
itemType = getSliceType(idxVal.Interface())
} else {
itemType = idxType.String()
}
// we have encountered multiple types for this field, have to accept anything
if sliceType != "" && itemType != sliceType {
sliceType = jsonRawMessage
break
}
sliceType = itemType
}
return fmt.Sprintf("[]%s", sliceType)
}
// Value returns the string version of RawValue.
func (f Field) Value() string {
if val := simpleAnyToString(f.rawValue); val != "" {
return val
}
if f.rawValue == nil {
return "null"
}
if vals := f.SimpleSliceValues(); f.IsSlice() && len(vals) > 0 {
return fmt.Sprintf("[%s]", strings.Join(vals, ", "))
}
return ""
}
// SimpleSliceValues returns a slice of strings with the values of simple slice Fields ([]int64, []float64, []bool,
// []string). If it doesn't recognize the Field as one of these, it returns an empty slice.
func (f Field) SimpleSliceValues() []string {
results := []string{}
if !f.IsSlice() {
return []string{}
}
rawVal := reflect.ValueOf(f.rawValue)
switch f.SliceType() {
case "[]int64", "[]float64", "[]bool", "[]string":
for i := 0; i < rawVal.Len(); i++ {
idxVal := rawVal.Index(i)
kind := idxVal.Type().Kind()
if kind == reflect.Pointer || kind == reflect.Interface {
idxVal = idxVal.Elem()
}
if !idxVal.IsValid() {
return []string{}
}
results = append(results, simpleAnyToString(idxVal.Interface()))
}
}
return results
}
// Comment returns the string used for example value comments.
func (f Field) Comment() string {
comment := ""
cleanVal := strings.ReplaceAll(f.Value(), "\n", "\\n")
if val := f.Value(); val != "" {
comment = fmt.Sprintf("// Example: %s", cleanVal)
}
if len(comment) > 50 {
comment = fmt.Sprintf("%s...", comment[0:47])
}
return comment
}
// IsStruct returns true if RawValue is either a struct or a pointer to a struct.
func (f Field) IsStruct() bool {
if f.rawValue == nil {
return false
}
typ := reflect.TypeOf(f.rawValue)
kind := typ.Kind()
if kind == reflect.Ptr {
kind = typ.Elem().Kind()
}
return kind == reflect.Struct
}
// GetStruct gets a the JSONStruct in RawValue if f is a struct or slice of struct, otherwise returns nil.
func (f Field) GetStruct() *JSONStruct {
switch {
case f.IsStruct():
js, ok := f.rawValue.(*JSONStruct)
if !ok {
return nil
}
return js.SetName(f.Name())
case f.IsStructSlice():
return f.GetSliceStruct()
default:
return nil
}
}
func (f Field) GetSliceStruct() *JSONStruct {
anySlice, ok := f.rawValue.([]any)
if !ok {
return nil
}
return getSliceStruct(anySlice).SetName(f.Name())
}
func getSliceStruct(input []any) *JSONStruct {
result := &JSONStruct{}
jStructs, err := anySliceToJSONStructs(input)
if err != nil {
return nil
}
// foundFields contains the first instance of a field, while fieldCounts reports the number of structs containing it
// have to use synced slices here to avoid the reordering that would occur with a map
foundFields := []*Field{}
fieldTypes := []string{}
fieldCounts := []int{}
// have a slice of structs, each of which may or may not contain the full set of fields - walk each and find the
// fields that don't reoccur
for _, jStruct := range jStructs {
for _, field := range jStruct.Fields() {
foundIndex := -1
for i, foundField := range foundFields {
if field.OriginalName() == foundField.OriginalName() {
fieldCounts[i]++
foundIndex = i
break
}
}
if foundIndex == -1 {
foundFields = append(foundFields, field)
fieldTypes = append(fieldTypes, field.Type())
fieldCounts = append(fieldCounts, 1)
} else if field.Type() != fieldTypes[foundIndex] {
foundFields[foundIndex].SetJSONRaw()
}
}
}
for i := 0; i < len(foundFields); i++ {
if fieldCounts[i] != len(jStructs) {
foundFields[i].SetOptional()
}
result.AddFields(foundFields[i])
}
return result
}
// IsSlice returns true if RawValue is of kind slice.
func (f Field) IsSlice() bool {
kind := reflect.TypeOf(f.rawValue).Kind()
return kind == reflect.Slice
}
func (f Field) IsStructSlice() bool {
return isStructSlice(f.rawValue)
}
func isStructSlice(input any) bool {
anySlice, ok := input.([]any)
if !ok {
return false
}
if _, err := anySliceToJSONStructs(anySlice); err != nil {
return false
}
return true
}
// Equals returns true if two Fields share an original name, Go name, and type - does not compare values!
func (f Field) Equals(input *Field) bool {
switch {
case f.Name() != input.Name():
return false
case f.Type() != input.Type():
return false
case f.OriginalName() != input.OriginalName():
return false
}
return true
}
// Fields is a convenience type for a slice of Field structs.
type Fields []*Field
func (f Fields) SortAlphabetically() {
sort.Slice(f, func(i, j int) bool {
return f[i].goName < f[j].goName
})
}