struct.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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) error {
  74. strs := key.Strings(delim)
  75. numVals := len(strs)
  76. if numVals == 0 {
  77. return nil
  78. }
  79. var vals interface{}
  80. sliceOf := field.Type().Elem().Kind()
  81. switch sliceOf {
  82. case reflect.String:
  83. vals = strs
  84. case reflect.Int:
  85. vals = key.Ints(delim)
  86. case reflect.Int64:
  87. vals = key.Int64s(delim)
  88. case reflect.Uint:
  89. vals = key.Uints(delim)
  90. case reflect.Uint64:
  91. vals = key.Uint64s(delim)
  92. case reflect.Float64:
  93. vals = key.Float64s(delim)
  94. case reflectTime:
  95. vals = key.Times(delim)
  96. default:
  97. return fmt.Errorf("unsupported type '[]%s'", sliceOf)
  98. }
  99. slice := reflect.MakeSlice(field.Type(), numVals, numVals)
  100. for i := 0; i < numVals; i++ {
  101. switch sliceOf {
  102. case reflect.String:
  103. slice.Index(i).Set(reflect.ValueOf(vals.([]string)[i]))
  104. case reflect.Int:
  105. slice.Index(i).Set(reflect.ValueOf(vals.([]int)[i]))
  106. case reflect.Int64:
  107. slice.Index(i).Set(reflect.ValueOf(vals.([]int64)[i]))
  108. case reflect.Uint:
  109. slice.Index(i).Set(reflect.ValueOf(vals.([]uint)[i]))
  110. case reflect.Uint64:
  111. slice.Index(i).Set(reflect.ValueOf(vals.([]uint64)[i]))
  112. case reflect.Float64:
  113. slice.Index(i).Set(reflect.ValueOf(vals.([]float64)[i]))
  114. case reflectTime:
  115. slice.Index(i).Set(reflect.ValueOf(vals.([]time.Time)[i]))
  116. }
  117. }
  118. field.Set(slice)
  119. return nil
  120. }
  121. // setWithProperType sets proper value to field based on its type,
  122. // but it does not return error for failing parsing,
  123. // because we want to use default value that is already assigned to strcut.
  124. func setWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string) error {
  125. switch t.Kind() {
  126. case reflect.String:
  127. if len(key.String()) == 0 {
  128. return nil
  129. }
  130. field.SetString(key.String())
  131. case reflect.Bool:
  132. boolVal, err := key.Bool()
  133. if err != nil {
  134. return nil
  135. }
  136. field.SetBool(boolVal)
  137. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  138. durationVal, err := key.Duration()
  139. // Skip zero value
  140. if err == nil && int(durationVal) > 0 {
  141. field.Set(reflect.ValueOf(durationVal))
  142. return nil
  143. }
  144. intVal, err := key.Int64()
  145. if err != nil || intVal == 0 {
  146. return nil
  147. }
  148. field.SetInt(intVal)
  149. // byte is an alias for uint8, so supporting uint8 breaks support for byte
  150. case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  151. durationVal, err := key.Duration()
  152. // Skip zero value
  153. if err == nil && int(durationVal) > 0 {
  154. field.Set(reflect.ValueOf(durationVal))
  155. return nil
  156. }
  157. uintVal, err := key.Uint64()
  158. if err != nil {
  159. return nil
  160. }
  161. field.SetUint(uintVal)
  162. case reflect.Float32, reflect.Float64:
  163. floatVal, err := key.Float64()
  164. if err != nil {
  165. return nil
  166. }
  167. field.SetFloat(floatVal)
  168. case reflectTime:
  169. timeVal, err := key.Time()
  170. if err != nil {
  171. return nil
  172. }
  173. field.Set(reflect.ValueOf(timeVal))
  174. case reflect.Slice:
  175. return setSliceWithProperType(key, field, delim)
  176. default:
  177. return fmt.Errorf("unsupported type '%s'", t)
  178. }
  179. return nil
  180. }
  181. func (s *Section) mapTo(val reflect.Value) error {
  182. if val.Kind() == reflect.Ptr {
  183. val = val.Elem()
  184. }
  185. typ := val.Type()
  186. for i := 0; i < typ.NumField(); i++ {
  187. field := val.Field(i)
  188. tpField := typ.Field(i)
  189. tag := tpField.Tag.Get("ini")
  190. if tag == "-" {
  191. continue
  192. }
  193. opts := strings.SplitN(tag, ",", 2) // strip off possible omitempty
  194. fieldName := s.parseFieldName(tpField.Name, opts[0])
  195. if len(fieldName) == 0 || !field.CanSet() {
  196. continue
  197. }
  198. isAnonymous := tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous
  199. isStruct := tpField.Type.Kind() == reflect.Struct
  200. if isAnonymous {
  201. field.Set(reflect.New(tpField.Type.Elem()))
  202. }
  203. if isAnonymous || isStruct {
  204. if sec, err := s.f.GetSection(fieldName); err == nil {
  205. if err = sec.mapTo(field); err != nil {
  206. return fmt.Errorf("error mapping field(%s): %v", fieldName, err)
  207. }
  208. continue
  209. }
  210. }
  211. if key, err := s.GetKey(fieldName); err == nil {
  212. if err = setWithProperType(tpField.Type, key, field, parseDelim(tpField.Tag.Get("delim"))); err != nil {
  213. return fmt.Errorf("error mapping field(%s): %v", fieldName, err)
  214. }
  215. }
  216. }
  217. return nil
  218. }
  219. // MapTo maps section to given struct.
  220. func (s *Section) MapTo(v interface{}) error {
  221. typ := reflect.TypeOf(v)
  222. val := reflect.ValueOf(v)
  223. if typ.Kind() == reflect.Ptr {
  224. typ = typ.Elem()
  225. val = val.Elem()
  226. } else {
  227. return errors.New("cannot map to non-pointer struct")
  228. }
  229. return s.mapTo(val)
  230. }
  231. // MapTo maps file to given struct.
  232. func (f *File) MapTo(v interface{}) error {
  233. return f.Section("").MapTo(v)
  234. }
  235. // MapTo maps data sources to given struct with name mapper.
  236. func MapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error {
  237. cfg, err := Load(source, others...)
  238. if err != nil {
  239. return err
  240. }
  241. cfg.NameMapper = mapper
  242. return cfg.MapTo(v)
  243. }
  244. // MapTo maps data sources to given struct.
  245. func MapTo(v, source interface{}, others ...interface{}) error {
  246. return MapToWithMapper(v, nil, source, others...)
  247. }
  248. // reflectSliceWithProperType does the opposite thing as setSliceWithProperType.
  249. func reflectSliceWithProperType(key *Key, field reflect.Value, delim string) error {
  250. slice := field.Slice(0, field.Len())
  251. if field.Len() == 0 {
  252. return nil
  253. }
  254. var buf bytes.Buffer
  255. sliceOf := field.Type().Elem().Kind()
  256. for i := 0; i < field.Len(); i++ {
  257. switch sliceOf {
  258. case reflect.String:
  259. buf.WriteString(slice.Index(i).String())
  260. case reflect.Int, reflect.Int64:
  261. buf.WriteString(fmt.Sprint(slice.Index(i).Int()))
  262. case reflect.Uint, reflect.Uint64:
  263. buf.WriteString(fmt.Sprint(slice.Index(i).Uint()))
  264. case reflect.Float64:
  265. buf.WriteString(fmt.Sprint(slice.Index(i).Float()))
  266. case reflectTime:
  267. buf.WriteString(slice.Index(i).Interface().(time.Time).Format(time.RFC3339))
  268. default:
  269. return fmt.Errorf("unsupported type '[]%s'", sliceOf)
  270. }
  271. buf.WriteString(delim)
  272. }
  273. key.SetValue(buf.String()[:buf.Len()-1])
  274. return nil
  275. }
  276. // reflectWithProperType does the opposite thing as setWithProperType.
  277. func reflectWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string) error {
  278. switch t.Kind() {
  279. case reflect.String:
  280. key.SetValue(field.String())
  281. case reflect.Bool:
  282. key.SetValue(fmt.Sprint(field.Bool()))
  283. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  284. key.SetValue(fmt.Sprint(field.Int()))
  285. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  286. key.SetValue(fmt.Sprint(field.Uint()))
  287. case reflect.Float32, reflect.Float64:
  288. key.SetValue(fmt.Sprint(field.Float()))
  289. case reflectTime:
  290. key.SetValue(fmt.Sprint(field.Interface().(time.Time).Format(time.RFC3339)))
  291. case reflect.Slice:
  292. return reflectSliceWithProperType(key, field, delim)
  293. default:
  294. return fmt.Errorf("unsupported type '%s'", t)
  295. }
  296. return nil
  297. }
  298. // CR: copied from encoding/json/encode.go with modifications of time.Time support.
  299. // TODO: add more test coverage.
  300. func isEmptyValue(v reflect.Value) bool {
  301. switch v.Kind() {
  302. case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
  303. return v.Len() == 0
  304. case reflect.Bool:
  305. return !v.Bool()
  306. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  307. return v.Int() == 0
  308. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  309. return v.Uint() == 0
  310. case reflect.Float32, reflect.Float64:
  311. return v.Float() == 0
  312. case reflectTime:
  313. return v.Interface().(time.Time).IsZero()
  314. case reflect.Interface, reflect.Ptr:
  315. return v.IsNil()
  316. }
  317. return false
  318. }
  319. func (s *Section) reflectFrom(val reflect.Value) error {
  320. if val.Kind() == reflect.Ptr {
  321. val = val.Elem()
  322. }
  323. typ := val.Type()
  324. for i := 0; i < typ.NumField(); i++ {
  325. field := val.Field(i)
  326. tpField := typ.Field(i)
  327. tag := tpField.Tag.Get("ini")
  328. if tag == "-" {
  329. continue
  330. }
  331. opts := strings.SplitN(tag, ",", 2)
  332. if len(opts) == 2 && opts[1] == "omitempty" && isEmptyValue(field) {
  333. continue
  334. }
  335. fieldName := s.parseFieldName(tpField.Name, opts[0])
  336. if len(fieldName) == 0 || !field.CanSet() {
  337. continue
  338. }
  339. if (tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous) ||
  340. (tpField.Type.Kind() == reflect.Struct && tpField.Type.Name() != "Time") {
  341. // Note: The only error here is section doesn't exist.
  342. sec, err := s.f.GetSection(fieldName)
  343. if err != nil {
  344. // Note: fieldName can never be empty here, ignore error.
  345. sec, _ = s.f.NewSection(fieldName)
  346. }
  347. if err = sec.reflectFrom(field); err != nil {
  348. return fmt.Errorf("error reflecting field (%s): %v", fieldName, err)
  349. }
  350. continue
  351. }
  352. // Note: Same reason as secion.
  353. key, err := s.GetKey(fieldName)
  354. if err != nil {
  355. key, _ = s.NewKey(fieldName, "")
  356. }
  357. if err = reflectWithProperType(tpField.Type, key, field, parseDelim(tpField.Tag.Get("delim"))); err != nil {
  358. return fmt.Errorf("error reflecting field (%s): %v", fieldName, err)
  359. }
  360. }
  361. return nil
  362. }
  363. // ReflectFrom reflects secion from given struct.
  364. func (s *Section) ReflectFrom(v interface{}) error {
  365. typ := reflect.TypeOf(v)
  366. val := reflect.ValueOf(v)
  367. if typ.Kind() == reflect.Ptr {
  368. typ = typ.Elem()
  369. val = val.Elem()
  370. } else {
  371. return errors.New("cannot reflect from non-pointer struct")
  372. }
  373. return s.reflectFrom(val)
  374. }
  375. // ReflectFrom reflects file from given struct.
  376. func (f *File) ReflectFrom(v interface{}) error {
  377. return f.Section("").ReflectFrom(v)
  378. }
  379. // ReflectFrom reflects data sources from given struct with name mapper.
  380. func ReflectFromWithMapper(cfg *File, v interface{}, mapper NameMapper) error {
  381. cfg.NameMapper = mapper
  382. return cfg.ReflectFrom(v)
  383. }
  384. // ReflectFrom reflects data sources from given struct.
  385. func ReflectFrom(cfg *File, v interface{}) error {
  386. return ReflectFromWithMapper(cfg, v, nil)
  387. }