Repository navigation
Expand file tree
/
Copy pathstruct.go
More file actions
951 lines (858 loc) · 26.5 KB
/
Copy pathstruct.go
File metadata and controls
951 lines (858 loc) · 26.5 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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
package ini
import (
"bytes"
"errors"
"fmt"
"reflect"
"slices"
"strconv"
"strings"
"time"
"unicode"
)
// NameMapper represents a ini tag name mapper.
type NameMapper func(string) string
// Built-in name getters.
var (
// SnakeCase converts to format SNAKE_CASE.
SnakeCase NameMapper = func(raw string) string {
newstr := make([]rune, 0, len(raw))
for i, chr := range raw {
if isUpper := 'A' <= chr && chr <= 'Z'; isUpper {
if i > 0 {
newstr = append(newstr, '_')
}
}
newstr = append(newstr, unicode.ToUpper(chr))
}
return string(newstr)
}
// TitleUnderscore converts to format title_underscore.
TitleUnderscore NameMapper = func(raw string) string {
newstr := make([]rune, 0, len(raw))
for i, chr := range raw {
if isUpper := 'A' <= chr && chr <= 'Z'; isUpper {
if i > 0 {
newstr = append(newstr, '_')
}
chr -= 'A' - 'a'
}
newstr = append(newstr, chr)
}
return string(newstr)
}
)
func (s *Section) parseFieldName(raw, actual string) string {
if len(actual) > 0 {
return actual
}
if s.f.options.NameMapper != nil {
return s.f.options.NameMapper(raw)
}
return raw
}
func parseDelim(actual string) string {
if len(actual) > 0 {
return actual
}
return ","
}
// Marshaler is implemented by types that format themselves as a key value.
// ReflectFrom and Marshal call MarshalINI for fields, pointer fields and
// slice elements of such a type, whatever its kind.
type Marshaler interface {
MarshalINI() ([]byte, error)
}
// Unmarshaler is implemented by types that parse themselves from a key value.
// MapTo, StrictMapTo, Unmarshal, List, In and Range call UnmarshalINI with the
// value as Key.String returns it, or with one element of a list. An error
// leaves the field unchanged, and StrictMapTo and StrictList return it.
//
// A struct type that implements Marshaler or Unmarshaler maps to a key, not
// to a section.
type Unmarshaler interface {
UnmarshalINI([]byte) error
}
var (
timeType = reflect.TypeFor[time.Time]()
marshalerType = reflect.TypeFor[Marshaler]()
unmarshalerType = reflect.TypeFor[Unmarshaler]()
)
// isMarshaler and isUnmarshaler report whether t, or a pointer to t,
// implements Marshaler or Unmarshaler.
func isMarshaler(t reflect.Type) bool {
return reflect.PointerTo(t).Implements(marshalerType)
}
func isUnmarshaler(t reflect.Type) bool {
return reflect.PointerTo(t).Implements(unmarshalerType)
}
// isCustomType reports whether t formats or parses itself, so that it maps
// to a key value whatever its kind.
func isCustomType(t reflect.Type) bool {
return isMarshaler(t) || isUnmarshaler(t)
}
// isStructType reports whether t is a struct type that maps to a section,
// which is any struct type but time.Time and custom types.
func isStructType(t reflect.Type) bool {
return t.Kind() == reflect.Struct && t != timeType && !isCustomType(t)
}
// isValueType reports whether a key value can be parsed as or formatted from
// a value of type t.
func isValueType(t reflect.Type) bool {
if t == timeType || isCustomType(t) {
return true
}
switch t.Kind() {
case reflect.String, reflect.Bool,
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64:
return true
}
return false
}
// isSliceElemType reports whether slices of t are supported.
func isSliceElemType(t reflect.Type) bool {
if t == timeType || isCustomType(t) {
return true
}
switch t.Kind() {
case reflect.String, reflect.Bool, reflect.Int, reflect.Int64, reflect.Uint, reflect.Uint64, reflect.Float64:
return true
}
return false
}
// parseValue parses str as a value of type t, for which isValueType is true.
func parseValue(t reflect.Type, str string) (reflect.Value, error) {
v := reflect.New(t).Elem()
if isUnmarshaler(t) {
err := v.Addr().Interface().(Unmarshaler).UnmarshalINI([]byte(str))
return v, err
}
if t == timeType {
ti, err := time.Parse(time.RFC3339, str)
if err != nil {
return v, err
}
v.Set(reflect.ValueOf(ti))
return v, nil
}
switch t.Kind() {
case reflect.String:
v.SetString(str)
case reflect.Bool:
b, err := parseBool(str)
if err != nil {
return v, err
}
v.SetBool(b)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
i, err := strconv.ParseInt(str, 0, 64)
// A duration can also be given as a number of nanoseconds.
if t.Name() == "Duration" {
if d, derr := time.ParseDuration(str); derr == nil {
i, err = int64(d), nil
}
}
if err != nil {
return v, err
}
if v.OverflowInt(i) {
return v, fmt.Errorf("value %q overflows %s", str, t)
}
v.SetInt(i)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
u, err := strconv.ParseUint(str, 0, 64)
if err != nil {
return v, err
}
if v.OverflowUint(u) {
return v, fmt.Errorf("value %q overflows %s", str, t)
}
v.SetUint(u)
case reflect.Float32, reflect.Float64:
f, err := strconv.ParseFloat(str, 64)
if err != nil {
return v, err
}
if v.OverflowFloat(f) {
return v, fmt.Errorf("value %q overflows %s", str, t)
}
v.SetFloat(f)
default:
return v, fmt.Errorf("unsupported type %q", t)
}
return v, nil
}
// formatValue does the opposite thing as parseValue.
func formatValue(v reflect.Value) (string, error) {
t := v.Type()
if isMarshaler(t) {
var m Marshaler
switch {
case t.Implements(marshalerType):
m = v.Interface().(Marshaler)
case v.CanAddr():
m = v.Addr().Interface().(Marshaler)
default:
// MarshalINI has a pointer receiver, so call it on a copy.
p := reflect.New(t)
p.Elem().Set(v)
m = p.Interface().(Marshaler)
}
b, err := m.MarshalINI()
return string(b), err
}
if t == timeType {
return v.Interface().(time.Time).Format(time.RFC3339Nano), nil
}
switch v.Kind() {
case reflect.String:
return v.String(), nil
case reflect.Bool:
return fmt.Sprint(v.Bool()), nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return fmt.Sprint(v.Int()), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return fmt.Sprint(v.Uint()), nil
case reflect.Float32, reflect.Float64:
return fmt.Sprint(v.Float()), nil
}
return "", fmt.Errorf("unsupported type %q", t)
}
// defaultComment sets *c to comment if it is empty, under the file's lock.
func (f *File) defaultComment(c *string, comment string) {
f.maybeLock()
defer f.maybeUnlock()
if *c == "" {
*c = comment
}
}
// tooDeep reports whether path, the struct types being mapped or reflected
// from the outermost one, already holds t twice. Section names are not
// nested, so a recursive struct type would use the same sections forever: it
// is followed one level deep only.
func tooDeep(path []reflect.Type, t reflect.Type) bool {
n := 0
for _, p := range path {
if p == t {
n++
}
}
return n >= 2
}
// decodeSlice sets proper values to slice based on its type.
func decodeSlice(key *Key, field reflect.Value, delim string, allowShadow, isStrict bool) error {
elemType := field.Type().Elem()
if !isSliceElemType(elemType) {
return fmt.Errorf("unsupported type '[]%s'", elemType)
}
var strs []string
if allowShadow {
// As in v1, each value is split at delim with no escapes, and each
// element trimmed and expanded. An empty value, kept with
// PreserveEmptyShadowValues, is an empty element, unless it is the only
// one: an empty slice is written as one empty value.
vals := key.Values()
if len(vals) == 1 && vals[0] == "" {
vals = nil
}
for _, v := range vals {
for _, s := range strings.Split(v, delim) {
strs = append(strs, key.expandValue(strings.TrimSpace(s)))
}
}
} else {
strs = key.Strings(delim)
}
numVals := len(strs)
if numVals == 0 {
return nil
}
slice := reflect.MakeSlice(field.Type(), numVals, numVals)
for i, str := range strs {
val, err := parseValue(elemType, str)
if err != nil {
if isStrict {
return err
}
// An invalid element is left as the zero value.
continue
}
slice.Index(i).Set(val)
}
field.Set(slice)
return nil
}
func wrapStrictError(err error, isStrict bool) error {
if isStrict {
return err
}
return nil
}
// decodeValue sets proper value to field based on its type,
// but it does not return error for failing parsing,
// because we want to use default value that is already assigned to struct.
func decodeValue(t reflect.Type, key *Key, field reflect.Value, delim string, allowShadow, isStrict bool) error {
if t.Kind() == reflect.Slice && !isCustomType(t) {
return decodeSlice(key, field, delim, allowShadow, isStrict)
}
vt := t
isPtr := t.Kind() == reflect.Pointer
if isPtr {
vt = t.Elem()
}
if !isValueType(vt) {
return fmt.Errorf("unsupported type %q", t)
}
str := key.String()
// An empty string keeps the default value of a string field, unless
// the type parses itself.
if vt.Kind() == reflect.String && len(str) == 0 && !isPtr && !isUnmarshaler(vt) {
return nil
}
val, err := parseValue(vt, str)
if err != nil {
return wrapStrictError(err, isStrict)
}
if isPtr {
ptr := reflect.New(vt)
ptr.Elem().Set(val)
val = ptr
}
field.Set(val)
return nil
}
func parseTagOptions(tag string) (rawName string, omitEmpty bool, allowShadow bool, allowNonUnique bool, extends bool) {
opts := strings.SplitN(tag, ",", 5)
rawName = opts[0]
for _, opt := range opts[1:] {
omitEmpty = omitEmpty || (opt == "omitempty")
allowShadow = allowShadow || (opt == "allowshadow")
allowNonUnique = allowNonUnique || (opt == "nonunique")
extends = extends || (opt == "extends")
}
return rawName, omitEmpty, allowShadow, allowNonUnique, extends
}
// decodeStruct maps the given value to the matching field of the given section.
// The sectionIndex is the index (if non unique sections are enabled) to which the value should be added.
// The path holds the struct types being mapped, see tooDeep.
func (s *Section) decodeStruct(val reflect.Value, isStrict bool, sectionIndex int, sectionName string, path []reflect.Type) error {
if val.Kind() == reflect.Pointer {
val = val.Elem()
}
typ := val.Type()
path = append(path, typ)
for i := 0; i < typ.NumField(); i++ {
field := val.Field(i)
tpField := typ.Field(i)
tag := tpField.Tag.Get("ini")
if tag == "-" {
continue
}
rawName, _, allowShadow, allowNonUnique, extends := parseTagOptions(tag)
fieldName := s.parseFieldName(tpField.Name, rawName)
if len(fieldName) == 0 || !field.CanSet() {
continue
}
isStruct := isStructType(tpField.Type)
isStructPtr := tpField.Type.Kind() == reflect.Pointer && isStructType(tpField.Type.Elem())
isAnonymousPtr := isStructPtr && tpField.Anonymous
structType := tpField.Type
if isStructPtr {
structType = tpField.Type.Elem()
}
if isAnonymousPtr && field.IsNil() && !tooDeep(path, structType) {
field.Set(reflect.New(structType))
}
if extends && (isAnonymousPtr || (isStruct && tpField.Anonymous)) {
if tooDeep(path, structType) {
continue
}
fieldSection := s
if rawName != "" {
sectionName = s.name + s.f.options.ChildSectionDelimiter + rawName
if secs, err := s.f.SectionsByName(sectionName); err == nil && sectionIndex < len(secs) {
fieldSection = secs[sectionIndex]
}
}
if err := fieldSection.decodeStruct(field, isStrict, sectionIndex, sectionName, path); err != nil {
return fmt.Errorf("map to field %q: %v", fieldName, err)
}
continue
} else if isStruct || isStructPtr {
if secs, err := s.f.SectionsByName(fieldName); err == nil {
if tooDeep(path, structType) {
continue
}
if len(secs) <= sectionIndex {
return fmt.Errorf("there are not enough sections (%d <= %d) for the field %q", len(secs), sectionIndex, fieldName)
}
// Only set the f
8BD0
ield to non-nil struct value if we have a section for it.
// Otherwise, we end up with a non-nil struct ptr even though there is no data.
if isStructPtr && field.IsNil() {
field.Set(reflect.New(structType))
}
if err = secs[sectionIndex].decodeStruct(field, isStrict, sectionIndex, fieldName, path); err != nil {
return fmt.Errorf("map to field %q: %v", fieldName, err)
}
continue
}
}
// Map non-unique sections
if allowNonUnique && tpField.Type.Kind() == reflect.Slice {
newField, err := s.decodeSections(fieldName, field, isStrict, path)
if err != nil {
return fmt.Errorf("map to slice %q: %v", fieldName, err)
}
field.Set(newField)
continue
}
if key, err := s.GetKey(fieldName); err == nil {
delim := parseDelim(tpField.Tag.Get("delim"))
if err = decodeValue(tpField.Type, key, field, delim, allowShadow, isStrict); err != nil {
return fmt.Errorf("set field %q: %v", fieldName, err)
}
}
}
return nil
}
// decodeSections maps all sections with the same name and returns the new value.
// The type of the Value must be a slice of structs or of pointers to structs.
func (s *Section) decodeSections(secName string, val reflect.Value, isStrict bool, path []reflect.Type) (reflect.Value, error) {
elemType := val.Type().Elem()
isPtr := elemType.Kind() == reflect.Pointer
structType := elemType
if isPtr {
structType = elemType.Elem()
}
if !isStructType(structType) {
return reflect.Value{}, fmt.Errorf("unsupported type %q for non-unique sections", val.Type())
}
secs, err := s.f.SectionsByName(secName)
if err != nil || tooDeep(path, structType) {
// The slice is left as it is when there are no sections.
return val, nil
}
for i, sec := range secs {
elem := reflect.New(structType)
if err = sec.decodeStruct(elem, isStrict, i, sec.name, path); err != nil {
return reflect.Value{}, fmt.Errorf("map to field from section %q: %v", secName, err)
}
if !isPtr {
elem = elem.Elem()
}
val = reflect.Append(val, elem)
}
return val, nil
}
// mapTo maps a section to object v.
func (s *Section) mapTo(v any, isStrict bool) error {
val := reflect.ValueOf(v)
if val.Kind() != reflect.Pointer || val.IsNil() {
return errors.New("not a pointer to a struct")
}
typ := val.Type().Elem()
for typ.Kind() == reflect.Pointer {
typ = typ.Elem()
}
if typ.Kind() != reflect.Struct && typ.Kind() != reflect.Slice {
return errors.New("not a pointer to a struct")
}
// Allocate the nil pointers v points through.
val = val.Elem()
for val.Kind() == reflect.Pointer {
if val.IsNil() {
val.Set(reflect.New(val.Type().Elem()))
}
val = val.Elem()
}
if typ.Kind() == reflect.Slice {
newField, err := s.decodeSections(s.name, val, isStrict, nil)
if err != nil {
return err
}
val.Set(newField)
return nil
}
return s.decodeStruct(val, isStrict, 0, s.name, nil)
}
// MapTo maps section to given struct.
func (s *Section) MapTo(v any) error {
return s.mapTo(v, false)
}
// StrictMapTo maps section to given struct in strict mode,
// which returns all possible error including value parsing error.
func (s *Section) StrictMapTo(v any) error {
return s.mapTo(v, true)
}
// MapTo maps file to given struct.
func (f *File) MapTo(v any) error {
return f.Section("").MapTo(v)
}
// StrictMapTo maps file to given struct in strict mode,
// which returns all possible error including value parsing error.
func (f *File) StrictMapTo(v any) error {
return f.Section("").StrictMapTo(v)
}
// MapTo loads a data source with opts and maps it to the given struct.
// NameMapping sets how field names map to section and key names.
func MapTo(v, source any, opts ...LoadOption) error {
cfg, err := Load(source, opts...)
if err != nil {
return err
}
return cfg.MapTo(v)
}
// StrictMapTo loads a data source with opts and maps it to the given struct
// in strict mode, which returns all possible error including value parsing
// error.
func StrictMapTo(v, source any, opts ...LoadOption) error {
cfg, err := Load(source, opts...)
if err != nil {
return err
}
return cfg.StrictMapTo(v)
}
10000
div>
// encodeSlice does the opposite thing as decodeSlice.
func encodeSlice(key *Key, field reflect.Value, delim string, allowShadow bool) error {
if field.Len() == 0 {
return nil
}
elemType := field.Type().Elem()
if !isSliceElemType(elemType) {
return fmt.Errorf("unsupported type '[]%s'", elemType)
}
vals := make([]string, field.Len())
for i := range vals {
var err error
if vals[i], err = formatValue(field.Index(i)); err != nil {
return err
}
}
if allowShadow {
// Each element is a value of its own, and the reader splits values
// at delim without escapes, as v1 did.
for _, v := range vals {
if strings.Contains(v, delim) {
return fmt.Errorf("element %q contains the delimiter %q, which an allowshadow slice can't hold", v, delim)
}
}
if len(vals) > 1 && !key.s.f.options.AllowShadows {
return errors.New("shadow key is not allowed")
}
// Shadows deduplicated as the file's options say, on a key that
// isn't boolean or auto-increment.
tmp := newKey(key.s, key.name, vals[0])
for _, val := range vals[1:] {
if err := tmp.addShadow(val); err != nil {
return err
}
}
key.s.f.maybeLock()
key.value, key.shadows = tmp.value, tmp.shadows
key.s.f.maybeUnlock()
return nil
}
for i := range vals {
vals[i] = escapeSliceElem(vals[i], delim)
}
key.SetValue(strings.Join(vals, delim))
return nil
}
// escapeSliceElem escapes s so that Key.Strings reads it back as one element
// even when it contains delim. Key.Strings keeps a backslash unless it comes
// before another backslash, delim or the end, so only those are doubled and
// paths like C:\dir are written as they are.
func escapeSliceElem(s, delim string) string {
if !strings.Contains(s, `\`) && !strings.Contains(s, delim) {
return s
}
var b strings.Builder
for i := 0; i < len(s); i++ {
rest := s[i:]
switch {
case strings.HasPrefix(rest, delim):
b.WriteString(`\` + delim)
i += len(delim) - 1
case s[i] == '\\' && (i+1 == len(s) || s[i+1] == '\\' || strings.HasPrefix(s[i+1:], delim)):
b.WriteString(`\\`)
default:
b.WriteByte(s[i])
}
}
return b.String()
}
// encodeValue does the opposite thing as decodeValue.
func encodeValue(t reflect.Type, key *Key, field reflect.Value, delim string, allowShadow bool) error {
switch {
case t.Kind() == reflect.Slice && !isCustomType(t):
return encodeSlice(key, field, delim, allowShadow)
case t.Kind() == reflect.Pointer:
if !field.IsNil() {
return encodeValue(t.Elem(), key, field.Elem(), delim, allowShadow)
}
case isValueType(t):
v, err := formatValue(field)
if err != nil {
return err
}
key.SetValue(v)
default:
return fmt.Errorf("unsupported type %q", t)
}
return nil
}
// CR: copied from encoding/json/encode.go with modifications of time.Time support.
// TODO: add more test coverage.
func isEmptyValue(v reflect.Value) bool {
if v.Type() == timeType {
return v.Interface().(time.Time).IsZero()
}
switch v.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Interface, reflect.Pointer:
return v.IsNil()
}
return false
}
// StructReflector is the interface implemented by struct types that can extract themselves into INI objects.
type StructReflector interface {
ReflectINIStruct(*File) error
}
// encodeStruct reflects the section from val. The path holds the struct types
// being reflected from, see tooDeep.
func (s *Section) encodeStruct(val reflect.Value, path []reflect.Type) error {
if val.Kind() == reflect.Pointer {
val = val.Elem()
}
typ := val.Type()
path = append(path, typ)
for i := 0; i < typ.NumField(); i++ {
if !val.Field(i).CanInterface() {
continue
}
field := val.Field(i)
tpField := typ.Field(i)
tag := tpField.Tag.Get("ini")
if tag == "-" {
continue
}
rawName, omitEmpty, allowShadow, allowNonUnique, extends := parseTagOptions(tag)
if omitEmpty && isEmptyValue(field) {
continue
}
if r, ok := field.Interface().(StructReflector); ok {
if err := r.ReflectINIStruct(s.f); err != nil {
return err
}
continue
}
fieldName := s.parseFieldName(tpField.Name, rawName)
if len(fieldName) == 0 || !field.CanSet() {
continue
}
// A nil pointer has nothing to write.
if field.Kind() == reflect.Pointer && field.IsNil() {
continue
}
isStruct := isStructType(tpField.Type)
isStructPtr := tpField.Type.Kind() == reflect.Pointer && isStructType(tpField.Type.Elem())
structType := tpField.Type
if isStructPtr {
structType = tpField.Type.Elem()
}
if extends && tpField.Anonymous && (isStruct || isStructPtr) {
if tooDeep(path, structType) {
continue
}
if err := s.encodeStruct(field, path); err != nil {
return fmt.Errorf("reflect from field %q: %v", fieldName, err)
}
continue
}
if isStruct || isStructPtr {
if tooDeep(path, structType) {
continue
}
// Note: The only error here is section doesn't exist.
sec, err := s.f.GetSection(fieldName)
if err != nil {
// Note: fieldName can never be empty here, ignore error.
sec, _ = s.f.NewSection(fieldName)
}
// Add comment from comment tag
s.f.defaultComment(&sec.comment, tpField.Tag.Get("comment"))
if err = sec.encodeStruct(field, path); err != nil {
return fmt.Errorf("reflect from field %q: %v", fieldName, err)
}
continue
}
if allowNonUnique && tpField.Type.Kind() == reflect.Slice {
if field.Len() == 0 {
continue
}
structType = tpField.Type.Elem()
if structType.Kind() == reflect.Pointer {
structType = structType.Elem()
}
if !isStructType(structType) {
return fmt.Errorf("field %q is not a slice of pointer or struct", fieldName)
}
if tooDeep(path, structType) {
continue
}
for i := 0; i < field.Len(); i++ {
elem := field.Index(i)
if elem.Kind() == reflect.Pointer && elem.IsNil() {
continue
}
sec, err := s.f.NewSection(fieldName)
if err != nil {
return err
}
// Add comment from comment tag
s.f.defaultComment(&sec.comment, tpField.Tag.Get("comment"))
if err := sec.encodeStruct(elem, path); err != nil {
return fmt.Errorf("reflect from field %q: %v", fieldName, err)
}
}
continue
}
// Note: Same reason as section.
key, err := s.GetKey(fieldName)
if err != nil {
key, _ = s.NewKey(fieldName, "")
}
// Add comment from comment tag
s.f.defaultComment(&key.comment, tpField.Tag.Get("comment"))
delim := parseDelim(tpField.Tag.Get("delim"))
if err = encodeValue(tpField.Type, key, field, delim, allowShadow); err != nil {
return fmt.Errorf("reflect field %q: %v", fieldName, err)
}
}
return nil
}
// ReflectFrom reflects section from given struct. It overwrites existing ones.
func (s *Section) ReflectFrom(v any) error {
typ := reflect.TypeOf(v)
val := reflect.ValueOf(v)
if typ == nil || (typ.Kind() == reflect.Pointer && val.IsNil()) {
return errors.New("not a pointer to a struct")
}
// A pointer to a pointer to a struct is accepted too, as in
// ReflectFrom(&cfg) with cfg a *Config.
for typ.Kind() == reflect.Pointer && typ.Elem().Kind() == reflect.Pointer {
if val = val.Elem(); val.IsNil() {
return errors.New("not a pointer to a struct")
}
typ = typ.Elem()
}
if !s.f.isDefaultSection(s.name) && s.f.options.AllowNonUniqueSections &&
(typ.Kind() == reflect.Slice || typ.Kind() == reflect.Pointer) {
if typ.Kind() == reflect.Pointer && !isStructType(typ.Elem()) {
return errors.New("not a pointer to a struct")
}
if typ.Kind() == reflect.Slice && (typ.Elem().Kind() != reflect.Pointer || !isStructType(typ.Elem().Elem())) {
return errors.New("not a slice of pointers to structs")
}
// Clear sections to make sure none exists before adding the new ones
s.f.DeleteSection(s.name)
if typ.Kind() == reflect.Pointer {
sec, err := s.f.NewSection(s.name)
if err != nil {
return err
}
return sec.encodeStruct(val.Elem(), nil)
}
for i := 0; i < val.Len(); i++ {
elem := val.Index(i)
if elem.IsNil() {
continue
}
sec, err := s.f.NewSection(s.name)
if err != nil {
return err
}
err = sec.encodeStruct(elem, nil)
if err != nil {
return fmt.Errorf("reflect from %dth field: %v", i, err)
}
}
return nil
}
if typ.Kind() != reflect.Pointer || typ.Elem().Kind() != reflect.Struct {
return errors.New("not a pointer to a struct")
}
return s.encodeStruct(val.Elem(), nil)
}
// ReflectFrom reflects file from given struct.
func (f *File) ReflectFrom(v any) error {
return f.Section("").ReflectFrom(v)
}
// Unmarshal parses INI data with opts and maps it to the struct v points to,
// as File.MapTo does. It reads what Marshal writes: when v has allowshadow
// fields it loads with AllowShadows, AllowDuplicateShadowValues and
// PreserveEmptyShadowValues, and when it has nonunique fields with
// AllowNonUniqueSections, as those tags need. These come after opts, so
// passing one of them as false doesn't drop the values the tags read.
func Unmarshal(data []byte, v any, opts ...LoadOption) error {
if v != nil {
shadows, nonUnique := tagOptions(reflect.TypeOf(v), map[reflect.Type]bool{})
opts = slices.Clone(opts)
if shadows {
opts = append(opts, AllowShadows(true), AllowDuplicateShadowValues(true), PreserveEmptyShadowValues(true))
}
if nonUnique {
opts = append(opts, AllowNonUniqueSections(true))
}
}
return MapTo(v, data, opts...)
}
// tagOptions reports whether t, or a struct type it holds, has allowshadow
// or nonunique fields.
func tagOptions(t reflect.Type, seen map[reflect.Type]bool) (shadows, nonUnique bool) {
for t.Kind() == reflect.Pointer || t.Kind() == reflect.Slice {
t = t.Elem()
}
if !isStructType(t) || seen[t] {
return false, false
}
seen[t] = true
for i := 0; i < t.NumField(); i++ {
_, _, allowShadow, allowNonUnique, _ := parseTagOptions(t.Field(i).Tag.Get("ini"))
s, n := tagOptions(t.Field(i).Type, seen)
shadows = shadows || allowShadow || s
nonUnique = nonUnique || allowNonUnique || n
}
return shadows, nonUnique
}
// Marshal returns the INI encoding of v, a struct or a pointer to one, as
// File.ReflectFrom and File.Write produce it.
func Marshal(v any, opts ...WriteOption) ([]byte, error) {
if val := reflect.ValueOf(v); val.Kind() == reflect.Struct {
ptr := reflect.New(val.Type())
ptr.Elem().Set(val)
v = ptr.Interface()
}
// Shadows and non-unique sections let allowshadow and nonunique fields
// write all their values.
f := Empty(AllowShadows(true), AllowDuplicateShadowValues(true), AllowNonUniqueSections(true))
if err := f.ReflectFrom(v); err != nil {
return nil, err
}
var buf bytes.Buffer
if _, err := f.Write(&buf, opts...); err != nil {
return nil, err
}
return buf.Bytes(), nil
}