struct.go (22099B)
1 // Copyright 2014 Unknwon 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"): you may 4 // not use this file except in compliance with the License. You may obtain 5 // a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 // License for the specific language governing permissions and limitations 13 // under the License. 14 15 package ini 16 17 import ( 18 "bytes" 19 "errors" 20 "fmt" 21 "reflect" 22 "strings" 23 "time" 24 "unicode" 25 ) 26 27 // NameMapper represents a ini tag name mapper. 28 type NameMapper func(string) string 29 30 // Built-in name getters. 31 var ( 32 // SnackCase converts to format SNACK_CASE. 33 SnackCase NameMapper = func(raw string) string { 34 newstr := make([]rune, 0, len(raw)) 35 for i, chr := range raw { 36 if isUpper := 'A' <= chr && chr <= 'Z'; isUpper { 37 if i > 0 { 38 newstr = append(newstr, '_') 39 } 40 } 41 newstr = append(newstr, unicode.ToUpper(chr)) 42 } 43 return string(newstr) 44 } 45 // TitleUnderscore converts to format title_underscore. 46 TitleUnderscore NameMapper = func(raw string) string { 47 newstr := make([]rune, 0, len(raw)) 48 for i, chr := range raw { 49 if isUpper := 'A' <= chr && chr <= 'Z'; isUpper { 50 if i > 0 { 51 newstr = append(newstr, '_') 52 } 53 chr -= 'A' - 'a' 54 } 55 newstr = append(newstr, chr) 56 } 57 return string(newstr) 58 } 59 ) 60 61 func (s *Section) parseFieldName(raw, actual string) string { 62 if len(actual) > 0 { 63 return actual 64 } 65 if s.f.NameMapper != nil { 66 return s.f.NameMapper(raw) 67 } 68 return raw 69 } 70 71 func parseDelim(actual string) string { 72 if len(actual) > 0 { 73 return actual 74 } 75 return "," 76 } 77 78 var reflectTime = reflect.TypeOf(time.Now()).Kind() 79 80 // setSliceWithProperType sets proper values to slice based on its type. 81 func setSliceWithProperType(key *Key, field reflect.Value, delim string, allowShadow, isStrict bool) error { 82 var strs []string 83 if allowShadow { 84 strs = key.StringsWithShadows(delim) 85 } else { 86 strs = key.Strings(delim) 87 } 88 89 numVals := len(strs) 90 if numVals == 0 { 91 return nil 92 } 93 94 var vals interface{} 95 var err error 96 97 elemType := field.Type().Elem() 98 isPtrElem := elemType.Kind() == reflect.Pointer 99 valueType := elemType 100 if isPtrElem { 101 valueType = elemType.Elem() 102 } 103 sliceOf := valueType.Kind() 104 switch sliceOf { 105 case reflect.String: 106 vals = strs 107 case reflect.Int: 108 vals, err = key.parseInts(strs, true, false) 109 case reflect.Int64: 110 vals, err = key.parseInt64s(strs, true, false) 111 case reflect.Uint: 112 vals, err = key.parseUints(strs, true, false) 113 case reflect.Uint64: 114 vals, err = key.parseUint64s(strs, true, false) 115 case reflect.Float64: 116 vals, err = key.parseFloat64s(strs, true, false) 117 case reflect.Bool: 118 vals, err = key.parseBools(strs, true, false) 119 case reflectTime: 120 vals, err = key.parseTimesFormat(time.RFC3339, strs, true, false) 121 default: 122 return fmt.Errorf("unsupported type '[]%s'", field.Type().Elem().Kind()) 123 } 124 if err != nil && isStrict { 125 return err 126 } 127 128 slice := reflect.MakeSlice(field.Type(), numVals, numVals) 129 for i := 0; i < numVals; i++ { 130 var v interface{} 131 switch sliceOf { 132 case reflect.String: 133 v = vals.([]string)[i] 134 case reflect.Int: 135 v = vals.([]int)[i] 136 case reflect.Int64: 137 v = vals.([]int64)[i] 138 case reflect.Uint: 139 v = vals.([]uint)[i] 140 case reflect.Uint64: 141 v = vals.([]uint64)[i] 142 case reflect.Float64: 143 v = vals.([]float64)[i] 144 case reflect.Bool: 145 v = vals.([]bool)[i] 146 case reflectTime: 147 v = vals.([]time.Time)[i] 148 } 149 rv := reflect.ValueOf(v) 150 if isPtrElem { 151 pv := reflect.New(rv.Type()) 152 pv.Elem().Set(rv) 153 slice.Index(i).Set(pv) 154 } else { 155 slice.Index(i).Set(rv) 156 } 157 } 158 field.Set(slice) 159 return nil 160 } 161 162 func wrapStrictError(err error, isStrict bool) error { 163 if isStrict { 164 return err 165 } 166 return nil 167 } 168 169 // setWithProperType sets proper value to field based on its type, 170 // but it does not return error for failing parsing, 171 // because we want to use default value that is already assigned to struct. 172 func setWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string, allowShadow, isStrict bool) error { 173 vt := t 174 isPtr := t.Kind() == reflect.Pointer 175 if isPtr { 176 vt = t.Elem() 177 } 178 switch vt.Kind() { 179 case reflect.String: 180 stringVal := key.String() 181 if isPtr { 182 field.Set(reflect.ValueOf(&stringVal)) 183 } else if len(stringVal) > 0 { 184 field.SetString(key.String()) 185 } 186 case reflect.Bool: 187 boolVal, err := key.Bool() 188 if err != nil { 189 return wrapStrictError(err, isStrict) 190 } 191 if isPtr { 192 field.Set(reflect.ValueOf(&boolVal)) 193 } else { 194 field.SetBool(boolVal) 195 } 196 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 197 // ParseDuration will not return err for `0`, so check the type name 198 if vt.Name() == "Duration" { 199 durationVal, err := key.Duration() 200 if err != nil { 201 if intVal, err := key.Int64(); err == nil { 202 field.SetInt(intVal) 203 return nil 204 } 205 return wrapStrictError(err, isStrict) 206 } 207 if isPtr { 208 field.Set(reflect.ValueOf(&durationVal)) 209 } else if int64(durationVal) > 0 { 210 field.Set(reflect.ValueOf(durationVal)) 211 } 212 return nil 213 } 214 215 intVal, err := key.Int64() 216 if err != nil { 217 return wrapStrictError(err, isStrict) 218 } 219 if isPtr { 220 pv := reflect.New(t.Elem()) 221 pv.Elem().SetInt(intVal) 222 field.Set(pv) 223 } else { 224 field.SetInt(intVal) 225 } 226 // byte is an alias for uint8, so supporting uint8 breaks support for byte 227 case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: 228 durationVal, err := key.Duration() 229 // Skip zero value 230 if err == nil && uint64(durationVal) > 0 { 231 if isPtr { 232 field.Set(reflect.ValueOf(&durationVal)) 233 } else { 234 field.Set(reflect.ValueOf(durationVal)) 235 } 236 return nil 237 } 238 239 uintVal, err := key.Uint64() 240 if err != nil { 241 return wrapStrictError(err, isStrict) 242 } 243 if isPtr { 244 pv := reflect.New(t.Elem()) 245 pv.Elem().SetUint(uintVal) 246 field.Set(pv) 247 } else { 248 field.SetUint(uintVal) 249 } 250 251 case reflect.Float32, reflect.Float64: 252 floatVal, err := key.Float64() 253 if err != nil { 254 return wrapStrictError(err, isStrict) 255 } 256 if isPtr { 257 pv := reflect.New(t.Elem()) 258 pv.Elem().SetFloat(floatVal) 259 field.Set(pv) 260 } else { 261 field.SetFloat(floatVal) 262 } 263 case reflectTime: 264 timeVal, err := key.Time() 265 if err != nil { 266 return wrapStrictError(err, isStrict) 267 } 268 if isPtr { 269 field.Set(reflect.ValueOf(&timeVal)) 270 } else { 271 field.Set(reflect.ValueOf(timeVal)) 272 } 273 case reflect.Slice: 274 return setSliceWithProperType(key, field, delim, allowShadow, isStrict) 275 default: 276 return fmt.Errorf("unsupported type %q", t) 277 } 278 return nil 279 } 280 281 func parseTagOptions(tag string) (rawName string, omitEmpty bool, allowShadow bool, allowNonUnique bool, extends bool) { 282 opts := strings.SplitN(tag, ",", 5) 283 rawName = opts[0] 284 for _, opt := range opts[1:] { 285 omitEmpty = omitEmpty || (opt == "omitempty") 286 allowShadow = allowShadow || (opt == "allowshadow") 287 allowNonUnique = allowNonUnique || (opt == "nonunique") 288 extends = extends || (opt == "extends") 289 } 290 return rawName, omitEmpty, allowShadow, allowNonUnique, extends 291 } 292 293 // mapToField maps the given value to the matching field of the given section. 294 // The sectionIndex is the index (if non unique sections are enabled) to which the value should be added. 295 func (s *Section) mapToField(val reflect.Value, isStrict bool, sectionIndex int, sectionName string) error { 296 if val.Kind() == reflect.Pointer { 297 val = val.Elem() 298 } 299 typ := val.Type() 300 301 for i := 0; i < typ.NumField(); i++ { 302 field := val.Field(i) 303 tpField := typ.Field(i) 304 305 tag := tpField.Tag.Get("ini") 306 if tag == "-" { 307 continue 308 } 309 310 rawName, _, allowShadow, allowNonUnique, extends := parseTagOptions(tag) 311 fieldName := s.parseFieldName(tpField.Name, rawName) 312 if len(fieldName) == 0 || !field.CanSet() { 313 continue 314 } 315 316 isStruct := tpField.Type.Kind() == reflect.Struct 317 isStructPtr := tpField.Type.Kind() == reflect.Pointer && tpField.Type.Elem().Kind() == reflect.Struct 318 isAnonymousPtr := tpField.Type.Kind() == reflect.Pointer && tpField.Anonymous 319 if isAnonymousPtr { 320 field.Set(reflect.New(tpField.Type.Elem())) 321 } 322 323 if extends && (isAnonymousPtr || (isStruct && tpField.Anonymous)) { 324 if isStructPtr && field.IsNil() { 325 field.Set(reflect.New(tpField.Type.Elem())) 326 } 327 fieldSection := s 328 if rawName != "" { 329 sectionName = s.name + s.f.options.ChildSectionDelimiter + rawName 330 if secs, err := s.f.SectionsByName(sectionName); err == nil && sectionIndex < len(secs) { 331 fieldSection = secs[sectionIndex] 332 } 333 } 334 if err := fieldSection.mapToField(field, isStrict, sectionIndex, sectionName); err != nil { 335 return fmt.Errorf("map to field %q: %v", fieldName, err) 336 } 337 } else if isAnonymousPtr || isStruct || isStructPtr { 338 if secs, err := s.f.SectionsByName(fieldName); err == nil { 339 if len(secs) <= sectionIndex { 340 return fmt.Errorf("there are not enough sections (%d <= %d) for the field %q", len(secs), sectionIndex, fieldName) 341 } 342 // Only set the field to non-nil struct value if we have a section for it. 343 // Otherwise, we end up with a non-nil struct ptr even though there is no data. 344 if isStructPtr && field.IsNil() { 345 field.Set(reflect.New(tpField.Type.Elem())) 346 } 347 if err = secs[sectionIndex].mapToField(field, isStrict, sectionIndex, fieldName); err != nil { 348 return fmt.Errorf("map to field %q: %v", fieldName, err) 349 } 350 continue 351 } 352 } 353 354 // Map non-unique sections 355 if allowNonUnique && tpField.Type.Kind() == reflect.Slice { 356 newField, err := s.mapToSlice(fieldName, field, isStrict) 357 if err != nil { 358 return fmt.Errorf("map to slice %q: %v", fieldName, err) 359 } 360 361 field.Set(newField) 362 continue 363 } 364 365 if key, err := s.GetKey(fieldName); err == nil { 366 delim := parseDelim(tpField.Tag.Get("delim")) 367 if err = setWithProperType(tpField.Type, key, field, delim, allowShadow, isStrict); err != nil { 368 return fmt.Errorf("set field %q: %v", fieldName, err) 369 } 370 } 371 } 372 return nil 373 } 374 375 // mapToSlice maps all sections with the same name and returns the new value. 376 // The type of the Value must be a slice of structs or pointers to structs. 377 func (s *Section) mapToSlice(secName string, val reflect.Value, isStrict bool) (reflect.Value, error) { 378 secs, err := s.f.SectionsByName(secName) 379 if err != nil { 380 return reflect.Value{}, err 381 } 382 383 elemType := val.Type().Elem() 384 isPtr := elemType.Kind() == reflect.Pointer 385 structType := elemType 386 if isPtr { 387 if elemType.Elem().Kind() != reflect.Struct { 388 return reflect.Value{}, fmt.Errorf("slice of pointers to non-struct type %s", elemType) 389 } 390 structType = elemType.Elem() 391 } 392 393 for i, sec := range secs { 394 elem := reflect.New(structType) 395 if err = sec.mapToField(elem, isStrict, i, sec.name); err != nil { 396 return reflect.Value{}, fmt.Errorf("map to field from section %q: %v", secName, err) 397 } 398 if isPtr { 399 val = reflect.Append(val, elem) 400 } else { 401 val = reflect.Append(val, elem.Elem()) 402 } 403 } 404 return val, nil 405 } 406 407 // mapTo maps a section to object v. 408 func (s *Section) mapTo(v interface{}, isStrict bool) error { 409 typ := reflect.TypeOf(v) 410 val := reflect.ValueOf(v) 411 if typ == nil || !val.IsValid() { 412 return errors.New("nil pointer to a struct") 413 } 414 if typ.Kind() == reflect.Pointer { 415 typ = typ.Elem() 416 val = val.Elem() 417 } else { 418 return errors.New("not a pointer to a struct") 419 } 420 421 // MapTo(&cfg) where cfg is a nil *T used to panic in mapToField (#369). 422 if !val.IsValid() || (val.Kind() == reflect.Pointer && val.IsNil()) { 423 return errors.New("nil pointer to a struct") 424 } 425 426 if typ.Kind() == reflect.Slice { 427 newField, err := s.mapToSlice(s.name, val, isStrict) 428 if err != nil { 429 return err 430 } 431 432 val.Set(newField) 433 return nil 434 } 435 436 return s.mapToField(val, isStrict, 0, s.name) 437 } 438 439 // MapTo maps section to given struct. 440 func (s *Section) MapTo(v interface{}) error { 441 return s.mapTo(v, false) 442 } 443 444 // StrictMapTo maps section to given struct in strict mode, 445 // which returns all possible error including value parsing error. 446 func (s *Section) StrictMapTo(v interface{}) error { 447 return s.mapTo(v, true) 448 } 449 450 // MapTo maps file to given struct. 451 func (f *File) MapTo(v interface{}) error { 452 return f.Section("").MapTo(v) 453 } 454 455 // StrictMapTo maps file to given struct in strict mode, 456 // which returns all possible error including value parsing error. 457 func (f *File) StrictMapTo(v interface{}) error { 458 return f.Section("").StrictMapTo(v) 459 } 460 461 // MapToWithMapper maps data sources to given struct with name mapper. 462 func MapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error { 463 cfg, err := Load(source, others...) 464 if err != nil { 465 return err 466 } 467 cfg.NameMapper = mapper 468 return cfg.MapTo(v) 469 } 470 471 // StrictMapToWithMapper maps data sources to given struct with name mapper in strict mode, 472 // which returns all possible error including value parsing error. 473 func StrictMapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error { 474 cfg, err := Load(source, others...) 475 if err != nil { 476 return err 477 } 478 cfg.NameMapper = mapper 479 return cfg.StrictMapTo(v) 480 } 481 482 // MapTo maps data sources to given struct. 483 func MapTo(v, source interface{}, others ...interface{}) error { 484 return MapToWithMapper(v, nil, source, others...) 485 } 486 487 // StrictMapTo maps data sources to given struct in strict mode, 488 // which returns all possible error including value parsing error. 489 func StrictMapTo(v, source interface{}, others ...interface{}) error { 490 return StrictMapToWithMapper(v, nil, source, others...) 491 } 492 493 // reflectSliceWithProperType does the opposite thing as setSliceWithProperType. 494 func reflectSliceWithProperType(key *Key, field reflect.Value, delim string, allowShadow bool) error { 495 slice := field.Slice(0, field.Len()) 496 if field.Len() == 0 { 497 return nil 498 } 499 sliceOf := field.Type().Elem().Kind() 500 501 if allowShadow { 502 var keyWithShadows *Key 503 for i := 0; i < field.Len(); i++ { 504 var val string 505 switch sliceOf { 506 case reflect.String: 507 val = slice.Index(i).String() 508 case reflect.Int, reflect.Int64: 509 val = fmt.Sprint(slice.Index(i).Int()) 510 case reflect.Uint, reflect.Uint64: 511 val = fmt.Sprint(slice.Index(i).Uint()) 512 case reflect.Float64: 513 val = fmt.Sprint(slice.Index(i).Float()) 514 case reflect.Bool: 515 val = fmt.Sprint(slice.Index(i).Bool()) 516 case reflectTime: 517 val = slice.Index(i).Interface().(time.Time).Format(time.RFC3339) 518 default: 519 return fmt.Errorf("unsupported type '[]%s'", sliceOf) 520 } 521 522 if i == 0 { 523 keyWithShadows = newKey(key.s, key.name, val) 524 } else { 525 _ = keyWithShadows.AddShadow(val) 526 } 527 } 528 *key = *keyWithShadows 529 return nil 530 } 531 532 var buf bytes.Buffer 533 for i := 0; i < field.Len(); i++ { 534 switch sliceOf { 535 case reflect.String: 536 val := slice.Index(i).String() 537 if key.s.f.options.EscapeSliceDelimiters { 538 val = escapeDelimited(val, delim) 539 } 540 buf.WriteString(val) 541 case reflect.Int, reflect.Int64: 542 fmt.Fprint(&buf, slice.Index(i).Int()) 543 case reflect.Uint, reflect.Uint64: 544 fmt.Fprint(&buf, slice.Index(i).Uint()) 545 case reflect.Float64: 546 fmt.Fprint(&buf, slice.Index(i).Float()) 547 case reflect.Bool: 548 fmt.Fprint(&buf, slice.Index(i).Bool()) 549 case reflectTime: 550 buf.WriteString(slice.Index(i).Interface().(time.Time).Format(time.RFC3339)) 551 default: 552 return fmt.Errorf("unsupported type '[]%s'", sliceOf) 553 } 554 buf.WriteString(delim) 555 } 556 key.SetValue(buf.String()[:buf.Len()-len(delim)]) 557 return nil 558 } 559 560 // reflectWithProperType does the opposite thing as setWithProperType. 561 func reflectWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string, allowShadow bool) error { 562 switch t.Kind() { 563 case reflect.String: 564 key.SetValue(field.String()) 565 case reflect.Bool: 566 key.SetValue(fmt.Sprint(field.Bool())) 567 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 568 key.SetValue(fmt.Sprint(field.Int())) 569 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: 570 key.SetValue(fmt.Sprint(field.Uint())) 571 case reflect.Float32, reflect.Float64: 572 key.SetValue(fmt.Sprint(field.Float())) 573 case reflectTime: 574 key.SetValue(fmt.Sprint(field.Interface().(time.Time).Format(time.RFC3339))) 575 case reflect.Slice: 576 return reflectSliceWithProperType(key, field, delim, allowShadow) 577 case reflect.Pointer: 578 if !field.IsNil() { 579 return reflectWithProperType(t.Elem(), key, field.Elem(), delim, allowShadow) 580 } 581 default: 582 return fmt.Errorf("unsupported type %q", t) 583 } 584 return nil 585 } 586 587 // CR: copied from encoding/json/encode.go with modifications of time.Time support. 588 // TODO: add more test coverage. 589 func isEmptyValue(v reflect.Value) bool { 590 switch v.Kind() { 591 case reflect.Array, reflect.Map, reflect.Slice, reflect.String: 592 return v.Len() == 0 593 case reflect.Bool: 594 return !v.Bool() 595 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 596 return v.Int() == 0 597 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 598 return v.Uint() == 0 599 case reflect.Float32, reflect.Float64: 600 return v.Float() == 0 601 case reflect.Interface, reflect.Pointer: 602 return v.IsNil() 603 case reflectTime: 604 t, ok := v.Interface().(time.Time) 605 return ok && t.IsZero() 606 } 607 return false 608 } 609 610 // StructReflector is the interface implemented by struct types that can extract themselves into INI objects. 611 type StructReflector interface { 612 ReflectINIStruct(*File) error 613 } 614 615 func (s *Section) reflectFrom(val reflect.Value) error { 616 if val.Kind() == reflect.Pointer { 617 val = val.Elem() 618 } 619 typ := val.Type() 620 621 for i := 0; i < typ.NumField(); i++ { 622 if !val.Field(i).CanInterface() { 623 continue 624 } 625 626 field := val.Field(i) 627 tpField := typ.Field(i) 628 629 tag := tpField.Tag.Get("ini") 630 if tag == "-" { 631 continue 632 } 633 634 rawName, omitEmpty, allowShadow, allowNonUnique, extends := parseTagOptions(tag) 635 if omitEmpty && isEmptyValue(field) { 636 continue 637 } 638 639 if r, ok := field.Interface().(StructReflector); ok { 640 if err := r.ReflectINIStruct(s.f); err != nil { 641 return err 642 } 643 continue 644 } 645 646 fieldName := s.parseFieldName(tpField.Name, rawName) 647 if len(fieldName) == 0 || !field.CanSet() { 648 continue 649 } 650 651 if extends && tpField.Anonymous && (tpField.Type.Kind() == reflect.Pointer || tpField.Type.Kind() == reflect.Struct) { 652 if err := s.reflectFrom(field); err != nil { 653 return fmt.Errorf("reflect from field %q: %v", fieldName, err) 654 } 655 continue 656 } 657 658 if (tpField.Type.Kind() == reflect.Pointer && tpField.Type.Elem().Kind() == reflect.Struct) || 659 (tpField.Type.Kind() == reflect.Struct && tpField.Type.Name() != "Time") { 660 // Note: The only error here is section doesn't exist. 661 sec, err := s.f.GetSection(fieldName) 662 if err != nil { 663 // Note: fieldName can never be empty here, ignore error. 664 sec, _ = s.f.NewSection(fieldName) 665 } 666 667 // Add comment from comment tag 668 if len(sec.Comment) == 0 { 669 sec.Comment = tpField.Tag.Get("comment") 670 } 671 672 if err = sec.reflectFrom(field); err != nil { 673 return fmt.Errorf("reflect from field %q: %v", fieldName, err) 674 } 675 continue 676 } 677 678 if allowNonUnique && tpField.Type.Kind() == reflect.Slice { 679 slice := field.Slice(0, field.Len()) 680 if field.Len() == 0 { 681 return nil 682 } 683 sliceOf := field.Type().Elem().Kind() 684 685 for i := 0; i < field.Len(); i++ { 686 if sliceOf != reflect.Struct && sliceOf != reflect.Pointer { 687 return fmt.Errorf("field %q is not a slice of pointer or struct", fieldName) 688 } 689 690 sec, err := s.f.NewSection(fieldName) 691 if err != nil { 692 return err 693 } 694 695 // Add comment from comment tag 696 if len(sec.Comment) == 0 { 697 sec.Comment = tpField.Tag.Get("comment") 698 } 699 700 if err := sec.reflectFrom(slice.Index(i)); err != nil { 701 return fmt.Errorf("reflect from field %q: %v", fieldName, err) 702 } 703 } 704 continue 705 } 706 707 // Note: Same reason as section. 708 key, err := s.GetKey(fieldName) 709 if err != nil { 710 key, _ = s.NewKey(fieldName, "") 711 } 712 713 // Add comment from comment tag 714 if len(key.Comment) == 0 { 715 key.Comment = tpField.Tag.Get("comment") 716 } 717 718 delim := parseDelim(tpField.Tag.Get("delim")) 719 if err = reflectWithProperType(tpField.Type, key, field, delim, allowShadow); err != nil { 720 return fmt.Errorf("reflect field %q: %v", fieldName, err) 721 } 722 723 } 724 return nil 725 } 726 727 // ReflectFrom reflects section from given struct. It overwrites existing ones. 728 func (s *Section) ReflectFrom(v interface{}) error { 729 typ := reflect.TypeOf(v) 730 val := reflect.ValueOf(v) 731 732 if s.name != DefaultSection && s.f.options.AllowNonUniqueSections && 733 (typ.Kind() == reflect.Slice || typ.Kind() == reflect.Pointer) { 734 // Clear sections to make sure none exists before adding the new ones 735 s.f.DeleteSection(s.name) 736 737 if typ.Kind() == reflect.Pointer { 738 sec, err := s.f.NewSection(s.name) 739 if err != nil { 740 return err 741 } 742 return sec.reflectFrom(val.Elem()) 743 } 744 745 slice := val.Slice(0, val.Len()) 746 sliceOf := val.Type().Elem().Kind() 747 if sliceOf != reflect.Pointer { 748 return fmt.Errorf("not a slice of pointers") 749 } 750 751 for i := 0; i < slice.Len(); i++ { 752 sec, err := s.f.NewSection(s.name) 753 if err != nil { 754 return err 755 } 756 757 err = sec.reflectFrom(slice.Index(i)) 758 if err != nil { 759 return fmt.Errorf("reflect from %dth field: %v", i, err) 760 } 761 } 762 763 return nil 764 } 765 766 if typ.Kind() == reflect.Pointer { 767 val = val.Elem() 768 } else { 769 return errors.New("not a pointer to a struct") 770 } 771 772 return s.reflectFrom(val) 773 } 774 775 // ReflectFrom reflects file from given struct. 776 func (f *File) ReflectFrom(v interface{}) error { 777 return f.Section("").ReflectFrom(v) 778 } 779 780 // ReflectFromWithMapper reflects data sources from given struct with name mapper. 781 func ReflectFromWithMapper(cfg *File, v interface{}, mapper NameMapper) error { 782 cfg.NameMapper = mapper 783 return cfg.ReflectFrom(v) 784 } 785 786 // ReflectFrom reflects data sources from given struct. 787 func ReflectFrom(cfg *File, v interface{}) error { 788 return ReflectFromWithMapper(cfg, v, nil) 789 }