本站源代码
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

572 lines
16KB

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