当前位置: 首页>>代码示例>>Golang>>正文


Golang resource.AsVersionedObject函数代码示例

本文整理汇总了Golang中k8s/io/kubernetes/pkg/kubectl/resource.AsVersionedObject函数的典型用法代码示例。如果您正苦于以下问题:Golang AsVersionedObject函数的具体用法?Golang AsVersionedObject怎么用?Golang AsVersionedObject使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了AsVersionedObject函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: RunConvert

// RunConvert implements the generic Convert command
func (o *ConvertOptions) RunConvert() error {
	r := o.builder.Do()
	err := r.Err()
	if err != nil {
		return err
	}

	count := 0
	err = r.Visit(func(info *resource.Info, err error) error {
		if err != nil {
			return err
		}

		infos := []*resource.Info{info}
		objects, err := resource.AsVersionedObject(infos, false, o.outputVersion, o.encoder)
		if err != nil {
			return err
		}

		count++
		return o.printer.PrintObj(objects, o.out)
	})
	if err != nil {
		return err
	}
	if count == 0 {
		return fmt.Errorf("no objects passed to convert")
	}
	return nil
}
开发者ID:humblec,项目名称:kubernetes,代码行数:31,代码来源:convert.go

示例2: Run

// Run executes the BackendOptions or returns an error.
func (o *BackendsOptions) Run() error {
	infos := o.Infos
	singular := len(o.Infos) <= 1
	if o.Builder != nil {
		loaded, err := o.Builder.Do().IntoSingular(&singular).Infos()
		if err != nil {
			return err
		}
		infos = loaded
	}

	if o.PrintTable && o.PrintObject == nil {
		return o.printBackends(infos)
	}

	patches := CalculatePatches(infos, o.Encoder, func(info *resource.Info) (bool, error) {
		return UpdateBackendsForObject(info.Object, o.Transform.Apply)
	})
	if singular && len(patches) == 0 {
		return fmt.Errorf("%s/%s is not a deployment config or build config", infos[0].Mapping.Resource, infos[0].Name)
	}
	if o.PrintObject != nil {
		object, err := resource.AsVersionedObject(infos, !singular, o.OutputVersion, kapi.Codecs.LegacyCodec(o.OutputVersion))
		if err != nil {
			return err
		}
		return o.PrintObject(object)
	}

	failed := false
	for _, patch := range patches {
		info := patch.Info
		if patch.Err != nil {
			failed = true
			fmt.Fprintf(o.Err, "error: %s/%s %v\n", info.Mapping.Resource, info.Name, patch.Err)
			continue
		}

		if string(patch.Patch) == "{}" || len(patch.Patch) == 0 {
			fmt.Fprintf(o.Err, "info: %s %q was not changed\n", info.Mapping.Resource, info.Name)
			continue
		}

		glog.V(4).Infof("Calculated patch %s", patch.Patch)

		obj, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, kapi.StrategicMergePatchType, patch.Patch)
		if err != nil {
			handlePodUpdateError(o.Err, err, "altered")
			failed = true
			continue
		}

		info.Refresh(obj, true)
		kcmdutil.PrintSuccess(o.Mapper, o.ShortOutput, o.Out, info.Mapping.Resource, info.Name, false, "updated")
	}
	if failed {
		return cmdutil.ErrExit
	}
	return nil
}
开发者ID:juanluisvaladas,项目名称:origin,代码行数:61,代码来源:routebackends.go

示例3: applyPatch

// applyPatch reads the latest version of the object, writes it to version, then attempts to merge
// the changes onto it without conflict. If a conflict occurs jsonmerge.IsConflicting(err) is
// true. The info object is mutated
func applyPatch(delta *jsonmerge.Delta, info *resource.Info, version string) error {
	if err := info.Get(); err != nil {
		return patchError{err}
	}
	obj, err := resource.AsVersionedObject([]*resource.Info{info}, false, version)
	if err != nil {
		return patchError{err}
	}
	data, err := info.Mapping.Codec.Encode(obj)
	if err != nil {
		return patchError{err}
	}
	merged, err := delta.Apply(data)
	if err != nil {
		return patchError{err}
	}
	mergedObj, err := info.Mapping.Codec.Decode(merged)
	if err != nil {
		return patchError{err}
	}
	updated, err := resource.NewHelper(info.Client, info.Mapping).Replace(info.Namespace, info.Name, false, mergedObj)
	if err != nil {
		return err
	}
	info.Refresh(updated, true)
	return nil
}
开发者ID:erinboyd,项目名称:origin,代码行数:30,代码来源:edit.go

