-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathconfig.go
525 lines (419 loc) · 12.1 KB
/
config.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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
package hocon
import (
"fmt"
"regexp"
"strconv"
"strings"
"time"
)
// Type of an hocon Value
type Type int
// Type constants
const (
ObjectType Type = iota
StringType
ArrayType
NumberType
BooleanType
NullType
SubstitutionType
ConcatenationType
valueWithAlternativeType
)
// Config stores the root of the configuration tree
// and provides an API to retrieve configuration values with the path expressions
type Config struct {
root Value
}
// String method returns the string representation of the Config object
func (c *Config) String() string { return c.root.String() }
// GetRoot method returns the root value of the configuration
func (c *Config) GetRoot() Value {
return c.root
}
// GetObject method finds the value at the given path and returns it as an Object, returns nil if the value is not found
func (c *Config) GetObject(path string) Object {
value := c.Get(path)
if value == nil {
return nil
}
return value.(Object)
}
// GetConfig method finds the value at the given path and returns it as a Config, returns nil if the value is not found
func (c *Config) GetConfig(path string) *Config {
value := c.GetObject(path)
if value == nil {
return nil
}
return value.ToConfig()
}
// GetStringMap method finds the value at the given path and returns it as a map[string]Value
// returns nil if the value is not found
func (c *Config) GetStringMap(path string) map[string]Value {
return c.GetObject(path)
}
// GetStringMapString method finds the value at the given path and returns it as a map[string]string
// returns nil if the value is not found
func (c *Config) GetStringMapString(path string) map[string]string {
value := c.Get(path)
if value == nil {
return nil
}
object := value.(Object)
var m = make(map[string]string, len(object))
for k, v := range object {
m[k] = v.String()
}
return m
}
// GetArray method finds the value at the given path and returns it as an Array, returns nil if the value is not found
func (c *Config) GetArray(path string) Array {
value := c.Get(path)
if value == nil {
return nil
}
return value.(Array)
}
// GetIntSlice method finds the value at the given path and returns it as []int, returns nil if the value is not found
func (c *Config) GetIntSlice(path string) []int {
value := c.Get(path)
if value == nil {
return nil
}
arr := value.(Array)
slice := make([]int, 0, len(arr))
for _, v := range arr {
slice = append(slice, int(v.(Int)))
}
return slice
}
// GetStringSlice method finds the value at the given path and returns it as []string
// returns nil if the value is not found
func (c *Config) GetStringSlice(path string) []string {
value := c.Get(path)
if value == nil {
return nil
}
arr := value.(Array)
slice := make([]string, 0, len(arr))
for _, v := range arr {
slice = append(slice, v.String())
}
return slice
}
// GetString method finds the value at the given path and returns it as a String
// returns empty string if the value is not found
func (c *Config) GetString(path string) string {
value := c.Get(path)
if value == nil {
return ""
}
return value.String()
}
// GetInt method finds the value at the given path and returns it as an Int, returns zero if the value is not found
func (c *Config) GetInt(path string) int {
value := c.Get(path)
if value == nil {
return 0
}
switch val := value.(type) {
case Int:
return int(val)
case String:
intValue, err := strconv.Atoi(string(val))
if err != nil {
panic(err)
}
return intValue
default:
panic("cannot parse value: " + val.String() + " to int!")
}
}
// GetFloat32 method finds the value at the given path and returns it as a Float32
// returns float32(0.0) if the value is not found
func (c *Config) GetFloat32(path string) float32 {
value := c.Get(path)
if value == nil {
return float32(0.0)
}
switch val := value.(type) {
case Float32:
return float32(val)
case Float64:
return float32(val)
case String:
floatValue, err := strconv.ParseFloat(string(val), 32)
if err != nil {
panic(err)
}
return float32(floatValue)
default:
panic("cannot parse value: " + val.String() + " to float32!")
}
}
// GetFloat64 method finds the value at the given path and returns it as a Float64
// returns 0.0 if the value is not found
func (c *Config) GetFloat64(path string) float64 {
value := c.Get(path)
if value == nil {
return 0.0
}
switch val := value.(type) {
case Float64:
return float64(val)
case Float32:
return float64(val)
case String:
floatValue, err := strconv.ParseFloat(string(val), 64)
if err != nil {
panic(err)
}
return floatValue
default:
panic("cannot parse value: " + val.String() + "to float64!")
}
}
// GetBoolean method finds the value at the given path and returns it as a Boolean
// returns false if the value is not found
func (c *Config) GetBoolean(path string) bool {
value := c.Get(path)
if value == nil {
return false
}
switch val := value.(type) {
case Boolean:
return bool(val)
case String:
switch val {
case "true", "yes", "on":
return true
case "false", "no", "off":
return false
default:
panic("cannot parse value: " + val + " to boolean!")
}
default:
panic("cannot parse value: " + val.String() + " to boolean!")
}
}
// GetDuration method finds the value at the given path and returns it as a time.Duration
// returns 0 if the value is not found
func (c *Config) GetDuration(path string) time.Duration {
value := c.Get(path)
if value == nil {
return 0
}
return time.Duration(value.(Duration))
}
// Get method finds the value at the given path and returns it without casting to any type
// returns nil if the value is not found
func (c *Config) Get(path string) Value {
if c.root.Type() != ObjectType {
return nil
}
return c.root.(Object).find(path)
}
// WithFallback method returns a new *Config (or the current config, if the given fallback doesn't get used)
// 1. merges the values of the current and fallback *Configs, if the root of both of them are of type Object
// for the same keys current values overrides the fallback values
// 2. if any of the *Configs has non-object root then returns the current *Config ignoring the fallback parameter
func (c *Config) WithFallback(fallback *Config) *Config {
if current, ok := c.root.(Object); ok {
if fallbackObject, ok := fallback.root.(Object); ok {
resultConfig := fallbackObject.copy()
mergeObjects(resultConfig, current)
return resultConfig.ToConfig()
}
}
return c
}
// Value interface represents a value in the configuration tree, all the value types implements this interface
type Value interface {
Type() Type
String() string
isConcatenable() bool
}
// String represents a string value
type String string
// Type String
func (s String) Type() Type { return StringType }
func (s String) String() string {
str := strings.Trim(string(s), `"`)
if str == "" {
return `""`
}
compile := regexp.MustCompile("[ !\\\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~]+")
if compile.MatchString(str) {
return fmt.Sprintf(`"%s"`, str)
}
return str
}
func (s String) isConcatenable() bool { return true }
// valueWithAlternative represents a value with Substitution which might override the original value
type valueWithAlternative struct {
value Value
alternative *Substitution
}
func (s *valueWithAlternative) Type() Type { return valueWithAlternativeType }
func (s *valueWithAlternative) String() string {
return fmt.Sprintf("(%s | %s)", s.value, s.alternative.String())
}
func (s *valueWithAlternative) isConcatenable() bool { return false }
// Object represents an object node in the configuration tree
type Object map[string]Value
// Type Object
func (o Object) Type() Type { return ObjectType }
func (o Object) isConcatenable() bool { return false }
// String method returns the string representation of the Object
func (o Object) String() string {
var builder strings.Builder
itemsSize := len(o)
i := 1
builder.WriteString(objectStartToken)
for key, value := range o {
builder.WriteString(key)
builder.WriteString(colonToken)
builder.WriteString(value.String())
if i < itemsSize {
builder.WriteString(", ")
}
i++
}
builder.WriteString(objectEndToken)
return builder.String()
}
// ToConfig method converts object to *Config
func (o Object) ToConfig() *Config {
return &Config{o}
}
func (o Object) find(path string) Value {
keys := strings.Split(path, dotToken)
size := len(keys)
lastKey := keys[size-1]
keysWithoutLast := keys[:size-1]
object := o
for _, key := range keysWithoutLast {
value, ok := object[key]
if !ok {
return nil
}
object = value.(Object)
}
return object[lastKey]
}
func (o Object) copy() Object {
result := Object{}
for k, v := range o {
subObject, ok := v.(Object)
if ok {
result[k] = subObject.copy()
} else {
result[k] = v
}
}
return result
}
// Array represents an array node in the configuration tree
type Array []Value
// Type Array
func (a Array) Type() Type { return ArrayType }
func (a Array) isConcatenable() bool { return false }
// String method returns the string representation of the Array
func (a Array) String() string {
if len(a) == 0 {
return "[]"
}
var builder strings.Builder
builder.WriteString(arrayStartToken)
builder.WriteString(a[0].String())
for _, value := range a[1:] {
builder.WriteString(commaToken)
builder.WriteString(value.String())
}
builder.WriteString(arrayEndToken)
return builder.String()
}
// Int represents an Integer value
type Int int
// Type Number
func (i Int) Type() Type { return NumberType }
func (i Int) String() string { return strconv.Itoa(int(i)) }
func (i Int) isConcatenable() bool { return true }
// Float32 represents a Float32 value
type Float32 float32
// Type Number
func (f Float32) Type() Type { return NumberType }
func (f Float32) String() string { return strconv.FormatFloat(float64(f), 'e', -1, 32) }
func (f Float32) isConcatenable() bool { return false }
// Float64 represents a Float64 value
type Float64 float64
// Type Number
func (f Float64) Type() Type { return NumberType }
func (f Float64) String() string { return strconv.FormatFloat(float64(f), 'e', -1, 64) }
func (f Float64) isConcatenable() bool { return false }
// Boolean represents bool value
type Boolean bool
func newBooleanFromString(value string) Boolean {
switch value {
case "true", "yes", "on":
return true
case "false", "no", "off":
return false
default:
panic(fmt.Sprintf("cannot parse value: %s to Boolean!", value))
}
}
// Type Boolean
func (b Boolean) Type() Type { return BooleanType }
func (b Boolean) String() string { return strconv.FormatBool(bool(b)) }
func (b Boolean) isConcatenable() bool { return true }
// Substitution refers to another value in the configuration tree
type Substitution struct {
path string
optional bool
}
// Type Substitution
func (s *Substitution) Type() Type { return SubstitutionType }
func (s *Substitution) isConcatenable() bool { return true }
// String method returns the string representation of the Substitution
func (s *Substitution) String() string {
var builder strings.Builder
builder.WriteString("${")
if s.optional {
builder.WriteString("?")
}
builder.WriteString(s.path)
builder.WriteString("}")
return builder.String()
}
// Null represents a null value
type Null string
const null Null = "null"
// Type Null
func (n Null) Type() Type { return NullType }
func (n Null) String() string { return string(null) }
func (n Null) isConcatenable() bool { return true }
// Duration represents a duration value
type Duration time.Duration
// Type Duration
func (d Duration) Type() Type { return StringType }
func (d Duration) String() string { return time.Duration(d).String() }
func (d Duration) isConcatenable() bool { return false }
type concatenation Array
func (c concatenation) Type() Type { return ConcatenationType }
func (c concatenation) isConcatenable() bool { return true }
func (c concatenation) containsObject() bool {
for _, value := range c {
if value.Type() == ObjectType {
return true
}
}
return false
}
func (c concatenation) String() string {
var builder strings.Builder
for _, value := range c {
builder.WriteString(value.String())
}
return builder.String()
}