struct.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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. return wrapStrictError(err, isStrict)
  173. }
  174. if isPtr {
  175. field.Set(reflect.ValueOf(&durationVal))
  176. } else if int64(durationVal) > 0 {
  177. field.Set(reflect.ValueOf(durationVal))
  178. }
  179. return nil
  180. }
  181. intVal, err := key.Int64()
  182. if err != nil {
  183. return wrapStrictError(err, isStrict)
  184. }
  185. if isPtr {
  186. pv := reflect.New(t.Elem())
  187. pv.Elem().SetInt(intVal)
  188. field.Set(pv)
  189. } else {
  190. field.SetInt(intVal)
  191. }
  192. // byte is an alias for uint8, so supporting uint8 breaks support for byte
  193. case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  194. durationVal, err := key.Duration()
  195. // Skip zero value
  196. if err == nil && uint64(durationVal) > 0 {
  197. if isPtr {
  198. field.Set(reflect.ValueOf(&durationVal))
  199. } else {
  200. field.Set(reflect.ValueOf(durationVal))
  201. }
  202. return nil
  203. }
  204. uintVal, err := key.Uint64()
  205. if err != nil {
  206. return wrapStrictError(err, isStrict)
  207. }
  208. if isPtr {
  209. pv := reflect.New(t.Elem())
  210. pv.Elem().SetUint(uintVal)
  211. field.Set(pv)
  212. } else {
  213. field.SetUint(uintVal)
  214. }
  215. case reflect.Float32, reflect.Float64:
  216. floatVal, err := key.Float64()
  217. if err != nil {
  218. return wrapStrictError(err, isStrict)
  219. }
  220. if isPtr {
  221. pv := reflect.New(t.Elem())
  222. pv.Elem().SetFloat(floatVal)
  223. field.Set(pv)
  224. } else {
  225. field.SetFloat(floatVal)
  226. }
  227. case reflectTime:
  228. timeVal, err := key.Time()
  229. if err != nil {
  230. return wrapStrictError(err, isStrict)
  231. }
  232. if isPtr {
  233. field.Set(reflect.ValueOf(&timeVal))
  234. } else {
  235. field.Set(reflect.ValueOf(timeVal))
  236. }
  237. case reflect.Slice:
  238. return setSliceWithProperType(key, field, delim, allowShadow, isStrict)
  239. default:
  240. return fmt.Errorf("unsupported type '%s'", t)
  241. }
  242. return nil
  243. }
  244. func parseTagOptions(tag string) (rawName string, omitEmpty bool, allowShadow bool) {
  245. opts := strings.SplitN(tag, ",", 3)
  246. rawName = opts[0]
  247. if len(opts) > 1 {
  248. omitEmpty = opts[1] == "omitempty"
  249. }
  250. if len(opts) > 2 {
  251. allowShadow = opts[2] == "allowshadow"
  252. }
  253. return rawName, omitEmpty, allowShadow
  254. }
  255. func (s *Section) mapTo(val reflect.Value, isStrict bool) error {
  256. if val.Kind() == reflect.Ptr {
  257. val = val.Elem()
  258. }
  259. typ := val.Type()
  260. for i := 0; i < typ.NumField(); i++ {
  261. field := val.Field(i)
  262. tpField := typ.Field(i)
  263. tag := tpField.Tag.Get("ini")
  264. if tag == "-" {
  265. continue
  266. }
  267. rawName, _, allowShadow := parseTagOptions(tag)
  268. fieldName := s.parseFieldName(tpField.Name, rawName)
  269. if len(fieldName) == 0 || !field.CanSet() {
  270. continue
  271. }
  272. isStruct := tpField.Type.Kind() == reflect.Struct
  273. isStructPtr := tpField.Type.Kind() == reflect.Ptr && tpField.Type.Elem().Kind() == reflect.Struct
  274. isAnonymous := tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous
  275. if isAnonymous {
  276. field.Set(reflect.New(tpField.Type.Elem()))
  277. }
  278. if isAnonymous || isStruct || isStructPtr {
  279. if sec, err := s.f.GetSection(fieldName); err == nil {
  280. // Only set the field to non-nil struct value if we have
  281. // a section for it. Otherwise, we end up with a non-nil
  282. // struct ptr even though there is no data.
  283. if isStructPtr && field.IsNil() {
  284. field.Set(reflect.New(tpField.Type.Elem()))
  285. }
  286. if err = sec.mapTo(field, isStrict); err != nil {
  287. return fmt.Errorf("error mapping field(%s): %v", fieldName, err)
  288. }
  289. continue
  290. }
  291. }
  292. if key, err := s.GetKey(fieldName); err == nil {
  293. delim := parseDelim(tpField.Tag.Get("delim"))
  294. if err = setWithProperType(tpField.Type, key, field, delim, allowShadow, isStrict); err != nil {
  295. return fmt.Errorf("error mapping field(%s): %v", fieldName, err)
  296. }
  297. }
  298. }
  299. return nil
  300. }
  301. // MapTo maps section to given struct.
  302. func (s *Section) MapTo(v interface{}) error {
  303. typ := reflect.TypeOf(v)
  304. val := reflect.ValueOf(v)
  305. if typ.Kind() == reflect.Ptr {
  306. typ = typ.Elem()
  307. val = val.Elem()
  308. } else {
  309. return errors.New("cannot map to non-pointer struct")
  310. }
  311. return s.mapTo(val, false)
  312. }
  313. // StrictMapTo maps section to given struct in strict mode,
  314. // which returns all possible error including value parsing error.
  315. func (s *Section) StrictMapTo(v interface{}) error {
  316. typ := reflect.TypeOf(v)
  317. val := reflect.ValueOf(v)
  318. if typ.Kind() == reflect.Ptr {
  319. typ = typ.Elem()
  320. val = val.Elem()
  321. } else {
  322. return errors.New("cannot map to non-pointer struct")
  323. }
  324. return s.mapTo(val, true)
  325. }
  326. // MapTo maps file to given struct.
  327. func (f *File) MapTo(v interface{}) error {
  328. return f.Section("").MapTo(v)
  329. }
  330. // StrictMapTo maps file to given struct in strict mode,
  331. // which returns all possible error including value parsing error.
  332. func (f *File) StrictMapTo(v interface{}) error {
  333. return f.Section("").StrictMapTo(v)
  334. }
  335. // MapToWithMapper maps data sources to given struct with name mapper.
  336. func MapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error {
  337. cfg, err := Load(source, others...)
  338. if err != nil {
  339. return err
  340. }
  341. cfg.NameMapper = mapper
  342. return cfg.MapTo(v)
  343. }
  344. // StrictMapToWithMapper maps data sources to given struct with name mapper in strict mode,
  345. // which returns all possible error including value parsing error.
  346. func StrictMapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error {
  347. cfg, err := Load(source, others...)
  348. if err != nil {
  349. return err
  350. }
  351. cfg.NameMapper = mapper
  352. return cfg.StrictMapTo(v)
  353. }
  354. // MapTo maps data sources to given struct.
  355. func MapTo(v, source interface{}, others ...interface{}) error {
  356. return MapToWithMapper(v, nil, source, others...)
  357. }
  358. // StrictMapTo maps data sources to given struct in strict mode,
  359. // which returns all possible error including value parsing error.
  360. func StrictMapTo(v, source interface{}, others ...interface{}) error {
  361. return StrictMapToWithMapper(v, nil, source, others...)
  362. }
  363. // reflectSliceWithProperType does the opposite thing as setSliceWithProperType.
  364. func reflectSliceWithProperType(key *Key, field reflect.Value, delim string, allowShadow bool) error {
  365. slice := field.Slice(0, field.Len())
  366. if field.Len() == 0 {
  367. return nil
  368. }
  369. sliceOf := field.Type().Elem().Kind()
  370. if allowShadow {
  371. var keyWithShadows *Key
  372. for i := 0; i < field.Len(); i++ {
  373. var val string
  374. switch sliceOf {
  375. case reflect.String:
  376. val = slice.Index(i).String()
  377. case reflect.Int, reflect.Int64:
  378. val = fmt.Sprint(slice.Index(i).Int())
  379. case reflect.Uint, reflect.Uint64:
  380. val = fmt.Sprint(slice.Index(i).Uint())
  381. case reflect.Float64:
  382. val = fmt.Sprint(slice.Index(i).Float())
  383. case reflect.Bool:
  384. val = fmt.Sprint(slice.Index(i).Bool())
  385. case reflectTime:
  386. val = slice.Index(i).Interface().(time.Time).Format(time.RFC3339)
  387. default:
  388. return fmt.Errorf("unsupported type '[]%s'", sliceOf)
  389. }
  390. if i == 0 {
  391. keyWithShadows = newKey(key.s, key.name, val)
  392. } else {
  393. keyWithShadows.AddShadow(val)
  394. }
  395. }
  396. key = keyWithShadows
  397. return nil
  398. }
  399. var buf bytes.Buffer
  400. for i := 0; i < field.Len(); i++ {
  401. switch sliceOf {
  402. case reflect.String:
  403. buf.WriteString(slice.Index(i).String())
  404. case reflect.Int, reflect.Int64:
  405. buf.WriteString(fmt.Sprint(slice.Index(i).Int()))
  406. case reflect.Uint, reflect.Uint64:
  407. buf.WriteString(fmt.Sprint(slice.Index(i).Uint()))
  408. case reflect.Float64:
  409. buf.WriteString(fmt.Sprint(slice.Index(i).Float()))
  410. case reflect.Bool:
  411. buf.WriteString(fmt.Sprint(slice.Index(i).Bool()))
  412. case reflectTime:
  413. buf.WriteString(slice.Index(i).Interface().(time.Time).Format(time.RFC3339))
  414. default:
  415. return fmt.Errorf("unsupported type '[]%s'", sliceOf)
  416. }
  417. buf.WriteString(delim)
  418. }
  419. key.SetValue(buf.String()[:buf.Len()-len(delim)])
  420. return nil
  421. }
  422. // reflectWithProperType does the opposite thing as setWithProperType.
  423. func reflectWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string, allowShadow bool) error {
  424. switch t.Kind() {
  425. case reflect.String:
  426. key.SetValue(field.String())
  427. case reflect.Bool:
  428. key.SetValue(fmt.Sprint(field.Bool()))
  429. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  430. key.SetValue(fmt.Sprint(field.Int()))
  431. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  432. key.SetValue(fmt.Sprint(field.Uint()))
  433. case reflect.Float32, reflect.Float64:
  434. key.SetValue(fmt.Sprint(field.Float()))
  435. case reflectTime:
  436. key.SetValue(fmt.Sprint(field.Interface().(time.Time).Format(time.RFC3339)))
  437. case reflect.Slice:
  438. return reflectSliceWithProperType(key, field, delim, allowShadow)
  439. case reflect.Ptr:
  440. if !field.IsNil() {
  441. return reflectWithProperType(t.Elem(), key, field.Elem(), delim, allowShadow)
  442. }
  443. default:
  444. return fmt.Errorf("unsupported type '%s'", t)
  445. }
  446. return nil
  447. }
  448. // CR: copied from encoding/json/encode.go with modifications of time.Time support.
  449. // TODO: add more test coverage.
  450. func isEmptyValue(v reflect.Value) bool {
  451. switch v.Kind() {
  452. case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
  453. return v.Len() == 0
  454. case reflect.Bool:
  455. return !v.Bool()
  456. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  457. return v.Int() == 0
  458. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  459. return v.Uint() == 0
  460. case reflect.Float32, reflect.Float64:
  461. return v.Float() == 0
  462. case reflect.Interface, reflect.Ptr:
  463. return v.IsNil()
  464. case reflectTime:
  465. t, ok := v.Interface().(time.Time)
  466. return ok && t.IsZero()
  467. }
  468. return false
  469. }
  470. func (s *Section) reflectFrom(val reflect.Value) error {
  471. if val.Kind() == reflect.Ptr {
  472. val = val.Elem()
  473. }
  474. typ := val.Type()
  475. for i := 0; i < typ.NumField(); i++ {
  476. field := val.Field(i)
  477. tpField := typ.Field(i)
  478. tag := tpField.Tag.Get("ini")
  479. if tag == "-" {
  480. continue
  481. }
  482. rawName, omitEmpty, allowShadow := parseTagOptions(tag)
  483. if omitEmpty && isEmptyValue(field) {
  484. continue
  485. }
  486. fieldName := s.parseFieldName(tpField.Name, rawName)
  487. if len(fieldName) == 0 || !field.CanSet() {
  488. continue
  489. }
  490. if (tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous) ||
  491. (tpField.Type.Kind() == reflect.Struct && tpField.Type.Name() != "Time") {
  492. // Note: The only error here is section doesn't exist.
  493. sec, err := s.f.GetSection(fieldName)
  494. if err != nil {
  495. // Note: fieldName can never be empty here, ignore error.
  496. sec, _ = s.f.NewSection(fieldName)
  497. }
  498. // Add comment from comment tag
  499. if len(sec.Comment) == 0 {
  500. sec.Comment = tpField.Tag.Get("comment")
  501. }
  502. if err = sec.reflectFrom(field); err != nil {
  503. return fmt.Errorf("error reflecting field (%s): %v", fieldName, err)
  504. }
  505. continue
  506. }
  507. // Note: Same reason as secion.
  508. key, err := s.GetKey(fieldName)
  509. if err != nil {
  510. key, _ = s.NewKey(fieldName, "")
  511. }
  512. // Add comment from comment tag
  513. if len(key.Comment) == 0 {
  514. key.Comment = tpField.Tag.Get("comment")
  515. }
  516. if err = reflectWithProperType(tpField.Type, key, field, parseDelim(tpField.Tag.Get("delim")), allowShadow); err != nil {
  517. return fmt.Errorf("error reflecting field (%s): %v", fieldName, err)
  518. }
  519. }
  520. return nil
  521. }
  522. // ReflectFrom reflects secion from given struct.
  523. func (s *Section) ReflectFrom(v interface{}) error {
  524. typ := reflect.TypeOf(v)
  525. val := reflect.ValueOf(v)
  526. if typ.Kind() == reflect.Ptr {
  527. typ = typ.Elem()
  528. val = val.Elem()
  529. } else {
  530. return errors.New("cannot reflect from non-pointer struct")
  531. }
  532. return s.reflectFrom(val)
  533. }
  534. // ReflectFrom reflects file from given struct.
  535. func (f *File) ReflectFrom(v interface{}) error {
  536. return f.Section("").ReflectFrom(v)
  537. }
  538. // ReflectFromWithMapper reflects data sources from given struct with name mapper.
  539. func ReflectFromWithMapper(cfg *File, v interface{}, mapper NameMapper) error {
  540. cfg.NameMapper = mapper
  541. return cfg.ReflectFrom(v)
  542. }
  543. // ReflectFrom reflects data sources from given struct.
  544. func ReflectFrom(cfg *File, v interface{}) error {
  545. return ReflectFromWithMapper(cfg, v, nil)
  546. }