示例4: Run

func (o *DeploymentHookOptions) Run() error {
	infos := o.Infos
	singular := len(o.Infos) <= 1
	if o.Builder != nil {
		loaded, err := o.Builder.Do().IntoSingular(&singular).Infos()
		if err != nil {
			return err
		}
		infos = loaded
	}

	patches := CalculatePatches(infos, o.Encoder, func(info *resource.Info) (bool, error) {
		dc, ok := info.Object.(*deployapi.DeploymentConfig)
		if !ok {
			return false, nil
		}
		updated, err := o.updateDeploymentConfig(dc)
		return updated, err
	})

	if singular && len(patches) == 0 {
		return fmt.Errorf("%s/%s is not a deployment config or does not have an applicable strategy", infos[0].Mapping.Resource, infos[0].Name)
	}

	if o.PrintObject != nil {
		object, err := resource.AsVersionedObject(infos, !singular, o.OutputVersion, kapi.Codecs.LegacyCodec(o.OutputVersion))
		if err != nil {
			return err
		}
		return o.PrintObject(object)
	}

	failed := false
	for _, patch := range patches {
		info := patch.Info
		if patch.Err != nil {
			fmt.Fprintf(o.Err, "error: %s/%s %v\n", info.Mapping.Resource, info.Name, patch.Err)
			continue
		}

		if string(patch.Patch) == "{}" || len(patch.Patch) == 0 {
			fmt.Fprintf(o.Err, "info: %s %q was not changed\n", info.Mapping.Resource, info.Name)
			continue
		}

		obj, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, kapi.StrategicMergePatchType, patch.Patch)
		if err != nil {
			fmt.Fprintf(o.Err, "error: %v\n", err)
			failed = true
			continue
		}

		info.Refresh(obj, true)
		kcmdutil.PrintSuccess(o.Mapper, o.ShortOutput, o.Out, info.Mapping.Resource, info.Name, "updated")
	}
	if failed {
		return cmdutil.ErrExit
	}
	return nil
}
开发者ID:Xmagicer,项目名称:origin,代码行数:60,代码来源:deploymenthook.go

示例5: Run

func (o *BuildSecretOptions) Run() error {
	infos := o.Infos
	singular := len(o.Infos) <= 1
	if o.Builder != nil {
		loaded, err := o.Builder.Do().IntoSingular(&singular).Infos()
		if err != nil {
			return err
		}
		infos = loaded
	}

	patches := CalculatePatches(infos, o.Encoder, func(info *resource.Info) (bool, error) {
		return o.setBuildSecret(info.Object)
	})

	if singular && len(patches) == 0 {
		return fmt.Errorf("cannot set a build secret on %s/%s", infos[0].Mapping.Resource, infos[0].Name)
	}

	if o.PrintObject != nil {
		object, err := resource.AsVersionedObject(infos, !singular, o.OutputVersion, kapi.Codecs.LegacyCodec(o.OutputVersion))
		if err != nil {
			return err
		}
		return o.PrintObject(object)
	}

	errs := []error{}
	for _, patch := range patches {
		info := patch.Info
		if patch.Err != nil {
			errs = append(errs, fmt.Errorf("%s/%s %v", info.Mapping.Resource, info.Name, patch.Err))
			continue
		}

		if string(patch.Patch) == "{}" || len(patch.Patch) == 0 {
			fmt.Fprintf(o.Err, "info: %s %q was not changed\n", info.Mapping.Resource, info.Name)
			continue
		}

		obj, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, kapi.StrategicMergePatchType, patch.Patch)
		if err != nil {
			errs = append(errs, fmt.Errorf("%s/%s %v", info.Mapping.Resource, info.Name, err))
			continue
		}

		info.Refresh(obj, true)
		kcmdutil.PrintSuccess(o.Mapper, o.ShortOutput, o.Out, info.Mapping.Resource, info.Name, "updated")
	}
	if len(errs) > 0 {
		return errors.NewAggregate(errs)
	}
	return nil
}
开发者ID:mffiedler,项目名称:origin,代码行数:54,代码来源:buildsecret.go

