Repository navigation
Expand file tree
/
Copy pathkey.go
More file actions
636 lines (557 loc) · 17.6 KB
/
Copy pathkey.go
File metadata and controls
636 lines (557 loc) · 17.6 KB
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
package ini
import (
"cmp"
"errors"
"fmt"
"reflect"
"slices"
"strconv"
"strings"
"time"
"unicode/utf8"
)
// Key represents a key under a section.
type Key struct {
s *Section
name string
comment string
value string
// shadows are the values after the first of a key that appears more
// than once, with AllowShadows.
shadows []string
isAutoIncrement bool
isBooleanType bool
nestedValues []string
}
// newKey simply return a key object with given values.
func newKey(s *Section, name, val string) *Key {
return &Key{
s: s,
name: name,
value: val,
}
}
func (k *Key) addShadow(val string) error {
if k.isAutoIncrement || k.isBooleanType {
return errors.New("cannot add shadow to auto-increment or boolean key")
}
// Deduplicate shadows based on their values. Empty values kept with
// PreserveEmptyShadowValues each reset the values before them, so they stay.
keptEmpty := val == "" && k.s.f.options.PreserveEmptyShadowValues
if !k.s.f.options.AllowDuplicateShadowValues && !keptEmpty {
if k.value == val || slices.Contains(k.shadows, val) {
return nil
}
}
k.shadows = append(k.shadows, val)
return nil
}
// AddShadow adds a new shadow key to itself.
func (k *Key) AddShadow(val string) error {
if !k.s.f.options.AllowShadows {
return errors.New("shadow key is not allowed")
}
k.s.f.maybeLock()
defer k.s.f.maybeUnlock()
return k.addShadow(val)
}
func (k *Key) addNestedValue(val string) error {
if k.isAutoIncrement || k.isBooleanType {
return errors.New("cannot add nested value to auto-increment or boolean key")
}
k.nestedValues = append(k.nestedValues, val)
return nil
}
// AddNestedValue adds a nested value to the key.
func (k *Key) AddNestedValue(val string) error {
if !k.s.f.options.AllowNestedValues {
return errors.New("nested value is not allowed")
}
k.s.f.maybeLock()
defer k.s.f.maybeUnlock()
return k.addNestedValue(val)
}
// ValueMapper represents a mapping function for values, e.g., os.ExpandEnv
type ValueMapper func(string) string
// Name returns name of key.
func (k *Key) Name() string {
return k.name
}
// Comment returns the comment lines before the key, with their comment
// symbols.
func (k *Key) Comment() string {
k.s.f.maybeRLock()
defer k.s.f.maybeRUnlock()
return k.comment
}
// SetComment sets the comment lines written before the key. Lines without a
// comment symbol get one.
func (k *Key) SetComment(comment string) {
k.s.f.maybeLock()
defer k.s.f.maybeUnlock()
k.comment = comment
}
// Value returns raw value of key for performance purpose.
func (k *Key) Value() string {
f := k.s.f
if !f.locking {
return k.value
}
f.mu.RLock()
v := k.value
f.mu.RUnlock()
return v
}
// Values returns raw values of key and its shadows if any. Empty
// values are left out, unless the file was loaded with
// PreserveEmptyShadowValues.
func (k *Key) Values() []string {
k.s.f.maybeRLock()
defer k.s.f.maybeRUnlock()
keepEmpty := k.s.f.options.PreserveEmptyShadowValues
vals := make([]string, 0, len(k.shadows)+1)
if keepEmpty || k.value != "" {
vals = append(vals, k.value)
}
for _, v := range k.shadows {
if keepEmpty || v != "" {
vals = append(vals, v)
}
}
return vals
}
// IsBoolean reports whether the key was read as a boolean key, a line
// without a delimiter loaded with AllowBooleanKeys.
func (k *Key) IsBoolean() bool {
k.s.f.maybeRLock()
defer k.s.f.maybeRUnlock()
return k.isBooleanType
}
// NestedValues returns nested values stored in the key.
// It is possible returned value is nil if no nested values stored in the key.
func (k *Key) NestedValues() []string {
k.s.f.maybeRLock()
defer k.s.f.maybeRUnlock()
return k.nestedValues
}
// expandValue takes a raw value and transforms to its final string.
func (k *Key) expandValue(val string) string {
return k.expand(val, 0, new(expansion))
}
// expansion counts the work of one %(name)s expansion.
type expansion struct {
substitutions int
bytes int // total length of the values substitutions made
}
// expand applies the ValueMapper and replaces %(name)s references in val
// with the expanded values of those keys. References nest at most
// depthValues deep, and one expansion makes at most maxSubstitutions
// substitutions producing at most maxExpandedLen bytes in total, so
// reference cycles and values that double at every level stop instead of
// overflowing the stack or using up time and memory.
func (k *Key) expand(val string, depth int, e *expansion) string {
if k.s.f.options.ValueMapper != nil {
val = k.s.f.options.ValueMapper(val)
}
// Fail-fast if no indicate char found for recursive value
if !strings.Contains(val, "%") {
return val
}
for i := 0; i < depthValues && depth < depthValues && e.substitutions < maxSubstitutions; i++ {
vr := varPattern.FindString(val)
if len(vr) == 0 {
break
}
// Take off leading '%(' and trailing ')s'.
noption := vr[2 : len(vr)-2]
// Search in the same section.
// If not found or found the key itself, then search again in default section.
nk, err := k.s.GetKey(noption)
if err != nil || k == nk {
nk, _ = k.s.f.Section("").GetKey(noption)
if nk == nil || nk == k {
// Stop when no results found in the default section, or only
// the key itself, and returns the value as-is.
break
}
}
e.substitutions++
sub := nk.expand(nk.Value(), depth+1, e)
n := len(val) + strings.Count(val, vr)*(len(sub)-len(vr))
if e.bytes+n > maxExpandedLen {
break
}
e.bytes += n
val = strings.ReplaceAll(val, vr, sub)
8000
}
return val
}
// String returns string representation of value.
func (k *Key) String() string {
return k.expandValue(k.Value())
}
// Validate accepts a validate function which can
// return modifed result as key value.
func (k *Key) Validate(fn func(string) string) string {
return fn(k.String())
}
// parseBool returns the boolean value represented by the string.
//
// It accepts 1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On,
// 0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off.
// Any other value returns an error.
func parseBool(str string) (value bool, err error) {
switch str {
case "1", "t", "T", "true", "TRUE", "True", "YES", "yes", "Yes", "y", "ON", "on", "On":
return true, nil
case "0", "f", "F", "false", "FALSE", "False", "NO", "no", "No", "n", "OFF", "off", "Off":
return false, nil
}
return false, fmt.Errorf("parsing \"%s\": invalid syntax", str)
}
// Bool returns bool type value.
func (k *Key) Bool() (bool, error) {
return parseBool(k.String())
}
// Float64 returns float64 type value.
func (k *Key) Float64() (float64, error) {
return strconv.ParseFloat(k.String(), 64)
}
// Int returns int type value.
func (k *Key) Int() (int, error) {
v, err := strconv.ParseInt(k.String(), 0, 64)
return int(v), err
}
// Int64 returns int64 type value.
func (k *Key) Int64() (int64, error) {
return strconv.ParseInt(k.String(), 0, 64)
}
// Uint returns uint type valued.
func (k *Key) Uint() (uint, error) {
u, e := strconv.ParseUint(k.String(), 0, 64)
return uint(u), e
}
// Uint64 returns uint64 type value.
func (k *Key) Uint64() (uint64, error) {
return strconv.ParseUint(k.String(), 0, 64)
}
// Duration returns time.Duration type value.
func (k *Key) Duration() (time.Duration, error) {
return time.ParseDuration(k.String())
}
// TimeFormat parses with given format and returns time.Time type value.
func (k *Key) TimeFormat(format string) (time.Time, error) {
return time.Parse(format, k.String())
}
// TimesFormat parses the elements of the value, split at delim, with the
// given layout. An element that doesn't parse is the zero time. For RFC 3339
// times, use List[time.Time].
func (k *Key) TimesFormat(format, delim string) []time.Time {
vals, _ := parseList(k.Strings(delim), timeParser(format), true, false)
return vals
}
// ValidTimesFormat is TimesFormat without the elements that don't parse.
func (k *Key) ValidTimesFormat(format, delim string) []time.Time {
vals, _ := parseList(k.Strings(delim), timeParser(format), false, false)
return vals
}
// StrictTimesFormat is TimesFormat that returns an error for the first
// element that doesn't parse.
func (k *Key) StrictTimesFormat(format, delim string) ([]time.Time, error) {
return parseList(k.Strings(delim), timeParser(format), false, true)
}
// InTimeFormat returns the value parsed with the given layout when it is the
// same instant as one of candidates, and defaultVal otherwise.
func (k *Key) InTimeFormat(format string, defaultVal time.Time, candidates []time.Time) time.Time {
if v, err := k.TimeFormat(format); err == nil && slices.ContainsFunc(candidates, v.Equal) {
return v
}
return defaultVal
}
// RangeTimeFormat returns the value parsed with the given layout when it is
// between min and max inclusive, and defaultVal otherwise.
func (k *Key) RangeTimeFormat(format string, defaultVal, min, max time.Time) time.Time {
if v, err := k.TimeFormat(format); err == nil && !v.Before(min) && !v.After(max) {
return v
}
return defaultVal
}
func timeParser(format string) func(string) (time.Time, error) {
return func(s string) (time.Time, error) { return time.Parse(format, s) }
}
// Time parses with RFC3339 format and returns time.Time type value.
func (k *Key) Time() (time.Time, error) {
return k.TimeFormat(time.RFC3339)
}
// MustString returns default value if key value is empty.
// It doesn't store the default in the key. Call SetValue for that.
func (k *Key) MustString(defaultVal string) string {
val := k.String()
if len(val) == 0 {
return defaultVal
}
return val
}
// MustBool always returns value without error,
// it returns false if error occurs.
// It doesn't store the default in the key. Call SetValue for that.
func (k *Key) MustBool(defaultVal ...bool) bool {
val, err := k.Bool()
if len(defaultVal) > 0 && err != nil {
return defaultVal[0]
}
return val
}
// MustFloat64 always returns value without error,
// it returns 0.0 if error occurs.
// It doesn't store the default in the key. Call SetValue for that.
func (k *Key) MustFloat64(defaultVal ...float64) float64 {
val, err := k.Float64()
if len(defaultVal) > 0 && err != nil {
return defaultVal[0]
}
return val
}
// MustInt always returns value without error,
// it returns 0 if error occurs.
// It doesn't store the default in the key. Call SetValue for that.
func (k *Key) MustInt(defaultVal ...int) int {
val, err := k.Int()
if len(defaultVal) > 0 && err != nil {
return defaultVal[0]
}
return val
}
// MustInt64 always returns value without error,
// it returns 0 if error occurs.
// It doesn't store the default in the key. Call SetValue for that.
func (k *Key) MustInt64(defaultVal ...int64) int64 {
val, err := k.Int64()
if len(defaultVal) > 0 && err != nil {
return defaultVal[0]
}
return val
}
// MustUint always returns value without error,
// it returns 0 if error occurs.
// It doesn't store the default in the key. Call SetValue for that.
func (k *Key) MustUint(defaultVal ...uint) uint {
val, err := k.Uint()
if len(defaultVal) > 0 && err != nil {
return defaultVal[0]
}
return val
}
// MustUint64 always returns value without error,
// it returns 0 if error occurs.
// It doesn't store the default in the key. Call SetValue for that.
func (k *Key) MustUint64(defaultVal ...uint64) uint64 {
val, err := k.Uint64()
if len(defaultVal) > 0 && err != nil {
return defaultVal[0]
}
return val
}
// MustDuration always returns value without error,
// it returns zero value if error occurs.
// It doesn't store the default in the key. Call SetValue for that.
func (k *Key) MustDuration(defaultVal ...time.Duration) time.Duration {
val, err := k.Duration()
if len(defaultVal) > 0 && err != nil {
return defaultVal[0]
}
return val
}
// MustTimeFormat always parses with given format and returns value without error,
// it returns zero value if error occurs.
// It doesn't store the default in the key. Call SetValue for that.
func (k *Key) MustTimeFormat(format string, defaultVal ...time.Time) time.Time {
val, err := k.TimeFormat(format)
if len(defaultVal) > 0 && err != nil {
return defaultVal[0]
}
return val
}
// MustTime always parses with RFC3339 format and returns value without error,
// it returns zero value if error occurs.
// It doesn't store the default in the key. Call SetValue for that.
func (k *Key) MustTime(defaultVal ...time.Time) time.Time {
return k.MustTimeFormat(time.RFC3339, defaultVal...)
}
// Strings returns list of string divided by given delimiter.
func (k *Key) Strings(delim string) []string {
return splitList(k.String(), delim)
}
// splitList splits str at delim into trimmed elements. A backslash escapes
// delim and another backslash. Before anything else it is kept.
func splitList(str, delim string) []string {
if len(str) == 0 {
return []string{}
}
if delim == "" {
return []string{strings.TrimSpace(str)}
}
maxParts := strings.Count(str, delim) + 1
vals := make([]string, 0, maxParts)
var buf strings.Builder
buf.Grow(len(str))
i := 0
for {
if str[i] == '\\' {
i++
if i >= len(str) {
break
}
if str[i] != '\\' && !strings.HasPrefix(str[i:], delim) {
buf.WriteRune('\\')
}
r, size := utf8.DecodeRuneInString(str[i:])
i += size
buf.WriteRune(r)
} else if strings.HasPrefix(str[i:], delim) {
i += len(delim)
vals = append(vals, strings.TrimSpace(buf.String()))
buf.Reset()
} else {
r, size := utf8.DecodeRuneInString(str[i:])
i += size
buf.WriteRune(r)
}
if i >= len(str) {
break
}
}
if buf.Len() > 0 {
vals = append(vals, strings.TrimSpace(buf.String()))
}
return vals
}
// StringsWithShadows returns list of string divided by given delimiter.
// Shadows will also be appended if any.
func (k *Key) StringsWithShadows(delim string) []string {
vals := k.Values()
results := make([]string, 0, len(vals)*2)
for i := range vals {
if len(vals) == 0 {
continue
}
results = append(results, strings.Split(vals[i], delim)...)
}
for i := range results {
results[i] = k.expandValue(strings.TrimSpace(results[i]))
}
return results
}
// SetValue changes key value.
func (k *Key) SetValue(v string) {
k.s.f.maybeLock()
defer k.s.f.maybeUnlock()
k.value = v
}
// Scalar is a type a value can be parsed as, as struct mapping parses
// fields: strings, booleans, integers and floats of any size, named types of
// those, time.Duration (as "1s" or nanoseconds) and time.Time (RFC 3339).
// A number that doesn't fit the type doesn't parse.
type Scalar interface {
~string | ~bool |
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
~float32 | ~float64 | time.Time
}
// Ordered is a Scalar that Range can compare: any but booleans.
type Ordered interface {
Scalar
cmp.Ordered | time.Time
}
// parse parses s as a T.
func parse[T Scalar](s string) (T, error) {
v, err := parseValue(reflect.TypeFor[T](), s)
if err != nil {
var zero T
return zero, err
}
return v.Interface().(T), nil
}
// parseList parses strs with parse. An element that doesn't parse is an
// error when strict, the zero value when keepInvalid, and left out
// otherwise.
func parseList[T any](strs []string, parse func(string) (T, error), keepInvalid, strict bool) ([]T, error) {
vals := make([]T, 0, len(strs))
for _, s := range strs {
v, err := parse(s)
if err != nil {
if strict {
return nil, err
}
if !keepInvalid {
continue
}
var zero T
v = zero
}
vals = append(vals, v)
}
return vals, nil
}
// List splits the value of k at delim, as Key.Strings does, and parses each
// element as a T. An element that doesn't parse is the zero value, as in
// List[int] of "1, x, 3", which is [1 0 3].
func List[T Scalar](k *Key, delim string) []T {
vals, _ := parseList(k.Strings(delim), parse[T], true, false)
return vals
}
// ValidList is List without the elements that don't parse: ValidList[int]
// of "1, x, 3" is [1 3].
func ValidList[T Scalar](k *Key, delim string) []T {
vals, _ := parseList(k.Strings(delim), parse[T], false, false)
return vals
}
// StrictList is List that returns an error for the first element that
// doesn't parse.
func StrictList[T Scalar](k *Key, delim string) ([]T, error) {
return parseList(k.Strings(delim), parse[T], false, true)
}
// In returns the value of k parsed as a T when it is one of candidates, and
// defaultVal otherwise. T comes from candidates, as in
// In(k, "info", []string{"debug", "info"}). Times match when they are the
// same instant.
func In[T Scalar](k *Key, defaultVal T, candidates []T) T {
if v, err := parse[T](k.String()); err == nil && slices.ContainsFunc(candidates, func(c T) bool { return equal(v, c) }) {
return v
}
return defaultVal
}
// Range returns the value of k parsed as a T wh
5114
en it is between lo and hi
// inclusive, and defaultVal otherwise. Untyped constants make T int, so give
// another type explicitly: Range(k, 0.5, 0, 1) or Range(k, uint8(0), 0, 9).
func Range[T Ordered](k *Key, defaultVal, lo, hi T) T {
if v, err := parse[T](k.String()); err == nil && !less(v, lo) && !less(hi, v) {
return v
}
return defaultVal
}
// equal compares times as instants and other values with ==.
func equal[T Scalar](a, b T) bool {
if t, ok := any(a).(time.Time); ok {
return t.Equal(any(b).(time.Time))
}
return a == b
}
// less reports whether a < b. Times compare as instants and the rest by kind,
// as T can't use < while time.Time is in its type set.
func less[T Ordered](a, b T) bool {
if t, ok := any(a).(time.Time); ok {
return t.Before(any(b).(time.Time))
}
va, vb := reflect.ValueOf(a), reflect.ValueOf(b)
switch va.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return va.Int() < vb.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return va.Uint() < vb.Uint()
case reflect.Float32, reflect.Float64:
return va.Float() < vb.Float()
default:
return va.String() < vb.String()
}
}