converter.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package conversion
  14. import (
  15. "fmt"
  16. "reflect"
  17. )
  18. type typePair struct {
  19. source reflect.Type
  20. dest reflect.Type
  21. }
  22. type typeNamePair struct {
  23. fieldType reflect.Type
  24. fieldName string
  25. }
  26. // DebugLogger allows you to get debugging messages if necessary.
  27. type DebugLogger interface {
  28. Logf(format string, args ...interface{})
  29. }
  30. type NameFunc func(t reflect.Type) string
  31. var DefaultNameFunc = func(t reflect.Type) string { return t.Name() }
  32. type GenericConversionFunc func(a, b interface{}, scope Scope) (bool, error)
  33. // Converter knows how to convert one type to another.
  34. type Converter struct {
  35. // Map from the conversion pair to a function which can
  36. // do the conversion.
  37. conversionFuncs ConversionFuncs
  38. generatedConversionFuncs ConversionFuncs
  39. // genericConversions are called during normal conversion to offer a "fast-path"
  40. // that avoids all reflection. These methods are not called outside of the .Convert()
  41. // method.
  42. genericConversions []GenericConversionFunc
  43. // Set of conversions that should be treated as a no-op
  44. ignoredConversions map[typePair]struct{}
  45. // This is a map from a source field type and name, to a list of destination
  46. // field type and name.
  47. structFieldDests map[typeNamePair][]typeNamePair
  48. // Allows for the opposite lookup of structFieldDests. So that SourceFromDest
  49. // copy flag also works. So this is a map of destination field name, to potential
  50. // source field name and type to look for.
  51. structFieldSources map[typeNamePair][]typeNamePair
  52. // Map from an input type to a function which can apply a key name mapping
  53. inputFieldMappingFuncs map[reflect.Type]FieldMappingFunc
  54. // Map from an input type to a set of default conversion flags.
  55. inputDefaultFlags map[reflect.Type]FieldMatchingFlags
  56. // If non-nil, will be called to print helpful debugging info. Quite verbose.
  57. Debug DebugLogger
  58. // nameFunc is called to retrieve the name of a type; this name is used for the
  59. // purpose of deciding whether two types match or not (i.e., will we attempt to
  60. // do a conversion). The default returns the go type name.
  61. nameFunc func(t reflect.Type) string
  62. }
  63. // NewConverter creates a new Converter object.
  64. func NewConverter(nameFn NameFunc) *Converter {
  65. c := &Converter{
  66. conversionFuncs: NewConversionFuncs(),
  67. generatedConversionFuncs: NewConversionFuncs(),
  68. ignoredConversions: make(map[typePair]struct{}),
  69. nameFunc: nameFn,
  70. structFieldDests: make(map[typeNamePair][]typeNamePair),
  71. structFieldSources: make(map[typeNamePair][]typeNamePair),
  72. inputFieldMappingFuncs: make(map[reflect.Type]FieldMappingFunc),
  73. inputDefaultFlags: make(map[reflect.Type]FieldMatchingFlags),
  74. }
  75. c.RegisterConversionFunc(Convert_Slice_byte_To_Slice_byte)
  76. return c
  77. }
  78. // AddGenericConversionFunc adds a function that accepts the ConversionFunc call pattern
  79. // (for two conversion types) to the converter. These functions are checked first during
  80. // a normal conversion, but are otherwise not called. Use AddConversionFuncs when registering
  81. // typed conversions.
  82. func (c *Converter) AddGenericConversionFunc(fn GenericConversionFunc) {
  83. c.genericConversions = append(c.genericConversions, fn)
  84. }
  85. // WithConversions returns a Converter that is a copy of c but with the additional
  86. // fns merged on top.
  87. func (c *Converter) WithConversions(fns ConversionFuncs) *Converter {
  88. copied := *c
  89. copied.conversionFuncs = c.conversionFuncs.Merge(fns)
  90. return &copied
  91. }
  92. // DefaultMeta returns the conversion FieldMappingFunc and meta for a given type.
  93. func (c *Converter) DefaultMeta(t reflect.Type) (FieldMatchingFlags, *Meta) {
  94. return c.inputDefaultFlags[t], &Meta{
  95. KeyNameMapping: c.inputFieldMappingFuncs[t],
  96. }
  97. }
  98. // Convert_Slice_byte_To_Slice_byte prevents recursing into every byte
  99. func Convert_Slice_byte_To_Slice_byte(in *[]byte, out *[]byte, s Scope) error {
  100. if *in == nil {
  101. *out = nil
  102. return nil
  103. }
  104. *out = make([]byte, len(*in))
  105. copy(*out, *in)
  106. return nil
  107. }
  108. // Scope is passed to conversion funcs to allow them to continue an ongoing conversion.
  109. // If multiple converters exist in the system, Scope will allow you to use the correct one
  110. // from a conversion function--that is, the one your conversion function was called by.
  111. type Scope interface {
  112. // Call Convert to convert sub-objects. Note that if you call it with your own exact
  113. // parameters, you'll run out of stack space before anything useful happens.
  114. Convert(src, dest interface{}, flags FieldMatchingFlags) error
  115. // DefaultConvert performs the default conversion, without calling a conversion func
  116. // on the current stack frame. This makes it safe to call from a conversion func.
  117. DefaultConvert(src, dest interface{}, flags FieldMatchingFlags) error
  118. // SrcTags and DestTags contain the struct tags that src and dest had, respectively.
  119. // If the enclosing object was not a struct, then these will contain no tags, of course.
  120. SrcTag() reflect.StructTag
  121. DestTag() reflect.StructTag
  122. // Flags returns the flags with which the conversion was started.
  123. Flags() FieldMatchingFlags
  124. // Meta returns any information originally passed to Convert.
  125. Meta() *Meta
  126. }
  127. // FieldMappingFunc can convert an input field value into different values, depending on
  128. // the value of the source or destination struct tags.
  129. type FieldMappingFunc func(key string, sourceTag, destTag reflect.StructTag) (source string, dest string)
  130. func NewConversionFuncs() ConversionFuncs {
  131. return ConversionFuncs{fns: make(map[typePair]reflect.Value)}
  132. }
  133. type ConversionFuncs struct {
  134. fns map[typePair]reflect.Value
  135. }
  136. // Add adds the provided conversion functions to the lookup table - they must have the signature
  137. // `func(type1, type2, Scope) error`. Functions are added in the order passed and will override
  138. // previously registered pairs.
  139. func (c ConversionFuncs) Add(fns ...interface{}) error {
  140. for _, fn := range fns {
  141. fv := reflect.ValueOf(fn)
  142. ft := fv.Type()
  143. if err := verifyConversionFunctionSignature(ft); err != nil {
  144. return err
  145. }
  146. c.fns[typePair{ft.In(0).Elem(), ft.In(1).Elem()}] = fv
  147. }
  148. return nil
  149. }
  150. // Merge returns a new ConversionFuncs that contains all conversions from
  151. // both other and c, with other conversions taking precedence.
  152. func (c ConversionFuncs) Merge(other ConversionFuncs) ConversionFuncs {
  153. merged := NewConversionFuncs()
  154. for k, v := range c.fns {
  155. merged.fns[k] = v
  156. }
  157. for k, v := range other.fns {
  158. merged.fns[k] = v
  159. }
  160. return merged
  161. }
  162. // Meta is supplied by Scheme, when it calls Convert.
  163. type Meta struct {
  164. // KeyNameMapping is an optional function which may map the listed key (field name)
  165. // into a source and destination value.
  166. KeyNameMapping FieldMappingFunc
  167. // Context is an optional field that callers may use to pass info to conversion functions.
  168. Context interface{}
  169. }
  170. // scope contains information about an ongoing conversion.
  171. type scope struct {
  172. converter *Converter
  173. meta *Meta
  174. flags FieldMatchingFlags
  175. // srcStack & destStack are separate because they may not have a 1:1
  176. // relationship.
  177. srcStack scopeStack
  178. destStack scopeStack
  179. }
  180. type scopeStackElem struct {
  181. tag reflect.StructTag
  182. value reflect.Value
  183. key string
  184. }
  185. type scopeStack []scopeStackElem
  186. func (s *scopeStack) pop() {
  187. n := len(*s)
  188. *s = (*s)[:n-1]
  189. }
  190. func (s *scopeStack) push(e scopeStackElem) {
  191. *s = append(*s, e)
  192. }
  193. func (s *scopeStack) top() *scopeStackElem {
  194. return &(*s)[len(*s)-1]
  195. }
  196. func (s scopeStack) describe() string {
  197. desc := ""
  198. if len(s) > 1 {
  199. desc = "(" + s[1].value.Type().String() + ")"
  200. }
  201. for i, v := range s {
  202. if i < 2 {
  203. // First layer on stack is not real; second is handled specially above.
  204. continue
  205. }
  206. if v.key == "" {
  207. desc += fmt.Sprintf(".%v", v.value.Type())
  208. } else {
  209. desc += fmt.Sprintf(".%v", v.key)
  210. }
  211. }
  212. return desc
  213. }
  214. // Formats src & dest as indices for printing.
  215. func (s *scope) setIndices(src, dest int) {
  216. s.srcStack.top().key = fmt.Sprintf("[%v]", src)
  217. s.destStack.top().key = fmt.Sprintf("[%v]", dest)
  218. }
  219. // Formats src & dest as map keys for printing.
  220. func (s *scope) setKeys(src, dest interface{}) {
  221. s.srcStack.top().key = fmt.Sprintf(`["%v"]`, src)
  222. s.destStack.top().key = fmt.Sprintf(`["%v"]`, dest)
  223. }
  224. // Convert continues a conversion.
  225. func (s *scope) Convert(src, dest interface{}, flags FieldMatchingFlags) error {
  226. return s.converter.Convert(src, dest, flags, s.meta)
  227. }
  228. // DefaultConvert continues a conversion, performing a default conversion (no conversion func)
  229. // for the current stack frame.
  230. func (s *scope) DefaultConvert(src, dest interface{}, flags FieldMatchingFlags) error {
  231. return s.converter.DefaultConvert(src, dest, flags, s.meta)
  232. }
  233. // SrcTag returns the tag of the struct containing the current source item, if any.
  234. func (s *scope) SrcTag() reflect.StructTag {
  235. return s.srcStack.top().tag
  236. }
  237. // DestTag returns the tag of the struct containing the current dest item, if any.
  238. func (s *scope) DestTag() reflect.StructTag {
  239. return s.destStack.top().tag
  240. }
  241. // Flags returns the flags with which the current conversion was started.
  242. func (s *scope) Flags() FieldMatchingFlags {
  243. return s.flags
  244. }
  245. // Meta returns the meta object that was originally passed to Convert.
  246. func (s *scope) Meta() *Meta {
  247. return s.meta
  248. }
  249. // describe prints the path to get to the current (source, dest) values.
  250. func (s *scope) describe() (src, dest string) {
  251. return s.srcStack.describe(), s.destStack.describe()
  252. }
  253. // error makes an error that includes information about where we were in the objects
  254. // we were asked to convert.
  255. func (s *scope) errorf(message string, args ...interface{}) error {
  256. srcPath, destPath := s.describe()
  257. where := fmt.Sprintf("converting %v to %v: ", srcPath, destPath)
  258. return fmt.Errorf(where+message, args...)
  259. }
  260. // Verifies whether a conversion function has a correct signature.
  261. func verifyConversionFunctionSignature(ft reflect.Type) error {
  262. if ft.Kind() != reflect.Func {
  263. return fmt.Errorf("expected func, got: %v", ft)
  264. }
  265. if ft.NumIn() != 3 {
  266. return fmt.Errorf("expected three 'in' params, got: %v", ft)
  267. }
  268. if ft.NumOut() != 1 {
  269. return fmt.Errorf("expected one 'out' param, got: %v", ft)
  270. }
  271. if ft.In(0).Kind() != reflect.Ptr {
  272. return fmt.Errorf("expected pointer arg for 'in' param 0, got: %v", ft)
  273. }
  274. if ft.In(1).Kind() != reflect.Ptr {
  275. return fmt.Errorf("expected pointer arg for 'in' param 1, got: %v", ft)
  276. }
  277. scopeType := Scope(nil)
  278. if e, a := reflect.TypeOf(&scopeType).Elem(), ft.In(2); e != a {
  279. return fmt.Errorf("expected '%v' arg for 'in' param 2, got '%v' (%v)", e, a, ft)
  280. }
  281. var forErrorType error
  282. // This convolution is necessary, otherwise TypeOf picks up on the fact
  283. // that forErrorType is nil.
  284. errorType := reflect.TypeOf(&forErrorType).Elem()
  285. if ft.Out(0) != errorType {
  286. return fmt.Errorf("expected error return, got: %v", ft)
  287. }
  288. return nil
  289. }
  290. // RegisterConversionFunc registers a conversion func with the
  291. // Converter. conversionFunc must take three parameters: a pointer to the input
  292. // type, a pointer to the output type, and a conversion.Scope (which should be
  293. // used if recursive conversion calls are desired). It must return an error.
  294. //
  295. // Example:
  296. // c.RegisterConversionFunc(
  297. // func(in *Pod, out *v1.Pod, s Scope) error {
  298. // // conversion logic...
  299. // return nil
  300. // })
  301. func (c *Converter) RegisterConversionFunc(conversionFunc interface{}) error {
  302. return c.conversionFuncs.Add(conversionFunc)
  303. }
  304. // Similar to RegisterConversionFunc, but registers conversion function that were
  305. // automatically generated.
  306. func (c *Converter) RegisterGeneratedConversionFunc(conversionFunc interface{}) error {
  307. return c.generatedConversionFuncs.Add(conversionFunc)
  308. }
  309. // RegisterIgnoredConversion registers a "no-op" for conversion, where any requested
  310. // conversion between from and to is ignored.
  311. func (c *Converter) RegisterIgnoredConversion(from, to interface{}) error {
  312. typeFrom := reflect.TypeOf(from)
  313. typeTo := reflect.TypeOf(to)
  314. if reflect.TypeOf(from).Kind() != reflect.Ptr {
  315. return fmt.Errorf("expected pointer arg for 'from' param 0, got: %v", typeFrom)
  316. }
  317. if typeTo.Kind() != reflect.Ptr {
  318. return fmt.Errorf("expected pointer arg for 'to' param 1, got: %v", typeTo)
  319. }
  320. c.ignoredConversions[typePair{typeFrom.Elem(), typeTo.Elem()}] = struct{}{}
  321. return nil
  322. }
  323. // IsConversionIgnored returns true if the specified objects should be dropped during
  324. // conversion.
  325. func (c *Converter) IsConversionIgnored(inType, outType reflect.Type) bool {
  326. _, found := c.ignoredConversions[typePair{inType, outType}]
  327. return found
  328. }
  329. func (c *Converter) HasConversionFunc(inType, outType reflect.Type) bool {
  330. _, found := c.conversionFuncs.fns[typePair{inType, outType}]
  331. return found
  332. }
  333. func (c *Converter) ConversionFuncValue(inType, outType reflect.Type) (reflect.Value, bool) {
  334. value, found := c.conversionFuncs.fns[typePair{inType, outType}]
  335. return value, found
  336. }
  337. // SetStructFieldCopy registers a correspondence. Whenever a struct field is encountered
  338. // which has a type and name matching srcFieldType and srcFieldName, it wil be copied
  339. // into the field in the destination struct matching destFieldType & Name, if such a
  340. // field exists.
  341. // May be called multiple times, even for the same source field & type--all applicable
  342. // copies will be performed.
  343. func (c *Converter) SetStructFieldCopy(srcFieldType interface{}, srcFieldName string, destFieldType interface{}, destFieldName string) error {
  344. st := reflect.TypeOf(srcFieldType)
  345. dt := reflect.TypeOf(destFieldType)
  346. srcKey := typeNamePair{st, srcFieldName}
  347. destKey := typeNamePair{dt, destFieldName}
  348. c.structFieldDests[srcKey] = append(c.structFieldDests[srcKey], destKey)
  349. c.structFieldSources[destKey] = append(c.structFieldSources[destKey], srcKey)
  350. return nil
  351. }
  352. // RegisterInputDefaults registers a field name mapping function, used when converting
  353. // from maps to structs. Inputs to the conversion methods are checked for this type and a mapping
  354. // applied automatically if the input matches in. A set of default flags for the input conversion
  355. // may also be provided, which will be used when no explicit flags are requested.
  356. func (c *Converter) RegisterInputDefaults(in interface{}, fn FieldMappingFunc, defaultFlags FieldMatchingFlags) error {
  357. fv := reflect.ValueOf(in)
  358. ft := fv.Type()
  359. if ft.Kind() != reflect.Ptr {
  360. return fmt.Errorf("expected pointer 'in' argument, got: %v", ft)
  361. }
  362. c.inputFieldMappingFuncs[ft] = fn
  363. c.inputDefaultFlags[ft] = defaultFlags
  364. return nil
  365. }
  366. // FieldMatchingFlags contains a list of ways in which struct fields could be
  367. // copied. These constants may be | combined.
  368. type FieldMatchingFlags int
  369. const (
  370. // Loop through destination fields, search for matching source
  371. // field to copy it from. Source fields with no corresponding
  372. // destination field will be ignored. If SourceToDest is
  373. // specified, this flag is ignored. If neither is specified,
  374. // or no flags are passed, this flag is the default.
  375. DestFromSource FieldMatchingFlags = 0
  376. // Loop through source fields, search for matching dest field
  377. // to copy it into. Destination fields with no corresponding
  378. // source field will be ignored.
  379. SourceToDest FieldMatchingFlags = 1 << iota
  380. // Don't treat it as an error if the corresponding source or
  381. // dest field can't be found.
  382. IgnoreMissingFields
  383. // Don't require type names to match.
  384. AllowDifferentFieldTypeNames
  385. )
  386. // IsSet returns true if the given flag or combination of flags is set.
  387. func (f FieldMatchingFlags) IsSet(flag FieldMatchingFlags) bool {
  388. if flag == DestFromSource {
  389. // The bit logic doesn't work on the default value.
  390. return f&SourceToDest != SourceToDest
  391. }
  392. return f&flag == flag
  393. }
  394. // Convert will translate src to dest if it knows how. Both must be pointers.
  395. // If no conversion func is registered and the default copying mechanism
  396. // doesn't work on this type pair, an error will be returned.
  397. // Read the comments on the various FieldMatchingFlags constants to understand
  398. // what the 'flags' parameter does.
  399. // 'meta' is given to allow you to pass information to conversion functions,
  400. // it is not used by Convert() other than storing it in the scope.
  401. // Not safe for objects with cyclic references!
  402. func (c *Converter) Convert(src, dest interface{}, flags FieldMatchingFlags, meta *Meta) error {
  403. if len(c.genericConversions) > 0 {
  404. // TODO: avoid scope allocation
  405. s := &scope{converter: c, flags: flags, meta: meta}
  406. for _, fn := range c.genericConversions {
  407. if ok, err := fn(src, dest, s); ok {
  408. return err
  409. }
  410. }
  411. }
  412. return c.doConversion(src, dest, flags, meta, c.convert)
  413. }
  414. // DefaultConvert will translate src to dest if it knows how. Both must be pointers.
  415. // No conversion func is used. If the default copying mechanism
  416. // doesn't work on this type pair, an error will be returned.
  417. // Read the comments on the various FieldMatchingFlags constants to understand
  418. // what the 'flags' parameter does.
  419. // 'meta' is given to allow you to pass information to conversion functions,
  420. // it is not used by DefaultConvert() other than storing it in the scope.
  421. // Not safe for objects with cyclic references!
  422. func (c *Converter) DefaultConvert(src, dest interface{}, flags FieldMatchingFlags, meta *Meta) error {
  423. return c.doConversion(src, dest, flags, meta, c.defaultConvert)
  424. }
  425. type conversionFunc func(sv, dv reflect.Value, scope *scope) error
  426. func (c *Converter) doConversion(src, dest interface{}, flags FieldMatchingFlags, meta *Meta, f conversionFunc) error {
  427. dv, err := EnforcePtr(dest)
  428. if err != nil {
  429. return err
  430. }
  431. if !dv.CanAddr() && !dv.CanSet() {
  432. return fmt.Errorf("can't write to dest")
  433. }
  434. sv, err := EnforcePtr(src)
  435. if err != nil {
  436. return err
  437. }
  438. s := &scope{
  439. converter: c,
  440. flags: flags,
  441. meta: meta,
  442. }
  443. // Leave something on the stack, so that calls to struct tag getters never fail.
  444. s.srcStack.push(scopeStackElem{})
  445. s.destStack.push(scopeStackElem{})
  446. return f(sv, dv, s)
  447. }
  448. // callCustom calls 'custom' with sv & dv. custom must be a conversion function.
  449. func (c *Converter) callCustom(sv, dv, custom reflect.Value, scope *scope) error {
  450. if !sv.CanAddr() {
  451. sv2 := reflect.New(sv.Type())
  452. sv2.Elem().Set(sv)
  453. sv = sv2
  454. } else {
  455. sv = sv.Addr()
  456. }
  457. if !dv.CanAddr() {
  458. if !dv.CanSet() {
  459. return scope.errorf("can't addr or set dest.")
  460. }
  461. dvOrig := dv
  462. dv := reflect.New(dvOrig.Type())
  463. defer func() { dvOrig.Set(dv) }()
  464. } else {
  465. dv = dv.Addr()
  466. }
  467. args := []reflect.Value{sv, dv, reflect.ValueOf(scope)}
  468. ret := custom.Call(args)[0].Interface()
  469. // This convolution is necessary because nil interfaces won't convert
  470. // to errors.
  471. if ret == nil {
  472. return nil
  473. }
  474. return ret.(error)
  475. }
  476. // convert recursively copies sv into dv, calling an appropriate conversion function if
  477. // one is registered.
  478. func (c *Converter) convert(sv, dv reflect.Value, scope *scope) error {
  479. dt, st := dv.Type(), sv.Type()
  480. pair := typePair{st, dt}
  481. // ignore conversions of this type
  482. if _, ok := c.ignoredConversions[pair]; ok {
  483. if c.Debug != nil {
  484. c.Debug.Logf("Ignoring conversion of '%v' to '%v'", st, dt)
  485. }
  486. return nil
  487. }
  488. // Convert sv to dv.
  489. if fv, ok := c.conversionFuncs.fns[pair]; ok {
  490. if c.Debug != nil {
  491. c.Debug.Logf("Calling custom conversion of '%v' to '%v'", st, dt)
  492. }
  493. return c.callCustom(sv, dv, fv, scope)
  494. }
  495. if fv, ok := c.generatedConversionFuncs.fns[pair]; ok {
  496. if c.Debug != nil {
  497. c.Debug.Logf("Calling generated conversion of '%v' to '%v'", st, dt)
  498. }
  499. return c.callCustom(sv, dv, fv, scope)
  500. }
  501. return c.defaultConvert(sv, dv, scope)
  502. }
  503. // defaultConvert recursively copies sv into dv. no conversion function is called
  504. // for the current stack frame (but conversion functions may be called for nested objects)
  505. func (c *Converter) defaultConvert(sv, dv reflect.Value, scope *scope) error {
  506. dt, st := dv.Type(), sv.Type()
  507. if !dv.CanSet() {
  508. return scope.errorf("Cannot set dest. (Tried to deep copy something with unexported fields?)")
  509. }
  510. if !scope.flags.IsSet(AllowDifferentFieldTypeNames) && c.nameFunc(dt) != c.nameFunc(st) {
  511. return scope.errorf(
  512. "type names don't match (%v, %v), and no conversion 'func (%v, %v) error' registered.",
  513. c.nameFunc(st), c.nameFunc(dt), st, dt)
  514. }
  515. switch st.Kind() {
  516. case reflect.Map, reflect.Ptr, reflect.Slice, reflect.Interface, reflect.Struct:
  517. // Don't copy these via assignment/conversion!
  518. default:
  519. // This should handle all simple types.
  520. if st.AssignableTo(dt) {
  521. dv.Set(sv)
  522. return nil
  523. }
  524. if st.ConvertibleTo(dt) {
  525. dv.Set(sv.Convert(dt))
  526. return nil
  527. }
  528. }
  529. if c.Debug != nil {
  530. c.Debug.Logf("Trying to convert '%v' to '%v'", st, dt)
  531. }
  532. scope.srcStack.push(scopeStackElem{value: sv})
  533. scope.destStack.push(scopeStackElem{value: dv})
  534. defer scope.srcStack.pop()
  535. defer scope.destStack.pop()
  536. switch dv.Kind() {
  537. case reflect.Struct:
  538. return c.convertKV(toKVValue(sv), toKVValue(dv), scope)
  539. case reflect.Slice:
  540. if sv.IsNil() {
  541. // Don't make a zero-length slice.
  542. dv.Set(reflect.Zero(dt))
  543. return nil
  544. }
  545. dv.Set(reflect.MakeSlice(dt, sv.Len(), sv.Cap()))
  546. for i := 0; i < sv.Len(); i++ {
  547. scope.setIndices(i, i)
  548. if err := c.convert(sv.Index(i), dv.Index(i), scope); err != nil {
  549. return err
  550. }
  551. }
  552. case reflect.Ptr:
  553. if sv.IsNil() {
  554. // Don't copy a nil ptr!
  555. dv.Set(reflect.Zero(dt))
  556. return nil
  557. }
  558. dv.Set(reflect.New(dt.Elem()))
  559. switch st.Kind() {
  560. case reflect.Ptr, reflect.Interface:
  561. return c.convert(sv.Elem(), dv.Elem(), scope)
  562. default:
  563. return c.convert(sv, dv.Elem(), scope)
  564. }
  565. case reflect.Map:
  566. if sv.IsNil() {
  567. // Don't copy a nil ptr!
  568. dv.Set(reflect.Zero(dt))
  569. return nil
  570. }
  571. dv.Set(reflect.MakeMap(dt))
  572. for _, sk := range sv.MapKeys() {
  573. dk := reflect.New(dt.Key()).Elem()
  574. if err := c.convert(sk, dk, scope); err != nil {
  575. return err
  576. }
  577. dkv := reflect.New(dt.Elem()).Elem()
  578. scope.setKeys(sk.Interface(), dk.Interface())
  579. // TODO: sv.MapIndex(sk) may return a value with CanAddr() == false,
  580. // because a map[string]struct{} does not allow a pointer reference.
  581. // Calling a custom conversion function defined for the map value
  582. // will panic. Example is PodInfo map[string]ContainerStatus.
  583. if err := c.convert(sv.MapIndex(sk), dkv, scope); err != nil {
  584. return err
  585. }
  586. dv.SetMapIndex(dk, dkv)
  587. }
  588. case reflect.Interface:
  589. if sv.IsNil() {
  590. // Don't copy a nil interface!
  591. dv.Set(reflect.Zero(dt))
  592. return nil
  593. }
  594. tmpdv := reflect.New(sv.Elem().Type()).Elem()
  595. if err := c.convert(sv.Elem(), tmpdv, scope); err != nil {
  596. return err
  597. }
  598. dv.Set(reflect.ValueOf(tmpdv.Interface()))
  599. return nil
  600. default:
  601. return scope.errorf("couldn't copy '%v' into '%v'; didn't understand types", st, dt)
  602. }
  603. return nil
  604. }
  605. var stringType = reflect.TypeOf("")
  606. func toKVValue(v reflect.Value) kvValue {
  607. switch v.Kind() {
  608. case reflect.Struct:
  609. return structAdaptor(v)
  610. case reflect.Map:
  611. if v.Type().Key().AssignableTo(stringType) {
  612. return stringMapAdaptor(v)
  613. }
  614. }
  615. return nil
  616. }
  617. // kvValue lets us write the same conversion logic to work with both maps
  618. // and structs. Only maps with string keys make sense for this.
  619. type kvValue interface {
  620. // returns all keys, as a []string.
  621. keys() []string
  622. // Will just return "" for maps.
  623. tagOf(key string) reflect.StructTag
  624. // Will return the zero Value if the key doesn't exist.
  625. value(key string) reflect.Value
  626. // Maps require explicit setting-- will do nothing for structs.
  627. // Returns false on failure.
  628. confirmSet(key string, v reflect.Value) bool
  629. }
  630. type stringMapAdaptor reflect.Value
  631. func (a stringMapAdaptor) len() int {
  632. return reflect.Value(a).Len()
  633. }
  634. func (a stringMapAdaptor) keys() []string {
  635. v := reflect.Value(a)
  636. keys := make([]string, v.Len())
  637. for i, v := range v.MapKeys() {
  638. if v.IsNil() {
  639. continue
  640. }
  641. switch t := v.Interface().(type) {
  642. case string:
  643. keys[i] = t
  644. }
  645. }
  646. return keys
  647. }
  648. func (a stringMapAdaptor) tagOf(key string) reflect.StructTag {
  649. return ""
  650. }
  651. func (a stringMapAdaptor) value(key string) reflect.Value {
  652. return reflect.Value(a).MapIndex(reflect.ValueOf(key))
  653. }
  654. func (a stringMapAdaptor) confirmSet(key string, v reflect.Value) bool {
  655. return true
  656. }
  657. type structAdaptor reflect.Value
  658. func (a structAdaptor) len() int {
  659. v := reflect.Value(a)
  660. return v.Type().NumField()
  661. }
  662. func (a structAdaptor) keys() []string {
  663. v := reflect.Value(a)
  664. t := v.Type()
  665. keys := make([]string, t.NumField())
  666. for i := range keys {
  667. keys[i] = t.Field(i).Name
  668. }
  669. return keys
  670. }
  671. func (a structAdaptor) tagOf(key string) reflect.StructTag {
  672. v := reflect.Value(a)
  673. field, ok := v.Type().FieldByName(key)
  674. if ok {
  675. return field.Tag
  676. }
  677. return ""
  678. }
  679. func (a structAdaptor) value(key string) reflect.Value {
  680. v := reflect.Value(a)
  681. return v.FieldByName(key)
  682. }
  683. func (a structAdaptor) confirmSet(key string, v reflect.Value) bool {
  684. return true
  685. }
  686. // convertKV can convert things that consist of key/value pairs, like structs
  687. // and some maps.
  688. func (c *Converter) convertKV(skv, dkv kvValue, scope *scope) error {
  689. if skv == nil || dkv == nil {
  690. // TODO: add keys to stack to support really understandable error messages.
  691. return fmt.Errorf("Unable to convert %#v to %#v", skv, dkv)
  692. }
  693. lister := dkv
  694. if scope.flags.IsSet(SourceToDest) {
  695. lister = skv
  696. }
  697. var mapping FieldMappingFunc
  698. if scope.meta != nil && scope.meta.KeyNameMapping != nil {
  699. mapping = scope.meta.KeyNameMapping
  700. }
  701. for _, key := range lister.keys() {
  702. if found, err := c.checkField(key, skv, dkv, scope); found {
  703. if err != nil {
  704. return err
  705. }
  706. continue
  707. }
  708. stag := skv.tagOf(key)
  709. dtag := dkv.tagOf(key)
  710. skey := key
  711. dkey := key
  712. if mapping != nil {
  713. skey, dkey = scope.meta.KeyNameMapping(key, stag, dtag)
  714. }
  715. df := dkv.value(dkey)
  716. sf := skv.value(skey)
  717. if !df.IsValid() || !sf.IsValid() {
  718. switch {
  719. case scope.flags.IsSet(IgnoreMissingFields):
  720. // No error.
  721. case scope.flags.IsSet(SourceToDest):
  722. return scope.errorf("%v not present in dest", dkey)
  723. default:
  724. return scope.errorf("%v not present in src", skey)
  725. }
  726. continue
  727. }
  728. scope.srcStack.top().key = skey
  729. scope.srcStack.top().tag = stag
  730. scope.destStack.top().key = dkey
  731. scope.destStack.top().tag = dtag
  732. if err := c.convert(sf, df, scope); err != nil {
  733. return err
  734. }
  735. }
  736. return nil
  737. }
  738. // checkField returns true if the field name matches any of the struct
  739. // field copying rules. The error should be ignored if it returns false.
  740. func (c *Converter) checkField(fieldName string, skv, dkv kvValue, scope *scope) (bool, error) {
  741. replacementMade := false
  742. if scope.flags.IsSet(DestFromSource) {
  743. df := dkv.value(fieldName)
  744. if !df.IsValid() {
  745. return false, nil
  746. }
  747. destKey := typeNamePair{df.Type(), fieldName}
  748. // Check each of the potential source (type, name) pairs to see if they're
  749. // present in sv.
  750. for _, potentialSourceKey := range c.structFieldSources[destKey] {
  751. sf := skv.value(potentialSourceKey.fieldName)
  752. if !sf.IsValid() {
  753. continue
  754. }
  755. if sf.Type() == potentialSourceKey.fieldType {
  756. // Both the source's name and type matched, so copy.
  757. scope.srcStack.top().key = potentialSourceKey.fieldName
  758. scope.destStack.top().key = fieldName
  759. if err := c.convert(sf, df, scope); err != nil {
  760. return true, err
  761. }
  762. dkv.confirmSet(fieldName, df)
  763. replacementMade = true
  764. }
  765. }
  766. return replacementMade, nil
  767. }
  768. sf := skv.value(fieldName)
  769. if !sf.IsValid() {
  770. return false, nil
  771. }
  772. srcKey := typeNamePair{sf.Type(), fieldName}
  773. // Check each of the potential dest (type, name) pairs to see if they're
  774. // present in dv.
  775. for _, potentialDestKey := range c.structFieldDests[srcKey] {
  776. df := dkv.value(potentialDestKey.fieldName)
  777. if !df.IsValid() {
  778. continue
  779. }
  780. if df.Type() == potentialDestKey.fieldType {
  781. // Both the dest's name and type matched, so copy.
  782. scope.srcStack.top().key = fieldName
  783. scope.destStack.top().key = potentialDestKey.fieldName
  784. if err := c.convert(sf, df, scope); err != nil {
  785. return true, err
  786. }
  787. dkv.confirmSet(potentialDestKey.fieldName, df)
  788. replacementMade = true
  789. }
  790. }
  791. return replacementMade, nil
  792. }