示例6: RunConvert

// RunConvert implements the generic Convert command
func (o *ConvertOptions) RunConvert() error {
	infos, err := o.builder.Do().Infos()
	if err != nil {
		return err
	}

	objects, err := resource.AsVersionedObject(infos, false, o.outputVersion.String(), o.encoder)
	if err != nil {
		return err
	}

	return o.printer.PrintObj(objects, o.out)
}
开发者ID:lohmander,项目名称:dashboard,代码行数:14,代码来源:convert.go

示例7: getCurrentObject

func getCurrentObject(targetName string, infos []*resource.Info) (runtime.Object, error) {
	var curr *resource.Info
	for _, currInfo := range infos {
		if currInfo.Name == targetName {
			curr = currInfo
		}
	}

	if curr == nil {
		return nil, fmt.Errorf("No resource with the name %s found.", targetName)
	}

	encoder := api.Codecs.LegacyCodec(registered.EnabledVersions()...)
	defaultVersion := unversioned.GroupVersion{}
	return resource.AsVersionedObject([]*resource.Info{curr}, false, defaultVersion, encoder)
}
开发者ID:runseb,项目名称:helm,代码行数:16,代码来源:client.go

示例8: RunConvert

// RunConvert implements the generic Convert command
func (o *ConvertOptions) RunConvert() error {
	r := o.builder.Do()
	err := r.Err()
	if err != nil {
		return err
	}

	singular := false
	infos, err := r.IntoSingular(&singular).Infos()
	if err != nil {
		return err
	}

	if len(infos) == 0 {
		return fmt.Errorf("no objects passed to convert")
	}

	objects, err := resource.AsVersionedObject(infos, !singular, o.outputVersion, o.encoder)
	if err != nil {
		return err
	}

	if meta.IsListType(objects) {
		_, items, err := cmdutil.FilterResourceList(objects, nil, nil)
		if err != nil {
			return err
		}
		filteredObj, err := cmdutil.ObjectListToVersionedObject(items, o.outputVersion)
		if err != nil {
			return err
		}
		return o.printer.PrintObj(filteredObj, o.out)
	}

	return o.printer.PrintObj(objects, o.out)
}
开发者ID:nak3,项目名称:origin,代码行数:37,代码来源:convert.go

示例9: changeObjectsVersion

func changeObjectsVersion(items []kruntime.Object) {
	if errs := kruntime.DecodeList(items, api.Scheme); len(errs) > 0 {
		log.Fatalf("Unable to decode Template objects: %v", errs)
	}
	for i, obj := range items {
		_, kind, err := api.Scheme.ObjectVersionAndKind(obj)
		if err != nil {
			glog.Infof("Template.Objects[%d]: Unable to determine version and kind: %v", i, err)
			continue
		}
		mapping, err := latest.RESTMapper.RESTMapping(kind, *outputVersion)
		if err != nil {
			glog.Infof("Template.Objects[%d]: Unable to get REST mappings: %v", err)
			continue
		}
		info := resource.Info{Object: obj, Mapping: mapping}
		outputObj, err := resource.AsVersionedObject([]*resource.Info{&info}, false, *outputVersion)
		if err != nil {
			glog.Infof("Template.Objects[%d]: Unable to convert: %v", err)
			continue
		}
		items[i] = outputObj
	}
}
开发者ID:johnmccawley,项目名称:origin,代码行数:24,代码来源:main.go

示例10: RunGet


