struct.go 21 KB

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