This repository has been archived by the owner on Apr 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tool_box.go
341 lines (284 loc) · 9.44 KB
/
tool_box.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
package sprbox
import (
"encoding/json"
"errors"
"fmt"
"path/filepath"
"reflect"
"strings"
"gopkg.in/yaml.v2"
)
// Struct field flags.
const (
sftSkip = "-"
)
// Errors.
var (
errInvalidPointer = errors.New("<box> parameter should be a struct pointer")
errNotConfigurable = errors.New("does not implement the 'configurable' interface: `func SpareConfig([]string) error`")
errNotConfigurableInCollection = errors.New("does not implement the 'configurable' interface nor its elements implements the 'configurableInCollection' one: `func SpareConfigBytes([]byte) error`")
)
type configurable interface {
SpareConfig([]string) error
}
type configurableInCollection interface {
SpareConfigBytes([]byte) error
}
// If PkgPath is set, the field is not exported
// exported := field.PkgPath == ""
// LoadToolBox initialize and (eventually) configure the provided struct pointer
// looking for the config files in the provided configPath.
func LoadToolBox(toolBox interface{}, configPath string) (err error) {
t := reflect.TypeOf(toolBox).Elem()
v := reflect.ValueOf(toolBox).Elem()
if t.Kind() != reflect.Struct {
return errInvalidPointer
} else if !v.CanSet() || !v.IsValid() {
return errInvalidPointer // nil pointer
}
for i := 0; i < v.NumField(); i++ {
sf := t.Field(i)
fv := v.Field(i)
if err = loadField(configPath, &sf, fv, 0); err != nil {
break
}
}
debugPrintf("\nLoaded toolbox: \n%s\n", green(dump(toolBox)))
fmt.Print("\n")
return
}
// level is the parent grade to the initially passed fv
func loadField(configPath string, sf *reflect.StructField, fv reflect.Value, level int) error {
switch fv.Kind() {
case reflect.Ptr:
if tag, found := sf.Tag.Lookup(sftKey); found && tag == sftSkip {
return nil
}
if !fv.CanSet() || sf.Anonymous {
return nil
}
// skip already initialized pointers (as can be a '*Config'
// field configured in 'configurable' interface call).
if fv.IsNil() {
fv.Set(reflect.New(fv.Type().Elem()))
}
return loadField(configPath, sf, fv.Elem(), level)
case reflect.Struct:
// !reflect.Zero(fv.Type()) is an already configured field, so sprbox will skip it.
if !fv.CanSet() || sf.Anonymous ||
!reflect.DeepEqual(fv.Interface(), reflect.Zero(fv.Type()).Interface()) {
return nil
}
configFiles := []string{sf.Name}
if skip := parseTags(&configFiles, sf); skip {
return nil
}
fv.Set(reflect.New(fv.Type()).Elem())
if _, isConfigurable := fv.Addr().Interface().(configurable); isConfigurable {
if err := configure(configPath, configFiles, sf, fv.Addr(), level); err != nil {
return err
}
} else {
printLoadResult(sf.Name, sf.Type, errNotConfigurable, level)
}
level += 1
for i := 0; i < fv.NumField(); i++ {
ssf := fv.Type().Field(i)
sfv := fv.Field(i)
verbosePrintf("%ssub-field: %s\n", strings.Repeat(" -> ", level), ssf.Name)
//subPath := filepath.Join(configPath, sf.Name)
if err := loadField(configPath, &ssf, sfv, level); err != nil {
return err
}
}
return nil
case reflect.Slice:
// !reflect.Zero(fv.Type()) is an already configured field, so sprbox will skip it.
if !fv.CanSet() || sf.Anonymous ||
!reflect.DeepEqual(fv.Interface(), reflect.Zero(fv.Type()).Interface()) {
return nil
}
configFiles := []string{sf.Name}
if skip := parseTags(&configFiles, sf); skip {
return nil
}
fv.Set(reflect.New(fv.Type()).Elem())
if _, isConfigurable := fv.Addr().Interface().(configurable); isConfigurable {
if err := configure(configPath, configFiles, sf, fv.Addr(), level); err != nil {
return err
}
} else {
// skip slices of non-configurableInCollection objects
cicType := reflect.TypeOf((*configurableInCollection)(nil)).Elem()
if !fv.Type().Elem().Implements(cicType) &&
!reflect.PtrTo(fv.Type().Elem()).Implements(cicType) {
printLoadResult(sf.Name, sf.Type, errNotConfigurableInCollection, level)
return nil
}
printLoadResult(sf.Name, sf.Type, errNotConfigurable, level)
level += 1
for i, file := range configFiles {
configFiles[i] = filepath.Join(configPath, file)
}
var config []interface{}
if err := LoadConfig(&config, configFiles...); err != nil {
printLoadResult(sf.Name, sf.Type.Elem(), err, level)
return err
}
for i := 0; i < len(config); i++ {
elemType := fv.Type().Elem()
var elem reflect.Value
sfName := fmt.Sprintf("%s[%d]", sf.Name, i)
switch elemType.Kind() {
case reflect.Ptr:
elem = reflect.New(elemType.Elem())
if err := configureElem(elem, config[i], sfName, level); err != nil {
return err
}
printLoadResult(sfName, elem.Type(), nil, level)
fv.Set(reflect.Append(fv, elem))
case reflect.Struct:
elem = reflect.New(elemType)
if err := configureElem(elem, config[i], sfName, level); err != nil {
return err
}
printLoadResult(sfName, elem.Elem().Type(), nil, level)
fv.Set(reflect.Append(fv, elem.Elem()))
}
}
}
return nil
case reflect.Map:
// !reflect.Zero(fv.Type()) is an already configured field, so sprbox will skip it.
if !fv.CanSet() || sf.Anonymous ||
!reflect.DeepEqual(fv.Interface(), reflect.Zero(fv.Type()).Interface()) {
return nil
}
configFiles := []string{sf.Name}
if skip := parseTags(&configFiles, sf); skip {
return nil
}
fv.Set(reflect.New(fv.Type()).Elem())
if _, isConfigurable := fv.Addr().Interface().(configurable); isConfigurable {
if err := configure(configPath, configFiles, sf, fv.Addr(), level); err != nil {
return err
}
} else {
// skip maps of non-configurableInCollection objects
cicType := reflect.TypeOf((*configurableInCollection)(nil)).Elem()
if !fv.Type().Elem().Implements(cicType) &&
!reflect.PtrTo(fv.Type().Elem()).Implements(cicType) {
printLoadResult(sf.Name, sf.Type, errNotConfigurableInCollection, level)
return nil
}
printLoadResult(sf.Name, sf.Type, errNotConfigurable, level)
level += 1
for i, file := range configFiles {
configFiles[i] = filepath.Join(configPath, file)
}
var config map[string]interface{}
if err := LoadConfig(&config, configFiles...); err != nil {
printLoadResult(sf.Name, fv.Type(), err, level)
return err
}
fv.Set(reflect.MakeMapWithSize(fv.Type(), len(config)))
for key, conf := range config {
kv := reflect.ValueOf(key)
elemType := fv.Type().Elem()
var elem reflect.Value
sfName := fmt.Sprintf("%s[%s]", sf.Name, key)
switch elemType.Kind() {
case reflect.Ptr:
elem = reflect.New(elemType.Elem())
if err := configureElem(elem, conf, sfName, level); err != nil {
return err
}
printLoadResult(sfName, elem.Type(), nil, level)
fv.SetMapIndex(kv, elem)
case reflect.Struct:
elem = reflect.New(elemType)
if err := configureElem(elem, conf, sfName, level); err != nil {
return err
}
printLoadResult(sfName, elem.Elem().Type(), nil, level)
fv.SetMapIndex(kv, elem.Elem())
}
}
}
return nil
default:
return nil
}
}
// parseTags returns the config file name and the skip flag.
// The name will be returned also if not specified in tags,
// the field name without extension will be returned in that case,
// loadConfig will look for a file with that prefix and any kind
// of extension, if necessary (no '.' in file name).
func parseTags(configFiles *[]string, f *reflect.StructField) (skip bool) {
tag, found := f.Tag.Lookup(sftKey)
if !found {
return
}
if tag == sftSkip {
//printLoadResult(f.Name, f.Type, errOmit)
return true
}
tagFields := strings.Split(tag, ",")
for _, flag := range tagFields {
files := strings.Split(flag, "|")
*configFiles = append(*configFiles, files...)
}
return
}
// configure will call the 'configurable' interface on the passed field struct pointer.
func configure(configPath string, configFiles []string, f *reflect.StructField, v reflect.Value, level int) error {
for i, file := range configFiles {
configFiles[i] = filepath.Join(configPath, file)
}
if err := v.Interface().(configurable).SpareConfig(configFiles); err != nil {
printLoadResult(f.Name, f.Type, err, level)
return err
}
printLoadResult(f.Name, f.Type, nil, level)
return nil
}
// configureElem will call the 'configurableInCollection' interface on the passed struct pointer.
func configureElem(elem reflect.Value, config interface{}, sfName string, level int) (err error) {
var bytes []byte
if bytes, err = json.Marshal(config); err != nil {
if bytes, err = yaml.Marshal(config); err != nil {
printLoadResult(sfName, elem.Type(), err, level)
return err
}
}
if err = elem.Interface().(configurableInCollection).SpareConfigBytes(bytes); err != nil {
printLoadResult(sfName, elem.Type(), err, level)
return err
}
return nil
}
func printLoadResult(objNameType string, t reflect.Type, err error, level int) {
if len(objNameType) == 0 {
objNameType = t.Name()
}
objNameType = strings.Repeat(" -> ", level) + objNameType
objType := t.String()
if len(objType)+len(objNameType)+1 >= 60 {
objType = t.Kind().String()
}
objNameType = fmt.Sprintf("%v (%v)", blue(objNameType), objType)
objNameType = fmt.Sprintf("%-60v", objNameType)
if err != nil {
if err == errNotConfigurable || err == errNotConfigurableInCollection {
if level > 0 { //&& !debug {
return
}
fmt.Printf("%s %s\n", objNameType, yellow("-> "+err.Error()))
} else {
fmt.Printf("%s %s\n", objNameType, red("-> "+err.Error()))
}
} else {
fmt.Printf("%s %s\n", objNameType, green("<- config loaded"))
}
}