//.........这里部分代码省略.........
	if isWatch || isWatchOnly {
		r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
			NamespaceParam(cmdNamespace).DefaultNamespace().AllNamespaces(allNamespaces).
			FilenameParam(enforceNamespace, filenames...).
			SelectorParam(selector).
			ResourceTypeOrNameArgs(true, args...).
			SingleResourceType().
			Latest().
			Do()
		if err != nil {
			return err
		}
		infos, err := r.Infos()
		if err != nil {
			return err
		}
		if len(infos) != 1 {
			return fmt.Errorf("watch is only supported on a single resource - %d resources were found", len(infos))
		}
		info := infos[0]
		mapping := info.ResourceMapping()
		printer, err := f.PrinterForMapping(cmd, mapping, allNamespaces)
		if err != nil {
			return err
		}

		obj, err := r.Object()
		if err != nil {
			return err
		}
		rv, err := mapping.MetadataAccessor.ResourceVersion(obj)
		if err != nil {
			return err
		}

		// print the current object
		if !isWatchOnly {
			if err := printer.PrintObj(obj, out); err != nil {
				return fmt.Errorf("unable to output the provided object: %v", err)
			}
		}

		// print watched changes
		w, err := r.Watch(rv)
		if err != nil {
			return err
		}

		kubectl.WatchLoop(w, func(e watch.Event) error {
			return printer.PrintObj(e.Object, out)
		})
		return nil
	}

	b := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
		NamespaceParam(cmdNamespace).DefaultNamespace().AllNamespaces(allNamespaces).
		FilenameParam(enforceNamespace, filenames...).
		SelectorParam(selector).
		ResourceTypeOrNameArgs(true, args...).
		ContinueOnError().
		Latest()
	printer, generic, err := cmdutil.PrinterForCommand(cmd)
	if err != nil {
		return err
	}

	if generic {
		clientConfig, err := f.ClientConfig()
		if err != nil {
			return err
		}
		defaultVersion := clientConfig.Version

		singular := false
		r := b.Flatten().Do()
		infos, err := r.IntoSingular(&singular).Infos()
		if err != nil {
			return err
		}

		// the outermost object will be converted to the output-version, but inner
		// objects can use their mappings
		version := cmdutil.OutputVersion(cmd, defaultVersion)
		obj, err := resource.AsVersionedObject(infos, !singular, version)
		if err != nil {
			return err
		}

		return printer.PrintObj(obj, out)
	}

	// use the default printer for each object
	return b.Do().Visit(func(r *resource.Info) error {
		printer, err := f.PrinterForMapping(cmd, r.Mapping, allNamespaces)
		if err != nil {
			return err
		}
		return printer.PrintObj(r.Object, out)
	})
}
开发者ID:nvnvrts,项目名称:kubernetes,代码行数:101,代码来源:get.go

示例11: RunVolume

