예제 #1
0
// DecodeToVersion converts a JSON string back into a pointer to an api object.
// Deduces the type based upon the fields added by the MetaInsertionFactory
// technique. The object will be converted, if necessary, into the versioned
// type before being returned. Decode will not decode objects without version
// set unless version is also "".
// a GroupVersion with .IsEmpty() == true is means "use the internal version for
// the object's group"
func (s *Scheme) DecodeToVersion(data []byte, targetVersion unversioned.GroupVersion) (interface{}, error) {
	obj, sourceKind, err := s.DecodeToVersionedObject(data)
	if err != nil {
		return nil, err
	}
	// Version and Kind should be blank in memory.
	if err := s.SetVersionAndKind("", "", obj); err != nil {
		return nil, err
	}

	// if the targetVersion is empty, then we want the internal version, but the internal version varies by
	// group.  We can lookup the group now because we have knowledge of the group
	if targetVersion.IsEmpty() {
		exists := false
		targetVersion, exists = s.InternalVersions[sourceKind.Group]
		if !exists {
			return nil, fmt.Errorf("no internalVersion specified for %v", targetVersion)
		}
	}

	// Convert if needed.
	if targetVersion != sourceKind.GroupVersion() {
		objOut, err := s.NewObject(targetVersion.WithKind(sourceKind.Kind))
		if err != nil {
			return nil, err
		}
		flags, meta := s.generateConvertMeta(sourceKind.GroupVersion(), targetVersion, obj)
		if err := s.converter.Convert(obj, objOut, flags, meta); err != nil {
			return nil, err
		}
		obj = objOut
	}
	return obj, nil
}
예제 #2
0
// AddKnownTypes registers all types passed in 'types' as being members of version 'version'.
// Encode() will refuse objects unless their type has been registered with AddKnownTypes.
// All objects passed to types should be pointers to structs. The name that go reports for
// the struct becomes the "kind" field when encoding.
func (s *Scheme) AddKnownTypes(gv unversioned.GroupVersion, types ...interface{}) {
	for _, obj := range types {
		t := reflect.TypeOf(obj)
		if t.Kind() != reflect.Ptr {
			panic("All types must be pointers to structs.")
		}
		t = t.Elem()
		if t.Kind() != reflect.Struct {
			panic("All types must be pointers to structs.")
		}

		gvk := gv.WithKind(t.Name())
		s.gvkToType[gvk] = t
		s.typeToGVK[t] = append(s.typeToGVK[t], gvk)
	}
}