copier.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. package copier
  2. import (
  3. "database/sql"
  4. "database/sql/driver"
  5. "fmt"
  6. "reflect"
  7. "strings"
  8. "sync"
  9. "unicode"
  10. )
  11. // These flags define options for tag handling
  12. const (
  13. // Denotes that a destination field must be copied to. If copying fails then a panic will ensue.
  14. tagMust uint8 = 1 << iota
  15. // Denotes that the program should not panic when the must flag is on and
  16. // value is not copied. The program will return an error instead.
  17. tagNoPanic
  18. // Ignore a destination field from being copied to.
  19. tagIgnore
  20. // Denotes that the value as been copied
  21. hasCopied
  22. // Some default converter types for a nicer syntax
  23. String string = ""
  24. Bool bool = false
  25. Int int = 0
  26. Float32 float32 = 0
  27. Float64 float64 = 0
  28. )
  29. // Option sets copy options
  30. type Option struct {
  31. // setting this value to true will ignore copying zero values of all the fields, including bools, as well as a
  32. // struct having all it's fields set to their zero values respectively (see IsZero() in reflect/value.go)
  33. IgnoreEmpty bool
  34. CaseSensitive bool
  35. DeepCopy bool
  36. Converters []TypeConverter
  37. // Custom field name mappings to copy values with different names in `fromValue` and `toValue` types.
  38. // Examples can be found in `copier_field_name_mapping_test.go`.
  39. FieldNameMapping []FieldNameMapping
  40. }
  41. func (opt Option) converters() map[converterPair]TypeConverter {
  42. var converters = map[converterPair]TypeConverter{}
  43. // save converters into map for faster lookup
  44. for i := range opt.Converters {
  45. pair := converterPair{
  46. SrcType: reflect.TypeOf(opt.Converters[i].SrcType),
  47. DstType: reflect.TypeOf(opt.Converters[i].DstType),
  48. }
  49. converters[pair] = opt.Converters[i]
  50. }
  51. return converters
  52. }
  53. type TypeConverter struct {
  54. SrcType interface{}
  55. DstType interface{}
  56. Fn func(src interface{}) (dst interface{}, err error)
  57. }
  58. type converterPair struct {
  59. SrcType reflect.Type
  60. DstType reflect.Type
  61. }
  62. func (opt Option) fieldNameMapping() map[converterPair]FieldNameMapping {
  63. var mapping = map[converterPair]FieldNameMapping{}
  64. for i := range opt.FieldNameMapping {
  65. pair := converterPair{
  66. SrcType: reflect.TypeOf(opt.FieldNameMapping[i].SrcType),
  67. DstType: reflect.TypeOf(opt.FieldNameMapping[i].DstType),
  68. }
  69. mapping[pair] = opt.FieldNameMapping[i]
  70. }
  71. return mapping
  72. }
  73. type FieldNameMapping struct {
  74. SrcType interface{}
  75. DstType interface{}
  76. Mapping map[string]string
  77. }
  78. // Tag Flags
  79. type flags struct {
  80. BitFlags map[string]uint8
  81. SrcNames tagNameMapping
  82. DestNames tagNameMapping
  83. }
  84. // Field Tag name mapping
  85. type tagNameMapping struct {
  86. FieldNameToTag map[string]string
  87. TagToFieldName map[string]string
  88. }
  89. // Copy copy things
  90. func Copy(toValue interface{}, fromValue interface{}) (err error) {
  91. return copier(toValue, fromValue, Option{})
  92. }
  93. // CopyWithOption copy with option
  94. func CopyWithOption(toValue interface{}, fromValue interface{}, opt Option) (err error) {
  95. return copier(toValue, fromValue, opt)
  96. }
  97. func copier(toValue interface{}, fromValue interface{}, opt Option) (err error) {
  98. var (
  99. isSlice bool
  100. amount = 1
  101. from = indirect(reflect.ValueOf(fromValue))
  102. to = indirect(reflect.ValueOf(toValue))
  103. converters = opt.converters()
  104. mappings = opt.fieldNameMapping()
  105. )
  106. if !to.CanAddr() {
  107. return ErrInvalidCopyDestination
  108. }
  109. // Return is from value is invalid
  110. if !from.IsValid() {
  111. return ErrInvalidCopyFrom
  112. }
  113. fromType, isPtrFrom := indirectType(from.Type())
  114. toType, _ := indirectType(to.Type())
  115. if fromType.Kind() == reflect.Interface {
  116. fromType = reflect.TypeOf(from.Interface())
  117. }
  118. if toType.Kind() == reflect.Interface {
  119. toType, _ = indirectType(reflect.TypeOf(to.Interface()))
  120. oldTo := to
  121. to = reflect.New(reflect.TypeOf(to.Interface())).Elem()
  122. defer func() {
  123. oldTo.Set(to)
  124. }()
  125. }
  126. // Just set it if possible to assign for normal types
  127. if from.Kind() != reflect.Slice && from.Kind() != reflect.Struct && from.Kind() != reflect.Map && (from.Type().AssignableTo(to.Type()) || from.Type().ConvertibleTo(to.Type())) {
  128. if !isPtrFrom || !opt.DeepCopy {
  129. to.Set(from.Convert(to.Type()))
  130. } else {
  131. fromCopy := reflect.New(from.Type())
  132. fromCopy.Set(from.Elem())
  133. to.Set(fromCopy.Convert(to.Type()))
  134. }
  135. return
  136. }
  137. if from.Kind() != reflect.Slice && fromType.Kind() == reflect.Map && toType.Kind() == reflect.Map {
  138. if !fromType.Key().ConvertibleTo(toType.Key()) {
  139. return ErrMapKeyNotMatch
  140. }
  141. if to.IsNil() {
  142. to.Set(reflect.MakeMapWithSize(toType, from.Len()))
  143. }
  144. for _, k := range from.MapKeys() {
  145. toKey := indirect(reflect.New(toType.Key()))
  146. isSet, err := set(toKey, k, opt.DeepCopy, converters)
  147. if err != nil {
  148. return err
  149. }
  150. if !isSet {
  151. return fmt.Errorf("%w map, old key: %v, new key: %v", ErrNotSupported, k.Type(), toType.Key())
  152. }
  153. elemType := toType.Elem()
  154. if elemType.Kind() != reflect.Slice {
  155. elemType, _ = indirectType(elemType)
  156. }
  157. toValue := indirect(reflect.New(elemType))
  158. isSet, err = set(toValue, from.MapIndex(k), opt.DeepCopy, converters)
  159. if err != nil {
  160. return err
  161. }
  162. if !isSet {
  163. if err = copier(toValue.Addr().Interface(), from.MapIndex(k).Interface(), opt); err != nil {
  164. return err
  165. }
  166. }
  167. for {
  168. if elemType == toType.Elem() {
  169. to.SetMapIndex(toKey, toValue)
  170. break
  171. }
  172. elemType = reflect.PtrTo(elemType)
  173. toValue = toValue.Addr()
  174. }
  175. }
  176. return
  177. }
  178. if from.Kind() == reflect.Slice && to.Kind() == reflect.Slice {
  179. if to.IsNil() {
  180. slice := reflect.MakeSlice(reflect.SliceOf(to.Type().Elem()), from.Len(), from.Cap())
  181. to.Set(slice)
  182. }
  183. if fromType.ConvertibleTo(toType) {
  184. for i := 0; i < from.Len(); i++ {
  185. if to.Len() < i+1 {
  186. to.Set(reflect.Append(to, reflect.New(to.Type().Elem()).Elem()))
  187. }
  188. isSet, err := set(to.Index(i), from.Index(i), opt.DeepCopy, converters)
  189. if err != nil {
  190. return err
  191. }
  192. if !isSet {
  193. // ignore error while copy slice element
  194. err = copier(to.Index(i).Addr().Interface(), from.Index(i).Interface(), opt)
  195. if err != nil {
  196. continue
  197. }
  198. }
  199. }
  200. return
  201. }
  202. }
  203. if fromType.Kind() != reflect.Struct || toType.Kind() != reflect.Struct {
  204. // skip not supported type
  205. return
  206. }
  207. if len(converters) > 0 {
  208. if ok, e := set(to, from, opt.DeepCopy, converters); e == nil && ok {
  209. // converter supported
  210. return
  211. }
  212. }
  213. if from.Kind() == reflect.Slice || to.Kind() == reflect.Slice {
  214. isSlice = true
  215. if from.Kind() == reflect.Slice {
  216. amount = from.Len()
  217. }
  218. }
  219. for i := 0; i < amount; i++ {
  220. var dest, source reflect.Value
  221. if isSlice {
  222. // source
  223. if from.Kind() == reflect.Slice {
  224. source = indirect(from.Index(i))
  225. } else {
  226. source = indirect(from)
  227. }
  228. // dest
  229. dest = indirect(reflect.New(toType).Elem())
  230. } else {
  231. source = indirect(from)
  232. dest = indirect(to)
  233. }
  234. if len(converters) > 0 {
  235. if ok, e := set(dest, source, opt.DeepCopy, converters); e == nil && ok {
  236. if isSlice {
  237. // FIXME: maybe should check the other types?
  238. if to.Type().Elem().Kind() == reflect.Ptr {
  239. to.Index(i).Set(dest.Addr())
  240. } else {
  241. if to.Len() < i+1 {
  242. reflect.Append(to, dest)
  243. } else {
  244. to.Index(i).Set(dest)
  245. }
  246. }
  247. } else {
  248. to.Set(dest)
  249. }
  250. continue
  251. }
  252. }
  253. destKind := dest.Kind()
  254. initDest := false
  255. if destKind == reflect.Interface {
  256. initDest = true
  257. dest = indirect(reflect.New(toType))
  258. }
  259. // Get tag options
  260. flgs, err := getFlags(dest, source, toType, fromType)
  261. if err != nil {
  262. return err
  263. }
  264. // check source
  265. if source.IsValid() {
  266. copyUnexportedStructFields(dest, source)
  267. // Copy from source field to dest field or method
  268. fromTypeFields := deepFields(fromType)
  269. for _, field := range fromTypeFields {
  270. name := field.Name
  271. // Get bit flags for field
  272. fieldFlags := flgs.BitFlags[name]
  273. // Check if we should ignore copying
  274. if (fieldFlags & tagIgnore) != 0 {
  275. continue
  276. }
  277. fieldNamesMapping := getFieldNamesMapping(mappings, fromType, toType)
  278. srcFieldName, destFieldName := getFieldName(name, flgs, fieldNamesMapping)
  279. if fromField := fieldByNameOrZeroValue(source, srcFieldName); fromField.IsValid() && !shouldIgnore(fromField, opt.IgnoreEmpty) {
  280. // process for nested anonymous field
  281. destFieldNotSet := false
  282. if f, ok := dest.Type().FieldByName(destFieldName); ok {
  283. // only initialize parent embedded struct pointer in the path
  284. for idx := range f.Index[:len(f.Index)-1] {
  285. destField := dest.FieldByIndex(f.Index[:idx+1])
  286. if destField.Kind() != reflect.Ptr {
  287. continue
  288. }
  289. if !destField.IsNil() {
  290. continue
  291. }
  292. if !destField.CanSet() {
  293. destFieldNotSet = true
  294. break
  295. }
  296. // destField is a nil pointer that can be set
  297. newValue := reflect.New(destField.Type().Elem())
  298. destField.Set(newValue)
  299. }
  300. }
  301. if destFieldNotSet {
  302. break
  303. }
  304. toField := fieldByName(dest, destFieldName, opt.CaseSensitive)
  305. if toField.IsValid() {
  306. if toField.CanSet() {
  307. isSet, err := set(toField, fromField, opt.DeepCopy, converters)
  308. if err != nil {
  309. return err
  310. }
  311. if !isSet {
  312. if err := copier(toField.Addr().Interface(), fromField.Interface(), opt); err != nil {
  313. return err
  314. }
  315. }
  316. if fieldFlags != 0 {
  317. // Note that a copy was made
  318. flgs.BitFlags[name] = fieldFlags | hasCopied
  319. }
  320. }
  321. } else {
  322. // try to set to method
  323. var toMethod reflect.Value
  324. if dest.CanAddr() {
  325. toMethod = dest.Addr().MethodByName(destFieldName)
  326. } else {
  327. toMethod = dest.MethodByName(destFieldName)
  328. }
  329. if toMethod.IsValid() && toMethod.Type().NumIn() == 1 && fromField.Type().AssignableTo(toMethod.Type().In(0)) {
  330. toMethod.Call([]reflect.Value{fromField})
  331. }
  332. }
  333. }
  334. }
  335. // Copy from from method to dest field
  336. for _, field := range deepFields(toType) {
  337. name := field.Name
  338. srcFieldName, destFieldName := getFieldName(name, flgs, getFieldNamesMapping(mappings, fromType, toType))
  339. var fromMethod reflect.Value
  340. if source.CanAddr() {
  341. fromMethod = source.Addr().MethodByName(srcFieldName)
  342. } else {
  343. fromMethod = source.MethodByName(srcFieldName)
  344. }
  345. if fromMethod.IsValid() && fromMethod.Type().NumIn() == 0 && fromMethod.Type().NumOut() == 1 && !shouldIgnore(fromMethod, opt.IgnoreEmpty) {
  346. if toField := fieldByName(dest, destFieldName, opt.CaseSensitive); toField.IsValid() && toField.CanSet() {
  347. values := fromMethod.Call([]reflect.Value{})
  348. if len(values) >= 1 {
  349. set(toField, values[0], opt.DeepCopy, converters)
  350. }
  351. }
  352. }
  353. }
  354. }
  355. if isSlice && to.Kind() == reflect.Slice {
  356. if dest.Addr().Type().AssignableTo(to.Type().Elem()) {
  357. if to.Len() < i+1 {
  358. to.Set(reflect.Append(to, dest.Addr()))
  359. } else {
  360. isSet, err := set(to.Index(i), dest.Addr(), opt.DeepCopy, converters)
  361. if err != nil {
  362. return err
  363. }
  364. if !isSet {
  365. // ignore error while copy slice element
  366. err = copier(to.Index(i).Addr().Interface(), dest.Addr().Interface(), opt)
  367. if err != nil {
  368. continue
  369. }
  370. }
  371. }
  372. } else if dest.Type().AssignableTo(to.Type().Elem()) {
  373. if to.Len() < i+1 {
  374. to.Set(reflect.Append(to, dest))
  375. } else {
  376. isSet, err := set(to.Index(i), dest, opt.DeepCopy, converters)
  377. if err != nil {
  378. return err
  379. }
  380. if !isSet {
  381. // ignore error while copy slice element
  382. err = copier(to.Index(i).Addr().Interface(), dest.Interface(), opt)
  383. if err != nil {
  384. continue
  385. }
  386. }
  387. }
  388. }
  389. } else if initDest {
  390. to.Set(dest)
  391. }
  392. err = checkBitFlags(flgs.BitFlags)
  393. }
  394. return
  395. }
  396. func getFieldNamesMapping(mappings map[converterPair]FieldNameMapping, fromType reflect.Type, toType reflect.Type) map[string]string {
  397. var fieldNamesMapping map[string]string
  398. if len(mappings) > 0 {
  399. pair := converterPair{
  400. SrcType: fromType,
  401. DstType: toType,
  402. }
  403. if v, ok := mappings[pair]; ok {
  404. fieldNamesMapping = v.Mapping
  405. }
  406. }
  407. return fieldNamesMapping
  408. }
  409. func fieldByNameOrZeroValue(source reflect.Value, fieldName string) (value reflect.Value) {
  410. defer func() {
  411. if err := recover(); err != nil {
  412. value = reflect.Value{}
  413. }
  414. }()
  415. return source.FieldByName(fieldName)
  416. }
  417. func copyUnexportedStructFields(to, from reflect.Value) {
  418. if from.Kind() != reflect.Struct || to.Kind() != reflect.Struct || !from.Type().AssignableTo(to.Type()) {
  419. return
  420. }
  421. // create a shallow copy of 'to' to get all fields
  422. tmp := indirect(reflect.New(to.Type()))
  423. tmp.Set(from)
  424. // revert exported fields
  425. for i := 0; i < to.NumField(); i++ {
  426. if tmp.Field(i).CanSet() {
  427. tmp.Field(i).Set(to.Field(i))
  428. }
  429. }
  430. to.Set(tmp)
  431. }
  432. func shouldIgnore(v reflect.Value, ignoreEmpty bool) bool {
  433. return ignoreEmpty && v.IsZero()
  434. }
  435. var deepFieldsLock sync.RWMutex
  436. var deepFieldsMap = make(map[reflect.Type][]reflect.StructField)
  437. func deepFields(reflectType reflect.Type) []reflect.StructField {
  438. deepFieldsLock.RLock()
  439. cache, ok := deepFieldsMap[reflectType]
  440. deepFieldsLock.RUnlock()
  441. if ok {
  442. return cache
  443. }
  444. var res []reflect.StructField
  445. if reflectType, _ = indirectType(reflectType); reflectType.Kind() == reflect.Struct {
  446. fields := make([]reflect.StructField, 0, reflectType.NumField())
  447. for i := 0; i < reflectType.NumField(); i++ {
  448. v := reflectType.Field(i)
  449. // PkgPath is the package path that qualifies a lower case (unexported)
  450. // field name. It is empty for upper case (exported) field names.
  451. // See https://golang.org/ref/spec#Uniqueness_of_identifiers
  452. if v.PkgPath == "" {
  453. fields = append(fields, v)
  454. if v.Anonymous {
  455. // also consider fields of anonymous fields as fields of the root
  456. fields = append(fields, deepFields(v.Type)...)
  457. }
  458. }
  459. }
  460. res = fields
  461. }
  462. deepFieldsLock.Lock()
  463. deepFieldsMap[reflectType] = res
  464. deepFieldsLock.Unlock()
  465. return res
  466. }
  467. func indirect(reflectValue reflect.Value) reflect.Value {
  468. for reflectValue.Kind() == reflect.Ptr {
  469. reflectValue = reflectValue.Elem()
  470. }
  471. return reflectValue
  472. }
  473. func indirectType(reflectType reflect.Type) (_ reflect.Type, isPtr bool) {
  474. for reflectType.Kind() == reflect.Ptr || reflectType.Kind() == reflect.Slice {
  475. reflectType = reflectType.Elem()
  476. isPtr = true
  477. }
  478. return reflectType, isPtr
  479. }
  480. func set(to, from reflect.Value, deepCopy bool, converters map[converterPair]TypeConverter) (bool, error) {
  481. if !from.IsValid() {
  482. return true, nil
  483. }
  484. if ok, err := lookupAndCopyWithConverter(to, from, converters); err != nil {
  485. return false, err
  486. } else if ok {
  487. return true, nil
  488. }
  489. if to.Kind() == reflect.Ptr {
  490. // set `to` to nil if from is nil
  491. if from.Kind() == reflect.Ptr && from.IsNil() {
  492. to.Set(reflect.Zero(to.Type()))
  493. return true, nil
  494. } else if to.IsNil() {
  495. // `from` -> `to`
  496. // sql.NullString -> *string
  497. if fromValuer, ok := driverValuer(from); ok {
  498. v, err := fromValuer.Value()
  499. if err != nil {
  500. return true, nil
  501. }
  502. // if `from` is not valid do nothing with `to`
  503. if v == nil {
  504. return true, nil
  505. }
  506. }
  507. // allocate new `to` variable with default value (eg. *string -> new(string))
  508. to.Set(reflect.New(to.Type().Elem()))
  509. }
  510. // depointer `to`
  511. to = to.Elem()
  512. }
  513. if deepCopy {
  514. toKind := to.Kind()
  515. if toKind == reflect.Interface && to.IsNil() {
  516. if reflect.TypeOf(from.Interface()) != nil {
  517. to.Set(reflect.New(reflect.TypeOf(from.Interface())).Elem())
  518. toKind = reflect.TypeOf(to.Interface()).Kind()
  519. }
  520. }
  521. if from.Kind() == reflect.Ptr && from.IsNil() {
  522. return true, nil
  523. }
  524. if _, ok := to.Addr().Interface().(sql.Scanner); !ok && (toKind == reflect.Struct || toKind == reflect.Map || toKind == reflect.Slice) {
  525. return false, nil
  526. }
  527. }
  528. if from.Type().ConvertibleTo(to.Type()) {
  529. to.Set(from.Convert(to.Type()))
  530. } else if toScanner, ok := to.Addr().Interface().(sql.Scanner); ok {
  531. // `from` -> `to`
  532. // *string -> sql.NullString
  533. if from.Kind() == reflect.Ptr {
  534. // if `from` is nil do nothing with `to`
  535. if from.IsNil() {
  536. return true, nil
  537. }
  538. // depointer `from`
  539. from = indirect(from)
  540. }
  541. // `from` -> `to`
  542. // string -> sql.NullString
  543. // set `to` by invoking method Scan(`from`)
  544. err := toScanner.Scan(from.Interface())
  545. if err != nil {
  546. return false, nil
  547. }
  548. } else if fromValuer, ok := driverValuer(from); ok {
  549. // `from` -> `to`
  550. // sql.NullString -> string
  551. v, err := fromValuer.Value()
  552. if err != nil {
  553. return false, nil
  554. }
  555. // if `from` is not valid do nothing with `to`
  556. if v == nil {
  557. return true, nil
  558. }
  559. rv := reflect.ValueOf(v)
  560. if rv.Type().AssignableTo(to.Type()) {
  561. to.Set(rv)
  562. } else if to.CanSet() && rv.Type().ConvertibleTo(to.Type()) {
  563. to.Set(rv.Convert(to.Type()))
  564. }
  565. } else if from.Kind() == reflect.Ptr {
  566. return set(to, from.Elem(), deepCopy, converters)
  567. } else {
  568. return false, nil
  569. }
  570. return true, nil
  571. }
  572. // lookupAndCopyWithConverter looks up the type pair, on success the TypeConverter Fn func is called to copy src to dst field.
  573. func lookupAndCopyWithConverter(to, from reflect.Value, converters map[converterPair]TypeConverter) (copied bool, err error) {
  574. pair := converterPair{
  575. SrcType: from.Type(),
  576. DstType: to.Type(),
  577. }
  578. if cnv, ok := converters[pair]; ok {
  579. result, err := cnv.Fn(from.Interface())
  580. if err != nil {
  581. return false, err
  582. }
  583. if result != nil {
  584. to.Set(reflect.ValueOf(result))
  585. } else {
  586. // in case we've got a nil value to copy
  587. to.Set(reflect.Zero(to.Type()))
  588. }
  589. return true, nil
  590. }
  591. return false, nil
  592. }
  593. // parseTags Parses struct tags and returns uint8 bit flags.
  594. func parseTags(tag string) (flg uint8, name string, err error) {
  595. for _, t := range strings.Split(tag, ",") {
  596. switch t {
  597. case "-":
  598. flg = tagIgnore
  599. return
  600. case "must":
  601. flg = flg | tagMust
  602. case "nopanic":
  603. flg = flg | tagNoPanic
  604. default:
  605. if unicode.IsUpper([]rune(t)[0]) {
  606. name = strings.TrimSpace(t)
  607. } else {
  608. err = ErrFieldNameTagStartNotUpperCase
  609. }
  610. }
  611. }
  612. return
  613. }
  614. // getTagFlags Parses struct tags for bit flags, field name.
  615. func getFlags(dest, src reflect.Value, toType, fromType reflect.Type) (flags, error) {
  616. flgs := flags{
  617. BitFlags: map[string]uint8{},
  618. SrcNames: tagNameMapping{
  619. FieldNameToTag: map[string]string{},
  620. TagToFieldName: map[string]string{},
  621. },
  622. DestNames: tagNameMapping{
  623. FieldNameToTag: map[string]string{},
  624. TagToFieldName: map[string]string{},
  625. },
  626. }
  627. var toTypeFields, fromTypeFields []reflect.StructField
  628. if dest.IsValid() {
  629. toTypeFields = deepFields(toType)
  630. }
  631. if src.IsValid() {
  632. fromTypeFields = deepFields(fromType)
  633. }
  634. // Get a list dest of tags
  635. for _, field := range toTypeFields {
  636. tags := field.Tag.Get("copier")
  637. if tags != "" {
  638. var name string
  639. var err error
  640. if flgs.BitFlags[field.Name], name, err = parseTags(tags); err != nil {
  641. return flags{}, err
  642. } else if name != "" {
  643. flgs.DestNames.FieldNameToTag[field.Name] = name
  644. flgs.DestNames.TagToFieldName[name] = field.Name
  645. }
  646. }
  647. }
  648. // Get a list source of tags
  649. for _, field := range fromTypeFields {
  650. tags := field.Tag.Get("copier")
  651. if tags != "" {
  652. var name string
  653. var err error
  654. if _, name, err = parseTags(tags); err != nil {
  655. return flags{}, err
  656. } else if name != "" {
  657. flgs.SrcNames.FieldNameToTag[field.Name] = name
  658. flgs.SrcNames.TagToFieldName[name] = field.Name
  659. }
  660. }
  661. }
  662. return flgs, nil
  663. }
  664. // checkBitFlags Checks flags for error or panic conditions.
  665. func checkBitFlags(flagsList map[string]uint8) (err error) {
  666. // Check flag conditions were met
  667. for name, flgs := range flagsList {
  668. if flgs&hasCopied == 0 {
  669. switch {
  670. case flgs&tagMust != 0 && flgs&tagNoPanic != 0:
  671. err = fmt.Errorf("field %s has must tag but was not copied", name)
  672. return
  673. case flgs&(tagMust) != 0:
  674. panic(fmt.Sprintf("Field %s has must tag but was not copied", name))
  675. }
  676. }
  677. }
  678. return
  679. }
  680. func getFieldName(fieldName string, flgs flags, fieldNameMapping map[string]string) (srcFieldName string, destFieldName string) {
  681. // get dest field name
  682. if name, ok := fieldNameMapping[fieldName]; ok {
  683. srcFieldName = fieldName
  684. destFieldName = name
  685. return
  686. }
  687. if srcTagName, ok := flgs.SrcNames.FieldNameToTag[fieldName]; ok {
  688. destFieldName = srcTagName
  689. if destTagName, ok := flgs.DestNames.TagToFieldName[srcTagName]; ok {
  690. destFieldName = destTagName
  691. }
  692. } else {
  693. if destTagName, ok := flgs.DestNames.TagToFieldName[fieldName]; ok {
  694. destFieldName = destTagName
  695. }
  696. }
  697. if destFieldName == "" {
  698. destFieldName = fieldName
  699. }
  700. // get source field name
  701. if destTagName, ok := flgs.DestNames.FieldNameToTag[fieldName]; ok {
  702. srcFieldName = destTagName
  703. if srcField, ok := flgs.SrcNames.TagToFieldName[destTagName]; ok {
  704. srcFieldName = srcField
  705. }
  706. } else {
  707. if srcField, ok := flgs.SrcNames.TagToFieldName[fieldName]; ok {
  708. srcFieldName = srcField
  709. }
  710. }
  711. if srcFieldName == "" {
  712. srcFieldName = fieldName
  713. }
  714. return
  715. }
  716. func driverValuer(v reflect.Value) (i driver.Valuer, ok bool) {
  717. if !v.CanAddr() {
  718. i, ok = v.Interface().(driver.Valuer)
  719. return
  720. }
  721. i, ok = v.Addr().Interface().(driver.Valuer)
  722. return
  723. }
  724. func fieldByName(v reflect.Value, name string, caseSensitive bool) reflect.Value {
  725. if caseSensitive {
  726. return v.FieldByName(name)
  727. }
  728. return v.FieldByNameFunc(func(n string) bool { return strings.EqualFold(n, name) })
  729. }