struct.go 15 KB

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