struct.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. "time"
  21. "unicode"
  22. )
  23. // NameMapper represents a ini tag name mapper.
  24. type NameMapper func(string) string
  25. // Built-in name getters.
  26. var (
  27. // AllCapsUnderscore converts to format ALL_CAPS_UNDERSCORE.
  28. AllCapsUnderscore NameMapper = func(raw string) string {
  29. newstr := make([]rune, 0, len(raw))
  30. for i, chr := range raw {
  31. if isUpper := 'A' <= chr && chr <= 'Z'; isUpper {
  32. if i > 0 {
  33. newstr = append(newstr, '_')
  34. }
  35. }
  36. newstr = append(newstr, unicode.ToUpper(chr))
  37. }
  38. return string(newstr)
  39. }
  40. // TitleUnderscore converts to format title_underscore.
  41. TitleUnderscore NameMapper = func(raw string) string {
  42. newstr := make([]rune, 0, len(raw))
  43. for i, chr := range raw {
  44. if isUpper := 'A' <= chr && chr <= 'Z'; isUpper {
  45. if i > 0 {
  46. newstr = append(newstr, '_')
  47. }
  48. chr -= ('A' - 'a')
  49. }
  50. newstr = append(newstr, chr)
  51. }
  52. return string(newstr)
  53. }
  54. )
  55. func (s *Section) parseFieldName(raw, actual string) string {
  56. if len(actual) > 0 {
  57. return actual
  58. }
  59. if s.f.NameMapper != nil {
  60. return s.f.NameMapper(raw)
  61. }
  62. return raw
  63. }
  64. func parseDelim(actual string) string {
  65. if len(actual) > 0 {
  66. return actual
  67. }
  68. return ","
  69. }
  70. var reflectTime = reflect.TypeOf(time.Now()).Kind()
  71. // setWithProperType sets proper value to field based on its type,
  72. // but it does not return error for failing parsing,
  73. // because we want to use default value that is already assigned to strcut.
  74. func setWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string) error {
  75. switch t.Kind() {
  76. case reflect.String:
  77. if len(key.String()) == 0 {
  78. return nil
  79. }
  80. field.SetString(key.String())
  81. case reflect.Bool:
  82. boolVal, err := key.Bool()
  83. if err != nil {
  84. return nil
  85. }
  86. field.SetBool(boolVal)
  87. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  88. durationVal, err := key.Duration()
  89. if err == nil {
  90. field.Set(reflect.ValueOf(durationVal))
  91. return nil
  92. }
  93. intVal, err := key.Int64()
  94. if err != nil {
  95. return nil
  96. }
  97. field.SetInt(intVal)
  98. // byte is an alias for uint8, so supporting uint8 breaks support for byte
  99. case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  100. durationVal, err := key.Duration()
  101. if err == nil {
  102. field.Set(reflect.ValueOf(durationVal))
  103. return nil
  104. }
  105. uintVal, err := key.Uint64()
  106. if err != nil {
  107. return nil
  108. }
  109. field.SetUint(uintVal)
  110. case reflect.Float64:
  111. floatVal, err := key.Float64()
  112. if err != nil {
  113. return nil
  114. }
  115. field.SetFloat(floatVal)
  116. case reflectTime:
  117. timeVal, err := key.Time()
  118. if err != nil {
  119. return nil
  120. }
  121. field.Set(reflect.ValueOf(timeVal))
  122. case reflect.Slice:
  123. vals := key.Strings(delim)
  124. numVals := len(vals)
  125. if numVals == 0 {
  126. return nil
  127. }
  128. sliceOf := field.Type().Elem().Kind()
  129. var times []time.Time
  130. if sliceOf == reflectTime {
  131. times = key.Times(delim)
  132. }
  133. slice := reflect.MakeSlice(field.Type(), numVals, numVals)
  134. for i := 0; i < numVals; i++ {
  135. switch sliceOf {
  136. case reflectTime:
  137. slice.Index(i).Set(reflect.ValueOf(times[i]))
  138. default:
  139. slice.Index(i).Set(reflect.ValueOf(vals[i]))
  140. }
  141. }
  142. field.Set(slice)
  143. default:
  144. return fmt.Errorf("unsupported type '%s'", t)
  145. }
  146. return nil
  147. }
  148. func (s *Section) mapTo(val reflect.Value) error {
  149. if val.Kind() == reflect.Ptr {
  150. val = val.Elem()
  151. }
  152. typ := val.Type()
  153. for i := 0; i < typ.NumField(); i++ {
  154. field := val.Field(i)
  155. tpField := typ.Field(i)
  156. tag := tpField.Tag.Get("ini")
  157. if tag == "-" {
  158. continue
  159. }
  160. fieldName := s.parseFieldName(tpField.Name, tag)
  161. if len(fieldName) == 0 || !field.CanSet() {
  162. continue
  163. }
  164. isAnonymous := tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous
  165. isStruct := tpField.Type.Kind() == reflect.Struct
  166. if isAnonymous {
  167. field.Set(reflect.New(tpField.Type.Elem()))
  168. }
  169. if isAnonymous || isStruct {
  170. if sec, err := s.f.GetSection(fieldName); err == nil {
  171. if err = sec.mapTo(field); err != nil {
  172. return fmt.Errorf("error mapping field(%s): %v", fieldName, err)
  173. }
  174. continue
  175. }
  176. }
  177. if key, err := s.GetKey(fieldName); err == nil {
  178. if err = setWithProperType(tpField.Type, key, field, parseDelim(tpField.Tag.Get("delim"))); err != nil {
  179. return fmt.Errorf("error mapping field(%s): %v", fieldName, err)
  180. }
  181. }
  182. }
  183. return nil
  184. }
  185. // MapTo maps section to given struct.
  186. func (s *Section) MapTo(v interface{}) error {
  187. typ := reflect.TypeOf(v)
  188. val := reflect.ValueOf(v)
  189. if typ.Kind() == reflect.Ptr {
  190. typ = typ.Elem()
  191. val = val.Elem()
  192. } else {
  193. return errors.New("cannot map to non-pointer struct")
  194. }
  195. return s.mapTo(val)
  196. }
  197. // MapTo maps file to given struct.
  198. func (f *File) MapTo(v interface{}) error {
  199. return f.Section("").MapTo(v)
  200. }
  201. // MapTo maps data sources to given struct with name mapper.
  202. func MapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error {
  203. cfg, err := Load(source, others...)
  204. if err != nil {
  205. return err
  206. }
  207. cfg.NameMapper = mapper
  208. return cfg.MapTo(v)
  209. }
  210. // MapTo maps data sources to given struct.
  211. func MapTo(v, source interface{}, others ...interface{}) error {
  212. return MapToWithMapper(v, nil, source, others...)
  213. }
  214. // reflectWithProperType does the opposite thing with setWithProperType.
  215. func reflectWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string) error {
  216. switch t.Kind() {
  217. case reflect.String:
  218. key.SetValue(field.String())
  219. case reflect.Bool,
  220. reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
  221. reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
  222. reflect.Float64,
  223. reflectTime:
  224. key.SetValue(fmt.Sprint(field))
  225. case reflect.Slice:
  226. vals := field.Slice(0, field.Len())
  227. if field.Len() == 0 {
  228. return nil
  229. }
  230. var buf bytes.Buffer
  231. isTime := fmt.Sprint(field.Type()) == "[]time.Time"
  232. for i := 0; i < field.Len(); i++ {
  233. if isTime {
  234. buf.WriteString(vals.Index(i).Interface().(time.Time).Format(time.RFC3339))
  235. } else {
  236. buf.WriteString(fmt.Sprint(vals.Index(i)))
  237. }
  238. buf.WriteString(delim)
  239. }
  240. key.SetValue(buf.String()[:buf.Len()-1])
  241. default:
  242. return fmt.Errorf("unsupported type '%s'", t)
  243. }
  244. return nil
  245. }
  246. func (s *Section) reflectFrom(val reflect.Value) error {
  247. if val.Kind() == reflect.Ptr {
  248. val = val.Elem()
  249. }
  250. typ := val.Type()
  251. for i := 0; i < typ.NumField(); i++ {
  252. field := val.Field(i)
  253. tpField := typ.Field(i)
  254. tag := tpField.Tag.Get("ini")
  255. if tag == "-" {
  256. continue
  257. }
  258. fieldName := s.parseFieldName(tpField.Name, tag)
  259. if len(fieldName) == 0 || !field.CanSet() {
  260. continue
  261. }
  262. if (tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous) ||
  263. (tpField.Type.Kind() == reflect.Struct) {
  264. // Note: The only error here is section doesn't exist.
  265. sec, err := s.f.GetSection(fieldName)
  266. if err != nil {
  267. // Note: fieldName can never be empty here, ignore error.
  268. sec, _ = s.f.NewSection(fieldName)
  269. }
  270. if err = sec.reflectFrom(field); err != nil {
  271. return fmt.Errorf("error reflecting field(%s): %v", fieldName, err)
  272. }
  273. continue
  274. }
  275. // Note: Same reason as secion.
  276. key, err := s.GetKey(fieldName)
  277. if err != nil {
  278. key, _ = s.NewKey(fieldName, "")
  279. }
  280. if err = reflectWithProperType(tpField.Type, key, field, parseDelim(tpField.Tag.Get("delim"))); err != nil {
  281. return fmt.Errorf("error reflecting field(%s): %v", fieldName, err)
  282. }
  283. }
  284. return nil
  285. }
  286. // ReflectFrom reflects secion from given struct.
  287. func (s *Section) ReflectFrom(v interface{}) error {
  288. typ := reflect.TypeOf(v)
  289. val := reflect.ValueOf(v)
  290. if typ.Kind() == reflect.Ptr {
  291. typ = typ.Elem()
  292. val = val.Elem()
  293. } else {
  294. return errors.New("cannot reflect from non-pointer struct")
  295. }
  296. return s.reflectFrom(val)
  297. }
  298. // ReflectFrom reflects file from given struct.
  299. func (f *File) ReflectFrom(v interface{}) error {
  300. return f.Section("").ReflectFrom(v)
  301. }
  302. // ReflectFrom reflects data sources from given struct with name mapper.
  303. func ReflectFromWithMapper(cfg *File, v interface{}, mapper NameMapper) error {
  304. cfg.NameMapper = mapper
  305. return cfg.ReflectFrom(v)
  306. }
  307. // ReflectFrom reflects data sources from given struct.
  308. func ReflectFrom(cfg *File, v interface{}) error {
  309. return ReflectFromWithMapper(cfg, v, nil)
  310. }