converter.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. package converter
  2. import (
  3. "fmt"
  4. "reflect"
  5. "strconv"
  6. )
  7. // ConvertFrom interface allows structs to define custom conversion functions if the automated reflection-based Convert
  8. // is not able to convert properties due to name changes or other factors.
  9. type ConvertFrom interface {
  10. ConvertFrom(interface{}) error
  11. }
  12. // Convert takes two objects, e.g. v2_1.Document and &v2_2.Document{} and attempts to map all the properties from one
  13. // to the other. After the automatic mapping, if a struct implements the ConvertFrom interface, this is called to
  14. // perform any additional conversion logic necessary.
  15. func Convert(from interface{}, to interface{}) error {
  16. fromValue := reflect.ValueOf(from)
  17. toValuePtr := reflect.ValueOf(to)
  18. toTypePtr := toValuePtr.Type()
  19. if !isPtr(toTypePtr) {
  20. return fmt.Errorf("TO value provided was not a pointer, unable to set value: %v", to)
  21. }
  22. toValue, err := getValue(fromValue, toTypePtr)
  23. if err != nil {
  24. return err
  25. }
  26. // don't set nil values
  27. if toValue == nilValue {
  28. return nil
  29. }
  30. // toValuePtr is the passed-in pointer, toValue is also the same type of pointer
  31. toValuePtr.Elem().Set(toValue.Elem())
  32. return nil
  33. }
  34. func getValue(fromValue reflect.Value, targetType reflect.Type) (reflect.Value, error) {
  35. var err error
  36. fromType := fromValue.Type()
  37. var toValue reflect.Value
  38. // handle incoming pointer Types
  39. if isPtr(fromType) {
  40. if fromValue.IsNil() {
  41. return nilValue, nil
  42. }
  43. fromValue = fromValue.Elem()
  44. if !fromValue.IsValid() || fromValue.IsZero() {
  45. return nilValue, nil
  46. }
  47. fromType = fromValue.Type()
  48. }
  49. baseTargetType := targetType
  50. if isPtr(targetType) {
  51. baseTargetType = targetType.Elem()
  52. }
  53. switch {
  54. case isStruct(fromType) && isStruct(baseTargetType):
  55. // this always creates a pointer type
  56. toValue = reflect.New(baseTargetType)
  57. toValue = toValue.Elem()
  58. for i := 0; i < fromType.NumField(); i++ {
  59. fromField := fromType.Field(i)
  60. fromFieldValue := fromValue.Field(i)
  61. toField, exists := baseTargetType.FieldByName(fromField.Name)
  62. if !exists {
  63. continue
  64. }
  65. toFieldType := toField.Type
  66. toFieldValue := toValue.FieldByName(toField.Name)
  67. newValue, err := getValue(fromFieldValue, toFieldType)
  68. if err != nil {
  69. return nilValue, err
  70. }
  71. if newValue == nilValue {
  72. continue
  73. }
  74. toFieldValue.Set(newValue)
  75. }
  76. // allow structs to implement a custom convert function from previous/next version struct
  77. if reflect.PtrTo(baseTargetType).Implements(convertFromType) {
  78. convertFrom := toValue.Addr().MethodByName(convertFromName)
  79. if !convertFrom.IsValid() {
  80. return nilValue, fmt.Errorf("unable to get ConvertFrom method")
  81. }
  82. args := []reflect.Value{fromValue}
  83. out := convertFrom.Call(args)
  84. err := out[0].Interface()
  85. if err != nil {
  86. return nilValue, fmt.Errorf("an error occurred calling %s.%s: %v", baseTargetType.Name(), convertFromName, err)
  87. }
  88. }
  89. case isSlice(fromType) && isSlice(baseTargetType):
  90. if fromValue.IsNil() {
  91. return nilValue, nil
  92. }
  93. length := fromValue.Len()
  94. targetElementType := baseTargetType.Elem()
  95. toValue = reflect.MakeSlice(baseTargetType, length, length)
  96. for i := 0; i < length; i++ {
  97. v, err := getValue(fromValue.Index(i), targetElementType)
  98. if err != nil {
  99. return nilValue, err
  100. }
  101. if v.IsValid() {
  102. toValue.Index(i).Set(v)
  103. }
  104. }
  105. case isMap(fromType) && isMap(baseTargetType):
  106. if fromValue.IsNil() {
  107. return nilValue, nil
  108. }
  109. keyType := baseTargetType.Key()
  110. elementType := baseTargetType.Elem()
  111. toValue = reflect.MakeMap(baseTargetType)
  112. for _, fromKey := range fromValue.MapKeys() {
  113. fromVal := fromValue.MapIndex(fromKey)
  114. k, err := getValue(fromKey, keyType)
  115. if err != nil {
  116. return nilValue, err
  117. }
  118. v, err := getValue(fromVal, elementType)
  119. if err != nil {
  120. return nilValue, err
  121. }
  122. if k == nilValue || v == nilValue {
  123. continue
  124. }
  125. if v == nilValue {
  126. continue
  127. }
  128. if k.IsValid() && v.IsValid() {
  129. toValue.SetMapIndex(k, v)
  130. }
  131. }
  132. default:
  133. // TODO determine if there are other conversions
  134. toValue = fromValue
  135. }
  136. // handle non-pointer returns -- the reflect.New earlier always creates a pointer
  137. if !isPtr(baseTargetType) {
  138. toValue = fromPtr(toValue)
  139. }
  140. toValue, err = convertValueTypes(toValue, baseTargetType)
  141. if err != nil {
  142. return nilValue, err
  143. }
  144. // handle elements which are now pointers
  145. if isPtr(targetType) {
  146. toValue = toPtr(toValue)
  147. }
  148. return toValue, nil
  149. }
  150. // convertValueTypes takes a value and a target type, and attempts to convert
  151. // between the Types - e.g. string -> int. when this function is called the value
  152. func convertValueTypes(value reflect.Value, targetType reflect.Type) (reflect.Value, error) {
  153. typ := value.Type()
  154. switch {
  155. // if the Types are the same, just return the value
  156. case typ.Kind() == targetType.Kind():
  157. return value, nil
  158. case value.IsZero() && isPrimitive(targetType):
  159. case isPrimitive(typ) && isPrimitive(targetType):
  160. // get a string representation of the value
  161. str := fmt.Sprintf("%v", value.Interface()) // TODO is there a better way to get a string representation?
  162. var err error
  163. var out interface{}
  164. switch {
  165. case isString(targetType):
  166. out = str
  167. case isBool(targetType):
  168. out, err = strconv.ParseBool(str)
  169. case isInt(targetType):
  170. out, err = strconv.Atoi(str)
  171. case isUint(targetType):
  172. out, err = strconv.ParseUint(str, 10, 64)
  173. case isFloat(targetType):
  174. out, err = strconv.ParseFloat(str, 64)
  175. }
  176. if err != nil {
  177. return nilValue, err
  178. }
  179. v := reflect.ValueOf(out)
  180. v = v.Convert(targetType)
  181. return v, nil
  182. case isSlice(typ) && isSlice(targetType):
  183. // this should already be handled in getValue
  184. case isSlice(typ):
  185. // this may be lossy
  186. if value.Len() > 0 {
  187. v := value.Index(0)
  188. v, err := convertValueTypes(v, targetType)
  189. if err != nil {
  190. return nilValue, err
  191. }
  192. return v, nil
  193. }
  194. return convertValueTypes(nilValue, targetType)
  195. case isSlice(targetType):
  196. elementType := targetType.Elem()
  197. v, err := convertValueTypes(value, elementType)
  198. if err != nil {
  199. return nilValue, err
  200. }
  201. if v == nilValue {
  202. return v, nil
  203. }
  204. slice := reflect.MakeSlice(targetType, 1, 1)
  205. slice.Index(0).Set(v)
  206. return slice, nil
  207. }
  208. return nilValue, fmt.Errorf("unable to convert from: %v to %v", value.Interface(), targetType.Name())
  209. }
  210. func isPtr(typ reflect.Type) bool {
  211. return typ.Kind() == reflect.Ptr
  212. }
  213. func isPrimitive(typ reflect.Type) bool {
  214. return isString(typ) || isBool(typ) || isInt(typ) || isUint(typ) || isFloat(typ)
  215. }
  216. func isString(typ reflect.Type) bool {
  217. return typ.Kind() == reflect.String
  218. }
  219. func isBool(typ reflect.Type) bool {
  220. return typ.Kind() == reflect.Bool
  221. }
  222. func isInt(typ reflect.Type) bool {
  223. switch typ.Kind() {
  224. case reflect.Int,
  225. reflect.Int8,
  226. reflect.Int16,
  227. reflect.Int32,
  228. reflect.Int64:
  229. return true
  230. }
  231. return false
  232. }
  233. func isUint(typ reflect.Type) bool {
  234. switch typ.Kind() {
  235. case reflect.Uint,
  236. reflect.Uint8,
  237. reflect.Uint16,
  238. reflect.Uint32,
  239. reflect.Uint64:
  240. return true
  241. }
  242. return false
  243. }
  244. func isFloat(typ reflect.Type) bool {
  245. switch typ.Kind() {
  246. case reflect.Float32,
  247. reflect.Float64:
  248. return true
  249. }
  250. return false
  251. }
  252. func isStruct(typ reflect.Type) bool {
  253. return typ.Kind() == reflect.Struct
  254. }
  255. func isSlice(typ reflect.Type) bool {
  256. return typ.Kind() == reflect.Slice
  257. }
  258. func isMap(typ reflect.Type) bool {
  259. return typ.Kind() == reflect.Map
  260. }
  261. func toPtr(val reflect.Value) reflect.Value {
  262. typ := val.Type()
  263. if !isPtr(typ) {
  264. // this creates a pointer type inherently
  265. ptrVal := reflect.New(typ)
  266. ptrVal.Elem().Set(val)
  267. val = ptrVal
  268. }
  269. return val
  270. }
  271. func fromPtr(val reflect.Value) reflect.Value {
  272. if isPtr(val.Type()) {
  273. val = val.Elem()
  274. }
  275. return val
  276. }
  277. // convertFromName constant to find the ConvertFrom method
  278. const convertFromName = "ConvertFrom"
  279. var (
  280. // nilValue is returned in a number of cases when a value should not be set
  281. nilValue = reflect.ValueOf(nil)
  282. // convertFromType is the type to check for ConvertFrom implementations
  283. convertFromType = reflect.TypeOf((*ConvertFrom)(nil)).Elem()
  284. )