// ConvertToVersion converts an unstructured object into the specified group/version
165614
func (k KubectlCmd) ConvertToVersion(obj *unstructured.Unstructured, group string, version string) (*unstructured.Unstructured, error) {
	gvk := obj.GroupVersionKind()
	if gvk.Group == group && gvk.Version == version {
		return obj.DeepCopy(), nil
	}
	newGroup, isObsoleteKind := obsoleteExtensionsKinds[gvk.Kind]

	// If converting from or to obsolete kind from 'extensions' group when just replace group, version, kind without real conversion.
	if gvk.Group == "extensions" && isObsoleteKind || isObsoleteKind && group == "extensions" && newGroup == gvk.Group {
		converted := obj.DeepCopy()
		converted.SetGroupVersionKind(schema.GroupVersionKind{
			Kind:    gvk.Kind,
			Group:   group,
			Version: version,
		})
		return converted, nil
	}

	manifestBytes, err := json.Marshal(obj)
	if err != nil {
		return nil, err
	}
	f, err := ioutil.TempFile(util.TempDir, "")
	if err != nil {
		return nil, fmt.Errorf("Failed to generate temp file for kubectl: %v", err)
	}
	_ = f.Close()
	if err := ioutil.WriteFile(f.Name(), manifestBytes, 0600); err != nil {
		return nil, err
	}
	defer util.DeleteFile(f.Name())
	outputVersion := fmt.Sprintf("%s/%s", group, version)
	cmd := exec.Command("kubectl", "convert", "--output-version", outputVersion, "-o", "json", "--local=true", "-f", f.Name())
	cmd.Stdin = bytes.NewReader(manifestBytes)
	out, err := cmd.Output()
	if err != nil {
		if exErr, ok := err.(*exec.ExitError); ok {
			errMsg := cleanKubectlOutput(string(exErr.Stderr))
			return nil, errors.New(errMsg)
		}
		return nil, fmt.Errorf("failed to convert %s/%s to %s/%s", obj.GetKind(), obj.GetName(), group, version)
	}
	// NOTE: when kubectl convert runs against stdin (i.e. kubectl convert -f -), the output is
	// a unstructured list instead of an unstructured object
	var convertedObj unstructured.Unstructured
	err = json.Unmarshal(out, &convertedObj)
	if err != nil {
		return nil, err
	}
	if convertedObj.GetNamespace() == "" {
		convertedObj.SetNamespace(obj.GetNamespace())
	}
	return &convertedObj, nil
}
259513
func convertInstanceToRunningService(inst service.Instance) dao.RunningService {
	return dao.RunningService{
		ID:            fmt.Sprintf("%s-%s-%d", inst.HostID, inst.ServiceID, inst.InstanceID),
		ServiceID:     inst.ServiceID,
		HostID:        inst.HostID,
		DockerID:      inst.ContainerID,
		StartedAt:     inst.Started,
		InSync:        inst.ImageSynced,
		Name:          inst.ServiceName,
		DesiredState:  int(inst.DesiredState),
		RAMCommitment: utils.NewEngNotation(inst.RAMCommitment),
		RAMThreshold:  inst.RAMThreshold,
		InstanceID:    inst.InstanceID,
	}
}
733389
func convertToVolumeInfo(all []params.VolumeDetails) (map[string]VolumeInfo, error) {
	result := make(map[string]VolumeInfo)
	for _, one := range all {
		volumeTag, info, err := createVolumeInfo(one)
		if err != nil {
			return nil, errors.Trace(err)
		}
		result[volumeTag.Id()] = info
	}
	return result, nil
}
666788
func (c *Conversation) commitToVersionFrom(versions int) error {
	if c.version != nil {
		return nil
	}

	var version otrVersion

	switch {
	case c.Policies.has(allowV3) && versions&(1<<3) > 0:
		version = otrV3{}
	case c.Policies.has(allowV2) && versions&(1<<2) > 0:
		version = otrV2{}
	default:
		return errUnsupportedOTRVersion
	}

	c.version = version

	return c.setKeyMatchingVersion()
}
316168
func ToVersionedYamlWithVersion(obj runtime.Object, version runtime.GroupVersioner) ([]byte, error) {
	var w bytes.Buffer
	err := encoder(version, "application/yaml").Encode(obj, &w)
	if err != nil {
		return nil, fmt.Errorf("error encoding %T: %v", obj, err)
	}
	return w.Bytes(), nil
}
110853
func (m *MockConfig) UpgradedToVersion() version.Number {
	ret := m.ctrl.Call(m, "UpgradedToVersion")
	ret0, _ := ret[0].(version.Number)
	return ret0
}
194013
func convertStructContainerReservation(in *ContainerReservation) *proto.ContainerReservation {
	if in == nil {
		return nil
	}

	return &proto.ContainerReservation{
		Envs:    in.Envs,
		Mounts:  convertStructMounts(in.Mounts),
		Devices: convertStructDeviceSpecs(in.Devices),
	}
}
844406
func NewVersionConverter(t TypeConverter, o runtime.ObjectConvertor, h schema.GroupVersion) merge.Converter {
	return &versionConverter{
		typeConverter:   t,
		objectConvertor: o,
		hubGetter: func(from schema.GroupVersion) schema.GroupVersion {
			return schema.GroupVersion{
				Group:   from.Group,
				Version: h.Version,
			}
		},
	}
}
484285
func convertProtoDeviceGroupStats(in *proto.DeviceGroupStats) *DeviceGroupStats {
	if in == nil {
		return nil
	}

	out := &DeviceGroupStats{
		Vendor:        in.Vendor,
		Type:          in.Type,
		Name:          in.Name,
		InstanceStats: make(map[string]*DeviceStats, len(in.InstanceStats)),
	}

	for k, v := range in.InstanceStats {
		out.InstanceStats[k] = convertProtoDeviceStats(v)
	}

	return out
}
739784
func (inv *JoinOrganizationInvitation) ConvertToView(usrMgr *user.Manager, valMgr *validation.Manager) (*JoinOrganizationInvitationView, error) {
	vw := &JoinOrganizationInvitationView{}
	vw.Organization = inv.Organization
	vw.Role = inv.Role
	vw.Status = inv.Status
	vw.Created = inv.Created
	vw.Method = inv.Method
	vw.EmailAddress = inv.EmailAddress
	vw.PhoneNumber = inv.PhoneNumber
	vw.IsOrganization = inv.IsOrganization

	var err error
	vw.User, err = organization.ConvertUsernameToIdentifier(inv.User, usrMgr, valMgr)
	// user can be empty if invited through email or phone number
	if db.IsNotFound(err) {
		err = nil
	}
	return vw, err
}
269699
func (c *unstructuredConverter) ToUnstructured(obj interface{}) (map[string]interface{}, error) {
	var u map[string]interface{}
	var err error
	if unstr, ok := obj.(Unstructured); ok {
		u = unstr.UnstructuredContent()
	} else {
		t := reflect.TypeOf(obj)
		value := reflect.ValueOf(obj)
		if t.Kind() != reflect.Ptr || value.IsNil() {
			return nil, fmt.Errorf("ToUnstructured requires a non-nil pointer to an object, got %v", t)
		}
		u = map[string]interface{}{}
		err = toUnstructured(value.Elem(), reflect.ValueOf(&u).Elem())
	}
	if c.mismatchDetection {
		newUnstr := map[string]interface{}{}
		newErr := toUnstructuredViaJSON(obj, &newUnstr)
		if (err != nil) != (newErr != nil) {
			klog.Fatalf("ToUnstructured unexpected error for %v: error: %v; newErr: %v", obj, err, newErr)
		}
		if err == nil && !c.comparison.DeepEqual(u, newUnstr) {
			klog.Fatalf("ToUnstructured mismatch\nobj1: %#v\nobj2: %#v", u, newUnstr)
		}
	}
	if err != nil {
		return nil, err
	}
	return u, nil
}
1364390
func Convert(obj interface{}) (url.Values, error) {
	result := url.Values{}
	if obj == nil {
		return result, nil
	}
	var sv reflect.Value
	switch reflect.TypeOf(obj).Kind() {
	case reflect.Ptr, reflect.Interface:
		sv = reflect.ValueOf(obj).Elem()
	default:
		return nil, fmt.Errorf("expecting a pointer or interface")
	}
	st := sv.Type()
	if !isStructKind(st.Kind()) {
		return nil, fmt.Errorf("expecting a pointer to a struct")
	}

	// Check all object fields
	convertStruct(result, st, sv)

	return result, nil
}
559833
func tryConvert(convertor runtime.ObjectConvertor, object runtime.Object, versions ...string) (runtime.Object, error) {
	var last error
	for _, version := range versions {
		if len(version) == 0 {
			return object, nil
		}
		obj, err := convertor.ConvertToVersion(object, version)
		if err != nil {
			last = err
			continue
		}
		return obj, nil
	}
	return nil, last
}
675299
func ConvertType(scheme *runtime.Scheme, in, out runtime.Object) error {
	in = in.DeepCopyObject()
	if err := scheme.Convert(in, out, nil); err != nil {
		return err
	}
	gvkOut := out.GetObjectKind().GroupVersionKind()
	if gvkOut.Kind == "" || gvkOut.Version == "" { // Group can be empty
		// API machinery discards TypeMeta for typed objects. This is annoying.
		gvks, _, err := scheme.ObjectKinds(in)
		if err != nil {
			return err
		}
		out.GetObjectKind().SetGroupVersionKind(gvks[0])
	}
	return nil
}
1013544
func (converter MarkupConverter) Convert(value interface{}, item AttributeAccessor) (interface{}, error) {
	// return a 'nil' result if the supplied 'value' was nil
	if value == nil {
		return nil, nil
	}
	switch value.(type) {
	case string:
		return rendering.NewMarkupContent(value.(string), converter.markup), nil
	default:
		return nil, errors.Errorf("Unexpected type of value to convert: %T", value)
	}
}
965768
func (c *Converter) Convert(ctx context.Context, opts ...ConvertOpt) (ocispec.Descriptor, error) {
	co := ConvertOptions{
		ManifestMediaType: ocispec.MediaTypeImageManifest,
		ConfigMediaType:   ocispec.MediaTypeImageConfig,
	}
	for _, opt := range opts {
		if err := opt(ctx, &co); err != nil {
			return ocispec.Descriptor{}, err
		}
	}

	history, diffIDs, err := c.schema1ManifestHistory()
	if err != nil {
		return ocispec.Descriptor{}, errors.Wrap(err, "schema 1 conversion failed")
	}

	var img ocispec.Image
	if err := json.Unmarshal([]byte(c.pulledManifest.History[0].V1Compatibility), &img); err != nil {
		return ocispec.Descriptor{}, errors.Wrap(err, "failed to unmarshal image from schema 1 history")
	}

	img.History = history
	img.RootFS = ocispec.RootFS{
		Type:    "layers",
		DiffIDs: diffIDs,
	}

	b, err := json.MarshalIndent(img, "", "   ")
	if err != nil {
		return ocispec.Descriptor{}, errors.Wrap(err, "failed to marshal image")
	}

	config := ocispec.Descriptor{
		MediaType: co.ConfigMediaType,
		Digest:    digest.Canonical.FromBytes(b),
		Size:      int64(len(b)),
	}

	layers := make([]ocispec.Descriptor, len(diffIDs))
	for i, diffID := range diffIDs {
		layers[i] = c.layerBlobs[diffID]
	}

	manifest := ocispec.Manifest{
		Versioned: specs.Versioned{
			SchemaVersion: 2,
		},
		Config: config,
		Layers: layers,
	}

	mb, err := json.MarshalIndent(manifest, "", "   ")
	if err != nil {
		return ocispec.Descriptor{}, errors.Wrap(err, "failed to marshal image")
	}

	desc := ocispec.Descriptor{
		MediaType: co.ManifestMediaType,
		Digest:    digest.Canonical.FromBytes(mb),
		Size:      int64(len(mb)),
	}

	labels := map[string]string{}
	labels["containerd.io/gc.ref.content.0"] = manifest.Config.Digest.String()
	for i, ch := range manifest.Layers {
		labels[fmt.Sprintf("containerd.io/gc.ref.content.%d", i+1)] = ch.Digest.String()
	}

	ref := remotes.MakeRefKey(ctx, desc)
	if err := content.WriteBlob(ctx, c.contentStore, ref, bytes.NewReader(mb), desc, content.WithLabels(labels)); err != nil {
		return ocispec.Descriptor{}, errors.Wrap(err, "failed to write config")
	}

	ref = remotes.MakeRefKey(ctx, config)
	if err := content.WriteBlob(ctx, c.contentStore, ref, bytes.NewReader(b), config); err != nil {
		return ocispec.Descriptor{}, errors.Wrap(err, "failed to write config")
	}

	return desc, nil
}
1335162
func (c *nopConverter) Convert(in runtime.Object, targetGV schema.GroupVersion) (runtime.Object, error) {
	// Run the converter on the list items instead of list itself
	if list, ok := in.(*unstructured.UnstructuredList); ok {
		for i := range list.Items {
			list.Items[i].SetGroupVersionKind(targetGV.WithKind(list.Items[i].GroupVersionKind().Kind))
		}
	}
	in.GetObjectKind().SetGroupVersionKind(targetGV.WithKind(in.GetObjectKind().GroupVersionKind().Kind))
	return in, nil
}