Пример #1
0
// EncodeToStream does not do conversion. It sets the gvk during serialization. overrides are ignored.
func (c DirectCodec) Encode(obj runtime.Object, stream io.Writer) error {
	gvks, _, err := c.ObjectTyper.ObjectKinds(obj)
	if err != nil {
		return err
	}
	kind := obj.GetObjectKind()
	oldGVK := kind.GroupVersionKind()
	kind.SetGroupVersionKind(gvks[0])
	err = c.Serializer.Encode(obj, stream)
	kind.SetGroupVersionKind(oldGVK)
	return err
}
Пример #2
0
// Encode ensures the provided object is output in the appropriate group and version, invoking
// conversion if necessary. Unversioned objects (according to the ObjectTyper) are output as is.
func (c *codec) Encode(obj runtime.Object, w io.Writer) error {
	if _, ok := obj.(*runtime.Unknown); ok {
		return c.encoder.Encode(obj, w)
	}
	gvks, isUnversioned, err := c.typer.ObjectKinds(obj)
	if err != nil {
		return err
	}
	gvk := gvks[0]

	if c.encodeVersion == nil || isUnversioned {
		objectKind := obj.GetObjectKind()
		old := objectKind.GroupVersionKind()
		objectKind.SetGroupVersionKind(gvk)
		err = c.encoder.Encode(obj, w)
		objectKind.SetGroupVersionKind(old)
		return err
	}

	targetGV, ok := c.encodeVersion[gvk.Group]

	// attempt a conversion to the sole encode version
	if !ok && c.preferredEncodeVersion != nil {
		ok = true
		targetGV = c.preferredEncodeVersion[0]
	}

	// if no fallback is available, error
	if !ok {
		return fmt.Errorf("the codec does not recognize group %q for kind %q and cannot encode it", gvk.Group, gvk.Kind)
	}

	// Perform a conversion if necessary
	objectKind := obj.GetObjectKind()
	old := objectKind.GroupVersionKind()
	out, err := c.convertor.ConvertToVersion(obj, targetGV)
	if err != nil {
		if ok {
			return err
		}
	} else {
		obj = out
	}
	// Conversion is responsible for setting the proper group, version, and kind onto the outgoing object
	err = c.encoder.Encode(obj, w)
	// restore the old GVK, in case conversion returned the same object
	objectKind.SetGroupVersionKind(old)
	return err
}