Пример #1
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 {
	switch t := obj.(type) {
	case *runtime.Unknown:
		if gv, ok := runtime.PreferredGroupVersion(c.encodeVersion); ok {
			t.APIVersion = gv.String()
		}
		return c.encoder.Encode(obj, w)
	case *runtime.Unstructured:
		if gv, ok := runtime.PreferredGroupVersion(c.encodeVersion); ok {
			t.SetAPIVersion(gv.String())
		}
		return c.encoder.Encode(obj, w)
	case *runtime.UnstructuredList:
		if gv, ok := runtime.PreferredGroupVersion(c.encodeVersion); ok {
			t.SetAPIVersion(gv.String())
		}
		return c.encoder.Encode(obj, w)
	}

	gvks, isUnversioned, err := c.typer.ObjectKinds(obj)
	if err != nil {
		return err
	}

	if c.encodeVersion == nil || isUnversioned {
		if e, ok := obj.(runtime.NestedObjectEncoder); ok {
			if err := e.EncodeNestedObjects(DirectEncoder{Encoder: c.encoder, ObjectTyper: c.typer}); err != nil {
				return err
			}
		}
		objectKind := obj.GetObjectKind()
		old := objectKind.GroupVersionKind()
		objectKind.SetGroupVersionKind(gvks[0])
		err = c.encoder.Encode(obj, w)
		objectKind.SetGroupVersionKind(old)
		return err
	}

	// Perform a conversion if necessary
	objectKind := obj.GetObjectKind()
	old := objectKind.GroupVersionKind()
	out, err := c.convertor.ConvertToVersion(obj, c.encodeVersion)
	if err != nil {
		return err
	}

	if e, ok := obj.(runtime.NestedObjectEncoder); ok {
		if err := e.EncodeNestedObjects(DirectEncoder{Encoder: c.encoder, ObjectTyper: c.typer}); err != nil {
			return err
		}
	}

	// Conversion is responsible for setting the proper group, version, and kind onto the outgoing object
	err = c.encoder.Encode(out, w)
	// restore the old GVK, in case conversion returned the same object
	objectKind.SetGroupVersionKind(old)
	return err
}
Пример #2
0
func (t *thirdPartyResourceDataCodecFactory) EncoderForVersion(s runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder {
	if target, ok := runtime.PreferredGroupVersion(gv); ok {
		return &thirdPartyResourceDataEncoder{delegate: t.delegate.EncoderForVersion(s, gv), gvk: target.WithKind(t.kind)}
	}
	return &thirdPartyResourceDataEncoder{delegate: t.delegate.EncoderForVersion(s, gv)}
}