func (v *VolumeOptions) RunVolume(args []string) error {
	mapper := resource.ClientMapperFunc(v.RESTClientFactory)
	b := resource.NewBuilder(v.Mapper, v.Typer, mapper).
		ContinueOnError().
		NamespaceParam(v.DefaultNamespace).DefaultNamespace().
		FilenameParam(v.ExplicitNamespace, v.Filenames...).
		SelectorParam(v.Selector).
		ResourceTypeOrNameArgs(v.All, args...).
		Flatten()

	singular := false
	infos, err := b.Do().IntoSingular(&singular).Infos()
	if err != nil {
		return err
	}

	updateInfos := []*resource.Info{}
	// if a claim should be created, generate the info we'll add to the flow
	if v.Add && v.AddOpts.CreateClaim {
		claim := v.AddOpts.createClaim()
		m, err := v.Mapper.RESTMapping("PersistentVolumeClaim")
		if err != nil {
			return err
		}
		client, err := mapper.ClientForMapping(m)
		if err != nil {
			return err
		}
		info := &resource.Info{
			Mapping:   m,
			Client:    client,
			Namespace: v.DefaultNamespace,
			Object:    claim,
		}
		infos = append(infos, info)
		updateInfos = append(updateInfos, info)
	}

	skipped := 0
	for _, info := range infos {
		ok, err := v.UpdatePodSpecForObject(info.Object, func(spec *kapi.PodSpec) error {
			var e error
			switch {
			case v.Add:
				e = v.addVolumeToSpec(spec, info, singular)
			case v.Remove:
				e = v.removeVolumeFromSpec(spec, info)
			case v.List:
				e = v.listVolumeForSpec(spec, info)
			}
			return e
		})
		if !ok {
			skipped++
			continue
		}
		if err != nil {
			fmt.Fprintf(v.Err, "error: %s/%s %v\n", info.Mapping.Resource, info.Name, err)
			continue
		}
		updateInfos = append(updateInfos, info)
	}
	if singular && skipped == len(infos) {
		return fmt.Errorf("the %s %s is not a pod or does not have a pod template", infos[0].Mapping.Resource, infos[0].Name)
	}
	updatePodSpecFailed := len(updateInfos) != len(infos)

	if v.List {
		if updatePodSpecFailed {
			return errExit
		}
		return nil
	}

	objects, err := resource.AsVersionedObject(infos, false, v.OutputVersion)
	if err != nil {
		return err
	}

	if len(v.Output) != 0 {
		p, _, err := kubectl.GetPrinter(v.Output, "")
		if err != nil {
			return err
		}
		return p.PrintObj(objects, v.Out)
	}

	failed := false
	for _, info := range updateInfos {
		var obj runtime.Object
		if len(info.ResourceVersion) == 0 {
			obj, err = resource.NewHelper(info.Client, info.Mapping).Create(info.Namespace, false, info.Object)
		} else {
			obj, err = resource.NewHelper(info.Client, info.Mapping).Replace(info.Namespace, info.Name, true, info.Object)
		}
		if err != nil {
			handlePodUpdateError(v.Err, err, "volume")
			failed = true
			continue
		}
//.........这里部分代码省略.........
开发者ID:hloganathan,项目名称:origin,代码行数:101,代码来源:volume.go

示例12: doEdit

func doEdit(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, prefix string, rejectSame bool, addSource func(*resource.Builder, bool, kubectl.ResourcePrinter) *resource.Builder, process editProcessingFunc) error {
	printer, ext, err := getEditPrinter(cmd)
	if err != nil {
		return err
	}

	cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
	if err != nil {
		return err
	}

	mapper, typer := f.Object()
	rmap := &resource.Mapper{
		ObjectTyper:  typer,
		RESTMapper:   mapper,
		ClientMapper: f.ClientMapperForCommand(),
	}

	b := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
		NamespaceParam(cmdNamespace).DefaultNamespace().
		Flatten()

	b = addSource(b, enforceNamespace, printer)

	r := b.Do()
	err = r.Err()
	if err != nil {
		return err
	}

	infos, err := r.Infos()
	if err != nil {
		return err
	}

	clientConfig, err := f.ClientConfig()
	if err != nil {
		return err
	}

	defaultVersion := cmdutil.OutputVersion(cmd, clientConfig.Version)
	results := editResults{}
	for {
		obj, err := resource.AsVersionedObject(infos, false, defaultVersion)
		if err != nil {
			return preservedFile(err, results.file, out)
		}

		// TODO: add an annotating YAML printer that can print inline comments on each field,
		//   including descriptions or validation errors

		// generate the file to edit
		buf := &bytes.Buffer{}
		if err := results.header.writeTo(buf); err != nil {
			return preservedFile(err, results.file, out)
		}
		if err := printer.PrintObj(obj, buf); err != nil {
			return preservedFile(err, results.file, out)
		}
		original := buf.Bytes()

		// launch the editor
		edit := editor.NewDefaultEditor()
		edited, file, err := edit.LaunchTempFile("kubectl-edit-", ext, buf)
		if err != nil {
			return preservedFile(err, results.file, out)
		}

		// cleanup any file from the previous pass
		if len(results.file) > 0 {
			os.Remove(results.file)
		}

		glog.V(4).Infof("User edited:\n%s", string(edited))
		fmt.Printf("User edited:\n%s", string(edited))
		lines, err := hasLines(bytes.NewBuffer(edited))
		if err != nil {
			return preservedFile(err, file, out)
		}
		if rejectSame && bytes.Equal(original, edited) {
			if len(results.edit) > 0 {
				preservedFile(nil, file, out)
			} else {
				os.Remove(file)
			}
			fmt.Fprintln(out, "Edit cancelled, no changes made.")
			return nil
		}
		if !lines {
			if len(results.edit) > 0 {
				preservedFile(nil, file, out)
			} else {
				os.Remove(file)
			}
			fmt.Fprintln(out, "Edit cancelled, saved file was empty.")
			return nil
		}

		results = editResults{
			file: file,
//.........这里部分代码省略.........
开发者ID:DirectXMan12,项目名称:kubernetes,代码行数:101,代码来源:edit.go

示例13: RunVolume

func (v *VolumeOptions) RunVolume(args []string) error {
	mapper := resource.ClientMapperFunc(v.RESTClientFactory)
	b := resource.NewBuilder(v.Mapper, v.Typer, mapper, kapi.Codecs.UniversalDecoder()).
		ContinueOnError().
		NamespaceParam(v.DefaultNamespace).DefaultNamespace().
		FilenameParam(v.ExplicitNamespace, false, v.Filenames...).
		SelectorParam(v.Selector).
		ResourceTypeOrNameArgs(v.All, args...).
		Flatten()

	singular := false
	infos, err := b.Do().IntoSingular(&singular).Infos()
	if err != nil {
		return err
	}

	if v.List {
		listingErrors := v.printVolumes(infos)
		if len(listingErrors) > 0 {
			return cmdutil.ErrExit
		}
		return nil
	}

	updateInfos := []*resource.Info{}
	// if a claim should be created, generate the info we'll add to the flow
	if v.Add && v.AddOpts.CreateClaim {
		claim := v.AddOpts.createClaim()
		m, err := v.Mapper.RESTMapping(kapi.Kind("PersistentVolumeClaim"))
		if err != nil {
			return err
		}
		client, err := mapper.ClientForMapping(m)
		if err != nil {
			return err
		}
		info := &resource.Info{
			Mapping:   m,
			Client:    client,
			Namespace: v.DefaultNamespace,
			Object:    claim,
		}
		infos = append(infos, info)
		updateInfos = append(updateInfos, info)
	}

	patches, patchError := v.getVolumeUpdatePatches(infos, singular)

	if patchError != nil {
		return patchError
	}

	objects, err := resource.AsVersionedObject(infos, false, v.OutputVersion, kapi.Codecs.LegacyCodec(v.OutputVersion))
	if err != nil {
		return err
	}

	if len(v.Output) != 0 {
		p, _, err := kubectl.GetPrinter(v.Output, "", false)
		if err != nil {
			return err
		}
		return p.PrintObj(objects, v.Out)
	}

	failed := false
	for _, info := range updateInfos {
		var obj runtime.Object
		if len(info.ResourceVersion) == 0 {
			obj, err = resource.NewHelper(info.Client, info.Mapping).Create(info.Namespace, false, info.Object)
		} else {
			obj, err = resource.NewHelper(info.Client, info.Mapping).Replace(info.Namespace, info.Name, true, info.Object)
		}
		if err != nil {
			handlePodUpdateError(v.Err, err, "volume")
			failed = true
			continue
		}
		info.Refresh(obj, true)
		fmt.Fprintf(v.Out, "%s/%s\n", info.Mapping.Resource, info.Name)
	}
	for _, patch := range patches {
		info := patch.Info
		if patch.Err != nil {
			failed = true
			fmt.Fprintf(v.Err, "error: %s/%s %v\n", info.Mapping.Resource, info.Name, patch.Err)
			continue
		}

		if string(patch.Patch) == "{}" || len(patch.Patch) == 0 {
			fmt.Fprintf(v.Err, "info: %s %q was not changed\n", info.Mapping.Resource, info.Name)
			continue
		}

		glog.V(4).Infof("Calculated patch %s", patch.Patch)

		obj, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, kapi.StrategicMergePatchType, patch.Patch)
		if err != nil {
			handlePodUpdateError(v.Err, err, "volume")
			failed = true
//.........这里部分代码省略.........
开发者ID:mffiedler,项目名称:origin,代码行数:101,代码来源:volume.go

示例14: RunGet


//.........这里部分代码省略.........

	printer, generic, err := cmdutil.PrinterForCommand(cmd)
	if err != nil {
		return err
	}

	if generic {
		clientConfig, err := f.ClientConfig()
		if err != nil {
			return err
		}

		allErrs := []error{}
		singular := false
		infos, err := r.IntoSingular(&singular).Infos()
		if err != nil {
			if singular {
				return err
			}
			allErrs = append(allErrs, err)
		}

		// the outermost object will be converted to the output-version, but inner
		// objects can use their mappings
		version, err := cmdutil.OutputVersion(cmd, clientConfig.GroupVersion)
		if err != nil {
			return err
		}
		res := ""
		if len(infos) > 0 {
			res = infos[0].ResourceMapping().Resource
		}

		obj, err := resource.AsVersionedObject(infos, !singular, version, f.JSONEncoder())
		if err != nil {
			return err
		}

		if err := printer.PrintObj(obj, out); err != nil {
			allErrs = append(allErrs, err)
		}
		printer.AfterPrint(errOut, res)
		return utilerrors.NewAggregate(allErrs)
	}

	allErrs := []error{}
	infos, err := r.Infos()
	if err != nil {
		allErrs = append(allErrs, err)
	}

	objs := make([]runtime.Object, len(infos))
	for ix := range infos {
		objs[ix] = infos[ix].Object
	}

	sorting, err := cmd.Flags().GetString("sort-by")
	if err != nil {
		return err
	}
	var sorter *kubectl.RuntimeSort
	if len(sorting) > 0 && len(objs) > 1 {
		clientConfig, err := f.ClientConfig()
		if err != nil {
			return err
		}
开发者ID:PeterLamar,项目名称:kubernetes,代码行数:67,代码来源:get.go

示例15: RunEdit

func RunEdit(f *cmdutil.Factory, out, errOut io.Writer, cmd *cobra.Command, args []string, options *EditOptions) error {
	var printer kubectl.ResourcePrinter
	var ext string
	switch format := cmdutil.GetFlagString(cmd, "output"); format {
	case "json":
		printer = &kubectl.JSONPrinter{}
		ext = ".json"
	case "yaml":
		printer = &kubectl.YAMLPrinter{}
		ext = ".yaml"
	default:
		return cmdutil.UsageError(cmd, "The flag 'output' must be one of yaml|json")
	}

	cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
	if err != nil {
		return err
	}

	mapper, typer := f.Object(cmdutil.GetIncludeThirdPartyAPIs(cmd))
	resourceMapper := &resource.Mapper{
		ObjectTyper:  typer,
		RESTMapper:   mapper,
		ClientMapper: resource.ClientMapperFunc(f.ClientForMapping),

		// NB: we use `f.Decoder(false)` to get a plain deserializer for
		// the resourceMapper, since it's used to read in edits and
		// we don't want to convert into the internal version when
		// reading in edits (this would cause us to potentially try to
		// compare two different GroupVersions).
		Decoder: f.Decoder(false),
	}

	r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
		NamespaceParam(cmdNamespace).DefaultNamespace().
		FilenameParam(enforceNamespace, options.Recursive, options.Filenames...).
		ResourceTypeOrNameArgs(true, args...).
		Flatten().
		Latest().
		Do()
	err = r.Err()
	if err != nil {
		return err
	}

	infos, err := r.Infos()
	if err != nil {
		return err
	}

	clientConfig, err := f.ClientConfig()
	if err != nil {
		return err
	}

	encoder := f.JSONEncoder()
	defaultVersion, err := cmdutil.OutputVersion(cmd, clientConfig.GroupVersion)
	if err != nil {
		return err
	}
	originalObj, err := resource.AsVersionedObject(infos, false, defaultVersion, encoder)
	if err != nil {
		return err
	}

	var (
		windowsLineEndings = cmdutil.GetFlagBool(cmd, "windows-line-endings")
		edit               = editor.NewDefaultEditor(f.EditorEnvs())
		results            = editResults{}
		original           = []byte{}
		edited             = []byte{}
		file               string
	)

	containsError := false

	for {
		// infos mutates over time to be the list of things we've tried and failed to edit
		// this means that our overall list changes over time.
		objToEdit, err := resource.AsVersionedObject(infos, false, defaultVersion, encoder)
		if err != nil {
			return err
		}

		// generate the file to edit
		buf := &bytes.Buffer{}
		var w io.Writer = buf
		if windowsLineEndings {
			w = crlf.NewCRLFWriter(w)
		}
		if err := results.header.writeTo(w); err != nil {
			return preservedFile(err, results.file, errOut)
		}
		if !containsError {
			if err := printer.PrintObj(objToEdit, w); err != nil {
				return preservedFile(err, results.file, errOut)
			}
			original = buf.Bytes()
		} else {
			// In case of an error, preserve the edited file.
//.........这里部分代码省略.........
开发者ID:FlyWings,项目名称:kubernetes,代码行数:101,代码来源:edit.go


注:本文中的k8s/io/kubernetes/pkg/kubectl/resource.AsVersionedObject函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。