This repository has been archived by the owner on Sep 16, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
config_adapter.go
441 lines (362 loc) · 8.72 KB
/
config_adapter.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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
/*
Copyright © 2017 Henry Huang <hhh@rutcode.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package config
import (
"math/big"
"reflect"
"strings"
"sync"
"time"
"github.com/iTrellis/common/formats"
"github.com/iTrellis/common/json"
"gopkg.in/yaml.v3"
)
const (
includeReg = `\$\{([0-9|a-z|A-Z|_|-]|\.)+\}`
)
// AdapterConfig default config adapter
type AdapterConfig struct {
ConfigFile string
ConfigString string
ConfigStruct interface{}
EnvPrefix string
EnvAllowed bool
data []byte
readerType ReaderType
reader Reader
locker sync.RWMutex
configs map[string]interface{}
}
// NewAdapterConfig return default config adapter
// name is file's path
func NewAdapterConfig(filepath string) (Config, error) {
if len(filepath) == 0 {
return nil, ErrInvalidFilePath
}
a := &AdapterConfig{
ConfigFile: filepath,
configs: make(map[string]interface{}),
}
err := a.init(OptionFile(filepath))
if err != nil {
return nil, err
}
return a.copy(), nil
}
func (p *AdapterConfig) init(opts ...OptionFunc) (err error) {
for i := 0; i < len(opts); i++ {
opts[i](p)
}
if len(p.ConfigFile) > 0 {
p.readerType = fileToReaderType(p.ConfigFile)
p.data, _, err = filesRepo.Read(p.ConfigFile)
if err != nil {
return
}
}
switch p.readerType {
case ReaderTypeJSON:
p.reader = NewJSONReader(ReaderOptionFilename(p.ConfigFile))
case ReaderTypeYAML:
p.reader = NewYAMLReader(ReaderOptionFilename(p.ConfigFile))
default:
return ErrNotSupportedReaderType
}
if len(p.ConfigString) > 0 {
p.data = []byte(p.ConfigString)
}
if p.ConfigStruct != nil {
p.data, err = p.reader.Dump(p.ConfigStruct)
if err != nil {
return err
}
}
if err = p.reader.ParseData(p.data, &p.configs); err != nil {
return
}
return p.copyDollarSymbol("", &p.configs)
}
// GetKeys get map keys
func (p *AdapterConfig) GetKeys() []string {
p.locker.RLock()
defer p.locker.RUnlock()
var keys []string
for key := range p.configs {
keys = append(keys, key)
}
return keys
}
func (p *AdapterConfig) copy() *AdapterConfig {
p.locker.RLock()
defer p.locker.RUnlock()
values := DeepCopy(p.configs)
valuesMap := values.(map[string]interface{})
return &AdapterConfig{
ConfigFile: p.ConfigFile,
ConfigString: p.ConfigString,
ConfigStruct: p.ConfigStruct,
readerType: p.readerType,
reader: p.reader,
configs: valuesMap,
}
}
// GetTimeDuration return time in p.configs by key
func (p *AdapterConfig) GetTimeDuration(key string, defValue ...time.Duration) time.Duration {
return formats.ParseStringTime(strings.ToLower(p.GetString(key)), defValue...)
}
// GetByteSize return time in p.configs by key
func (p *AdapterConfig) GetByteSize(key string, defValue ...*big.Int) *big.Int {
return formats.ParseStringByteSize(strings.ToLower(p.GetString(key)), defValue...)
}
// GetInterface return a interface object in p.configs by key
func (p *AdapterConfig) GetInterface(key string, defValue ...interface{}) (res interface{}) {
var err error
var v interface{}
defer func() {
if err != nil {
if len(defValue) == 0 {
return
}
res = defValue[0]
} else {
res = v
}
}()
if key == "" {
return ErrInvalidKey
}
v, err = p.getKeyValue(key)
return
}
// GetString return a string object in p.configs by key
func (p *AdapterConfig) GetString(key string, defValue ...string) (res string) {
var ok bool
defer func() {
if ok || len(defValue) == 0 {
return
}
res = defValue[0]
}()
v := p.GetInterface(key, defValue)
res, ok = v.(string)
return
}
// GetBoolean return a bool object in p.configs by key
func (p *AdapterConfig) GetBoolean(key string, defValue ...bool) (b bool) {
var ok bool
defer func() {
if ok || len(defValue) == 0 {
return
}
b = defValue[0]
}()
v := p.GetInterface(key, defValue)
if v == nil {
return
}
switch reflect.TypeOf(v).Kind() {
case reflect.Bool:
ok, b = true, v.(bool)
case reflect.String:
ok, b = true, strings.ToLower(v.(string)) == "on"
}
return
}
// GetInt return a int object in p.configs by key
func (p *AdapterConfig) GetInt(key string, defValue ...int) (res int) {
var err error
defer func() {
if err != nil {
if len(defValue) == 0 {
return
}
res = defValue[0]
}
}()
v, e := formats.ToInt64(p.GetInterface(key, defValue))
if e != nil {
err = e
return
}
return int(v)
}
// GetFloat return a float object in p.configs by key
func (p *AdapterConfig) GetFloat(key string, defValue ...float64) (res float64) {
var err error
defer func() {
if err != nil {
if len(defValue) == 0 {
return
}
res = defValue[0]
}
}()
v, e := formats.ToFloat64(p.GetInterface(key, defValue))
if e != nil {
err = e
return
}
return v
}
// GetList return a list of interface{} in p.configs by key
func (p *AdapterConfig) GetList(key string) (res []interface{}) {
vS := reflect.Indirect(reflect.ValueOf(p.GetInterface(key)))
if vS.Kind() != reflect.Slice {
return nil
}
var vs []interface{}
for i := 0; i < vS.Len(); i++ {
vs = append(vs, vS.Index(i).Interface())
}
return vs
}
// GetStringList return a list of strings in p.configs by key
func (p *AdapterConfig) GetStringList(key string) []string {
var items []string
for _, v := range p.GetList(key) {
item, ok := v.(string)
if !ok {
return nil
}
items = append(items, item)
}
return items
}
// GetBooleanList return a list of booleans in p.configs by key
func (p *AdapterConfig) GetBooleanList(key string) []bool {
var items []bool
for _, v := range p.GetList(key) {
item, ok := v.(bool)
if !ok {
return nil
}
items = append(items, item)
}
return items
}
// GetIntList return a list of ints in p.configs by key
func (p *AdapterConfig) GetIntList(key string) []int {
var items []int
for _, v := range p.GetList(key) {
i, e := formats.ToInt(v)
if e != nil {
return nil
}
items = append(items, i)
}
return items
}
// GetFloatList return a list of floats in p.configs by key
func (p *AdapterConfig) GetFloatList(key string) []float64 {
var items []float64
for _, v := range p.GetList(key) {
f, e := formats.ToFloat64(v)
if e != nil {
return nil
}
items = append(items, f)
}
return items
}
// GetMap get map value
func (p *AdapterConfig) GetMap(key string) Options {
vm, err := p.getKeyValue(key)
if err != nil {
return nil
}
switch t := vm.(type) {
case Options:
return t
case map[string]interface{}:
return t
case map[interface{}]interface{}:
result := make(map[string]interface{})
for k, v := range t {
sk, ok := k.(string)
if !ok {
continue
}
result[sk] = v
}
return result
default:
return nil
}
}
// GetConfig return object config in p.configs by key
func (p *AdapterConfig) GetConfig(key string) Config {
vm, err := p.getKeyValue(key)
if err != nil {
return nil
}
c := &AdapterConfig{
reader: p.reader,
configs: map[string]interface{}{key: vm},
}
return c
}
// ToObject unmarshal values to object
func (p *AdapterConfig) ToObject(key string, model interface{}) (err error) {
var vm interface{}
if key != "" {
vm, err = p.getKeyValue(key)
if err != nil {
return
}
} else {
vm = p.copy().configs
}
switch p.readerType {
case ReaderTypeJSON:
bs, _ := json.Marshal(vm)
err = json.Unmarshal(bs, model)
case ReaderTypeYAML:
bs, _ := yaml.Marshal(vm)
err = yaml.Unmarshal(bs, model)
}
return err
}
// GetValuesConfig get key's values if values can be Config, or panic
func (p *AdapterConfig) GetValuesConfig(key string) Config {
opt := p.GetMap(key)
return opt.ToConfig(p.readerType)
}
// GetKeyValue get value with key
func (p *AdapterConfig) GetKeyValue(key string) (vm interface{}, err error) {
if len(key) == 0 {
return nil, ErrInvalidKey
}
p.locker.RLock()
defer p.locker.RUnlock()
return p.getKeyValue(key)
}
// SetKeyValue set key value into p.configs
func (p *AdapterConfig) SetKeyValue(key string, value interface{}) (err error) {
if len(key) == 0 {
return ErrInvalidKey
}
p.locker.Lock()
defer p.locker.Unlock()
return p.setKeyValue(key, value)
}
// Dump return p.configs' bytes
func (p *AdapterConfig) Dump() (bs []byte, err error) {
p.locker.Lock()
defer p.locker.Unlock()
return p.reader.Dump(p.configs)
}
// Copy return a copy
func (p *AdapterConfig) Copy() Config {
return p.copy()
}