本文整理汇总了Golang中k8s/io/kubernetes/pkg/kubectl/cmd/util.Factory.Decoder方法的典型用法代码示例。如果您正苦于以下问题:Golang Factory.Decoder方法的具体用法?Golang Factory.Decoder怎么用?Golang Factory.Decoder使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类k8s/io/kubernetes/pkg/kubectl/cmd/util.Factory
的用法示例。
在下文中一共展示了Factory.Decoder方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: getMapperAndResult
func getMapperAndResult(f cmdutil.Factory, args []string, options *resource.FilenameOptions) (meta.RESTMapper, *resource.Mapper, *resource.Result, string, error) {
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return nil, nil, nil, "", err
}
mapper, typer := f.Object()
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).
ResourceTypeOrNameArgs(true, args...).
ContinueOnError().
Flatten().
Latest().
Do()
err = r.Err()
if err != nil {
return nil, nil, nil, "", err
}
return mapper, resourceMapper, r, cmdNamespace, err
}
示例2: createGeneratedObject
func createGeneratedObject(f *cmdutil.Factory, cmd *cobra.Command, generator kubectl.Generator, names []kubectl.GeneratorParam, params map[string]interface{}, overrides, namespace string) (runtime.Object, string, meta.RESTMapper, *meta.RESTMapping, error) {
err := kubectl.ValidateParams(names, params)
if err != nil {
return nil, "", nil, nil, err
}
// TODO: Validate flag usage against selected generator. More tricky since --expose was added.
obj, err := generator.Generate(params)
if err != nil {
return nil, "", nil, nil, err
}
mapper, typer := f.Object()
groupVersionKind, err := typer.ObjectKind(obj)
if err != nil {
return nil, "", nil, nil, err
}
if len(overrides) > 0 {
codec := runtime.NewCodec(f.JSONEncoder(), f.Decoder(true))
obj, err = cmdutil.Merge(codec, obj, overrides, groupVersionKind.Kind)
if err != nil {
return nil, "", nil, nil, err
}
}
mapping, err := mapper.RESTMapping(groupVersionKind.GroupKind(), groupVersionKind.Version)
if err != nil {
return nil, "", nil, nil, err
}
client, err := f.ClientForMapping(mapping)
if err != nil {
return nil, "", nil, nil, err
}
// TODO: extract this flag to a central location, when such a location exists.
if !cmdutil.GetFlagBool(cmd, "dry-run") {
resourceMapper := &resource.Mapper{
ObjectTyper: typer,
RESTMapper: mapper,
ClientMapper: resource.ClientMapperFunc(f.ClientForMapping),
Decoder: f.Decoder(true),
}
info, err := resourceMapper.InfoForObject(obj)
if err != nil {
return nil, "", nil, nil, err
}
if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info, f.JSONEncoder()); err != nil {
return nil, "", nil, nil, err
}
obj, err = resource.NewHelper(client, mapping).Create(namespace, false, info.Object)
if err != nil {
return nil, "", nil, nil, err
}
}
return obj, groupVersionKind.Kind, mapper, mapping, err
}
示例3: Complete
func (o *LogsOptions) Complete(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error {
containerName := cmdutil.GetFlagString(cmd, "container")
switch len(args) {
case 0:
return cmdutil.UsageError(cmd, "POD is required for logs")
case 1:
o.ResourceArg = args[0]
case 2:
if cmd.Flag("container").Changed {
return cmdutil.UsageError(cmd, "only one of -c, [CONTAINER] arg is allowed")
}
o.ResourceArg = args[0]
containerName = args[1]
default:
return cmdutil.UsageError(cmd, "logs POD [-c CONTAINER]")
}
var err error
o.Namespace, _, err = f.DefaultNamespace()
if err != nil {
return err
}
logOptions := &api.PodLogOptions{
Container: containerName,
Follow: cmdutil.GetFlagBool(cmd, "follow"),
Previous: cmdutil.GetFlagBool(cmd, "previous"),
Timestamps: cmdutil.GetFlagBool(cmd, "timestamps"),
}
if sinceTime := cmdutil.GetFlagString(cmd, "since-time"); len(sinceTime) > 0 {
t, err := api.ParseRFC3339(sinceTime, unversioned.Now)
if err != nil {
return err
}
logOptions.SinceTime = &t
}
if limit := cmdutil.GetFlagInt64(cmd, "limit-bytes"); limit != 0 {
logOptions.LimitBytes = &limit
}
if tail := cmdutil.GetFlagInt64(cmd, "tail"); tail != -1 {
logOptions.TailLines = &tail
}
if sinceSeconds := cmdutil.GetFlagDuration(cmd, "since"); sinceSeconds != 0 {
// round up to the nearest second
sec := int64(math.Ceil(float64(sinceSeconds) / float64(time.Second)))
logOptions.SinceSeconds = &sec
}
o.Options = logOptions
o.Mapper, o.Typer = f.Object()
o.Decoder = f.Decoder(true)
o.ClientMapper = resource.ClientMapperFunc(f.ClientForMapping)
o.LogsForObject = f.LogsForObject
o.Out = out
return nil
}
示例4: getMapperAndResult
func getMapperAndResult(f cmdutil.Factory, args []string, options *resource.FilenameOptions, editMode EditMode) (meta.RESTMapper, *resource.Mapper, *resource.Result, string, error) {
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return nil, nil, nil, "", err
}
var mapper meta.RESTMapper
var typer runtime.ObjectTyper
switch editMode {
case NormalEditMode:
mapper, typer = f.Object()
case EditBeforeCreateMode:
mapper, typer, err = f.UnstructuredObject()
default:
return nil, nil, nil, "", fmt.Errorf("Not supported edit mode %q", editMode)
}
if err != nil {
return nil, nil, nil, "", err
}
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),
}
var b *resource.Builder
switch editMode {
case NormalEditMode:
b = resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
ResourceTypeOrNameArgs(true, args...).
Latest()
case EditBeforeCreateMode:
b = resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.UnstructuredClientForMapping), runtime.UnstructuredJSONScheme)
default:
return nil, nil, nil, "", fmt.Errorf("Not supported edit mode %q", editMode)
}
r := b.NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(enforceNamespace, options).
ContinueOnError().
Flatten().
Do()
err = r.Err()
if err != nil {
return nil, nil, nil, "", err
}
return mapper, resourceMapper, r, cmdNamespace, err
}
示例5: Complete
// Complete collects information required to run Convert command from command line.
func (o *ConvertOptions) Complete(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) (err error) {
o.outputVersion, err = cmdutil.OutputVersion(cmd, ®istered.EnabledVersionsForGroup(api.GroupName)[0])
if err != nil {
return err
}
if !registered.IsEnabledVersion(o.outputVersion) {
cmdutil.UsageError(cmd, "'%s' is not a registered version.", o.outputVersion)
}
// build the builder
mapper, typer := f.Object(cmdutil.GetIncludeThirdPartyAPIs(cmd))
clientMapper := resource.ClientMapperFunc(f.ClientForMapping)
if o.local {
fmt.Fprintln(os.Stderr, "running in local mode...")
o.builder = resource.NewBuilder(mapper, typer, resource.DisabledClientForMapping{ClientMapper: clientMapper}, f.Decoder(true))
} else {
o.builder = resource.NewBuilder(mapper, typer, clientMapper, f.Decoder(true))
schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"), cmdutil.GetFlagString(cmd, "schema-cache-dir"))
if err != nil {
return err
}
o.builder = o.builder.Schema(schema)
}
cmdNamespace, _, err := f.DefaultNamespace()
if err != nil {
return err
}
o.builder = o.builder.NamespaceParam(cmdNamespace).
ContinueOnError().
FilenameParam(false, o.recursive, o.filenames...).
Flatten()
// build the printer
o.out = out
outputFormat := cmdutil.GetFlagString(cmd, "output")
templateFile := cmdutil.GetFlagString(cmd, "template")
if len(outputFormat) == 0 {
if len(templateFile) == 0 {
outputFormat = "yaml"
} else {
outputFormat = "template"
}
}
o.encoder = f.JSONEncoder()
o.printer, _, err = kubectl.GetPrinter(outputFormat, templateFile, false)
if err != nil {
return err
}
return nil
}
示例6: Run
//.........这里部分代码省略.........
},
CommandName: cmd.Parent().CommandPath() + " attach",
Attach: &DefaultRemoteAttach{},
}
config, err := f.ClientConfig()
if err != nil {
return err
}
opts.Config = config
clientset, err := f.ClientSet()
if err != nil {
return err
}
opts.PodClient = clientset.Core()
attachablePod, err := f.AttachablePodForObject(obj)
if err != nil {
return err
}
err = handleAttachPod(f, clientset.Core(), attachablePod.Namespace, attachablePod.Name, opts, quiet)
if err != nil {
return err
}
var pod *api.Pod
leaveStdinOpen := cmdutil.GetFlagBool(cmd, "leave-stdin-open")
waitForExitCode := !leaveStdinOpen && restartPolicy == api.RestartPolicyNever
if waitForExitCode {
pod, err = waitForPodTerminated(clientset.Core(), attachablePod.Namespace, attachablePod.Name, opts.Out, quiet)
if err != nil {
return err
}
}
if remove {
namespace, err = mapping.MetadataAccessor.Namespace(obj)
if err != nil {
return err
}
var name string
name, err = mapping.MetadataAccessor.Name(obj)
if err != nil {
return err
}
_, typer := f.Object()
r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
ContinueOnError().
NamespaceParam(namespace).DefaultNamespace().
ResourceNames(mapping.Resource, name).
Flatten().
Do()
// Note: we pass in "true" for the "quiet" parameter because
// ReadResult will only print one thing based on the "quiet"
// flag, and that's the "pod xxx deleted" message. If they
// asked for us to remove the pod (via --rm) then telling them
// its been deleted is unnecessary since that's what they asked
// for. We should only print something if the "rm" fails.
err = ReapResult(r, f, cmdOut, true, true, 0, -1, false, false, mapper, true)
if err != nil {
return err
}
}
// after removal is done, return successfully if we are not interested in the exit code
if !waitForExitCode {
return nil
}
switch pod.Status.Phase {
case api.PodSucceeded:
return nil
case api.PodFailed:
unknownRcErr := fmt.Errorf("pod %s/%s failed with unknown exit code", pod.Namespace, pod.Name)
if len(pod.Status.ContainerStatuses) == 0 || pod.Status.ContainerStatuses[0].State.Terminated == nil {
return unknownRcErr
}
// assume here that we have at most one status because kubectl-run only creates one container per pod
rc := pod.Status.ContainerStatuses[0].State.Terminated.ExitCode
if rc == 0 {
return unknownRcErr
}
return uexec.CodeExitError{
Err: fmt.Errorf("pod %s/%s terminated", pod.Namespace, pod.Name),
Code: int(rc),
}
default:
return fmt.Errorf("pod %s/%s left in phase %s", pod.Namespace, pod.Name, pod.Status.Phase)
}
}
outputFormat := cmdutil.GetFlagString(cmd, "output")
if outputFormat != "" || cmdutil.GetDryRunFlag(cmd) {
return f.PrintObject(cmd, mapper, obj, cmdOut)
}
cmdutil.PrintSuccess(mapper, false, cmdOut, mapping.Resource, args[0], cmdutil.GetDryRunFlag(cmd), "created")
return nil
}
示例7: Run
//.........这里部分代码省略.........
generator, found := generators[generatorName]
if !found {
return cmdutil.UsageError(cmd, fmt.Sprintf("generator %q not found.", generatorName))
}
names := generator.ParamNames()
params := kubectl.MakeParams(cmd, names)
params["name"] = args[0]
if len(args) > 1 {
params["args"] = args[1:]
}
params["env"] = cmdutil.GetFlagStringSlice(cmd, "env")
obj, _, mapper, mapping, err := createGeneratedObject(f, cmd, generator, names, params, cmdutil.GetFlagString(cmd, "overrides"), namespace)
if err != nil {
return err
}
if cmdutil.GetFlagBool(cmd, "expose") {
serviceGenerator := cmdutil.GetFlagString(cmd, "service-generator")
if len(serviceGenerator) == 0 {
return cmdutil.UsageError(cmd, fmt.Sprintf("No service generator specified"))
}
if err := generateService(f, cmd, args, serviceGenerator, params, namespace, cmdOut); err != nil {
return err
}
}
attachFlag := cmd.Flags().Lookup("attach")
attach := cmdutil.GetFlagBool(cmd, "attach")
if !attachFlag.Changed && interactive {
attach = true
}
remove := cmdutil.GetFlagBool(cmd, "rm")
if !attach && remove {
return cmdutil.UsageError(cmd, "--rm should only be used for attached containers")
}
if attach {
opts := &AttachOptions{
In: cmdIn,
Out: cmdOut,
Err: cmdErr,
Stdin: interactive,
TTY: tty,
Attach: &DefaultRemoteAttach{},
}
config, err := f.ClientConfig()
if err != nil {
return err
}
opts.Config = config
client, err := f.Client()
if err != nil {
return err
}
opts.Client = client
attachablePod, err := f.AttachablePodForObject(obj)
if err != nil {
return err
}
err = handleAttachPod(f, client, attachablePod, opts)
if err != nil {
return err
}
if remove {
namespace, err = mapping.MetadataAccessor.Namespace(obj)
if err != nil {
return err
}
var name string
name, err = mapping.MetadataAccessor.Name(obj)
if err != nil {
return err
}
_, typer := f.Object(cmdutil.GetIncludeThirdPartyAPIs(cmd))
r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
ContinueOnError().
NamespaceParam(namespace).DefaultNamespace().
ResourceNames(mapping.Resource, name).
Flatten().
Do()
return ReapResult(r, f, cmdOut, true, true, 0, -1, false, mapper)
}
return nil
}
outputFormat := cmdutil.GetFlagString(cmd, "output")
if outputFormat != "" {
return f.PrintObject(cmd, mapper, obj, cmdOut)
}
cmdutil.PrintSuccess(mapper, false, cmdOut, mapping.Resource, args[0], "created")
return nil
}
示例8: RunDescribe
func RunDescribe(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *DescribeOptions, describerSettings *kubectl.DescriberSettings) error {
selector := cmdutil.GetFlagString(cmd, "selector")
allNamespaces := cmdutil.GetFlagBool(cmd, "all-namespaces")
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
if allNamespaces {
enforceNamespace = false
}
if len(args) == 0 && len(options.Filenames) == 0 {
fmt.Fprint(out, "You must specify the type of resource to describe. ", valid_resources)
return cmdutil.UsageError(cmd, "Required resource not specified.")
}
mapper, typer := f.Object(cmdutil.GetIncludeThirdPartyAPIs(cmd))
r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().AllNamespaces(allNamespaces).
FilenameParam(enforceNamespace, options.Recursive, options.Filenames...).
SelectorParam(selector).
ResourceTypeOrNameArgs(true, args...).
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
allErrs := []error{}
infos, err := r.Infos()
if err != nil {
if apierrors.IsNotFound(err) && len(args) == 2 {
return DescribeMatchingResources(mapper, typer, f, cmdNamespace, args[0], args[1], describerSettings, out, err)
}
allErrs = append(allErrs, err)
}
first := true
for _, info := range infos {
mapping := info.ResourceMapping()
describer, err := f.Describer(mapping)
if err != nil {
allErrs = append(allErrs, err)
continue
}
s, err := describer.Describe(info.Namespace, info.Name, *describerSettings)
if err != nil {
allErrs = append(allErrs, err)
continue
}
if first {
first = false
fmt.Fprint(out, s)
} else {
fmt.Fprintf(out, "\n\n%s", s)
}
}
return utilerrors.NewAggregate(allErrs)
}
示例9: RunExpose
func RunExpose(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *ExposeOptions) error {
namespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
mapper, typer := f.Object(false)
r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
ContinueOnError().
NamespaceParam(namespace).DefaultNamespace().
FilenameParam(enforceNamespace, options.Recursive, options.Filenames...).
ResourceTypeOrNameArgs(false, args...).
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
// Get the generator, setup and validate all required parameters
generatorName := cmdutil.GetFlagString(cmd, "generator")
generators := f.Generators("expose")
generator, found := generators[generatorName]
if !found {
return cmdutil.UsageError(cmd, fmt.Sprintf("generator %q not found.", generatorName))
}
names := generator.ParamNames()
err = r.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
mapping := info.ResourceMapping()
if err := f.CanBeExposed(mapping.GroupVersionKind.GroupKind()); err != nil {
return err
}
params := kubectl.MakeParams(cmd, names)
name := info.Name
if len(name) > validation.DNS952LabelMaxLength {
name = name[:validation.DNS952LabelMaxLength]
}
params["default-name"] = name
// For objects that need a pod selector, derive it from the exposed object in case a user
// didn't explicitly specify one via --selector
if s, found := params["selector"]; found && kubectl.IsZero(s) {
s, err := f.MapBasedSelectorForObject(info.Object)
if err != nil {
return cmdutil.UsageError(cmd, fmt.Sprintf("couldn't retrieve selectors via --selector flag or introspection: %s", err))
}
params["selector"] = s
}
// For objects that need a port, derive it from the exposed object in case a user
// didn't explicitly specify one via --port
if port, found := params["port"]; found && kubectl.IsZero(port) {
ports, err := f.PortsForObject(info.Object)
if err != nil {
return cmdutil.UsageError(cmd, fmt.Sprintf("couldn't find port via --port flag or introspection: %s", err))
}
switch len(ports) {
case 0:
return cmdutil.UsageError(cmd, "couldn't find port via --port flag or introspection")
case 1:
params["port"] = ports[0]
default:
params["ports"] = strings.Join(ports, ",")
}
}
// Always try to derive protocols from the exposed object, may use
// different protocols for different ports.
if _, found := params["protocol"]; found {
protocolsMap, err := f.ProtocolsForObject(info.Object)
if err != nil {
return cmdutil.UsageError(cmd, fmt.Sprintf("couldn't find protocol via introspection: %s", err))
}
if protocols := kubectl.MakeProtocols(protocolsMap); !kubectl.IsZero(protocols) {
params["protocols"] = protocols
}
}
if kubectl.IsZero(params["labels"]) {
labels, err := f.LabelsForObject(info.Object)
if err != nil {
return err
}
params["labels"] = kubectl.MakeLabels(labels)
}
if err = kubectl.ValidateParams(names, params); err != nil {
return err
}
// Check for invalid flags used against the present generator.
if err := kubectl.EnsureFlagsValid(cmd, generators, generatorName); err != nil {
return err
}
// Generate new object
//.........这里部分代码省略.........
示例10: CompleteUndo
func (o *UndoOptions) CompleteUndo(f cmdutil.Factory, cmd *cobra.Command, out io.Writer, args []string) error {
if len(args) == 0 && cmdutil.IsFilenameEmpty(o.Filenames) {
return cmdutil.UsageError(cmd, "Required resource not specified.")
}
o.ToRevision = cmdutil.GetFlagInt64(cmd, "to-revision")
o.Mapper, o.Typer = f.Object()
o.Out = out
o.DryRun = cmdutil.GetFlagBool(cmd, "dry-run")
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
r := resource.NewBuilder(o.Mapper, o.Typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(enforceNamespace, &o.FilenameOptions).
ResourceTypeOrNameArgs(true, args...).
ContinueOnError().
Latest().
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
err = r.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
rollbacker, err := f.Rollbacker(info.ResourceMapping())
if err != nil {
return err
}
o.Infos = append(o.Infos, info)
o.Rollbackers = append(o.Rollbackers, rollbacker)
return nil
})
return err
}
示例11: RunCreate
func RunCreate(f *cmdutil.Factory, cmd *cobra.Command, out io.Writer, options *CreateOptions) error {
schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"), cmdutil.GetFlagString(cmd, "schema-cache-dir"))
if err != nil {
return err
}
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
mapper, typer := f.Object()
r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
Schema(schema).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(enforceNamespace, options.Filenames...).
Flatten().
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
}
if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info, f.JSONEncoder()); err != nil {
return cmdutil.AddSourceToErr("creating", info.Source, err)
}
if cmdutil.ShouldRecord(cmd, info) {
if err := cmdutil.RecordChangeCause(info.Object, f.Command()); err != nil {
return cmdutil.AddSourceToErr("creating", info.Source, err)
}
}
if err := createAndRefresh(info); err != nil {
return cmdutil.AddSourceToErr("creating", info.Source, err)
}
count++
shortOutput := cmdutil.GetFlagString(cmd, "output") == "name"
if !shortOutput {
printObjectSpecificMessage(info.Object, out)
}
cmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "created")
return nil
})
if err != nil {
return err
}
if count == 0 {
return fmt.Errorf("no objects passed to create")
}
return nil
}
示例12: RunHistory
func RunHistory(f *cmdutil.Factory, cmd *cobra.Command, out io.Writer, args []string, options *HistoryOptions) error {
if len(args) == 0 && len(options.Filenames) == 0 {
return cmdutil.UsageError(cmd, "Required resource not specified.")
}
revision := cmdutil.GetFlagInt64(cmd, "revision")
if revision < 0 {
return fmt.Errorf("revision must be a positive integer: %v", revision)
}
mapper, typer := f.Object(false)
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(enforceNamespace, options.Recursive, options.Filenames...).
ResourceTypeOrNameArgs(true, args...).
ContinueOnError().
Latest().
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
return r.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
mapping := info.ResourceMapping()
historyViewer, err := f.HistoryViewer(mapping)
if err != nil {
return err
}
historyInfo, err := historyViewer.ViewHistory(info.Namespace, info.Name, revision)
if err != nil {
return err
}
header := fmt.Sprintf("%s %q", mapping.Resource, info.Name)
if revision > 0 {
header = fmt.Sprintf("%s with revision #%d", header, revision)
}
fmt.Fprintf(out, "%s\n", header)
fmt.Fprintf(out, "%s\n", historyInfo)
return nil
})
}
示例13: RunLabel
func RunLabel(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *LabelOptions) error {
resources, labelArgs := []string{}, []string{}
first := true
for _, s := range args {
isLabel := strings.Contains(s, "=") || strings.HasSuffix(s, "-")
switch {
case first && isLabel:
first = false
fallthrough
case !first && isLabel:
labelArgs = append(labelArgs, s)
case first && !isLabel:
resources = append(resources, s)
case !first && !isLabel:
return cmdutil.UsageError(cmd, "all resources must be specified before label changes: %s", s)
}
}
if len(resources) < 1 && len(options.Filenames) == 0 {
return cmdutil.UsageError(cmd, "one or more resources must be specified as <resource> <name> or <resource>/<name>")
}
if len(labelArgs) < 1 {
return cmdutil.UsageError(cmd, "at least one label update is required")
}
selector := cmdutil.GetFlagString(cmd, "selector")
all := cmdutil.GetFlagBool(cmd, "all")
overwrite := cmdutil.GetFlagBool(cmd, "overwrite")
resourceVersion := cmdutil.GetFlagString(cmd, "resource-version")
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
lbls, remove, err := parseLabels(labelArgs)
if err != nil {
return cmdutil.UsageError(cmd, err.Error())
}
mapper, typer := f.Object()
b := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(enforceNamespace, options.Filenames...).
SelectorParam(selector).
ResourceTypeOrNameArgs(all, resources...).
Flatten().
Latest()
one := false
r := b.Do().IntoSingular(&one)
if err := r.Err(); err != nil {
return err
}
// only apply resource version locking on a single resource
if !one && len(resourceVersion) > 0 {
return cmdutil.UsageError(cmd, "--resource-version may only be used with a single resource")
}
// TODO: support bulk generic output a la Get
return r.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
var outputObj runtime.Object
dataChangeMsg := "not labeled"
if cmdutil.GetFlagBool(cmd, "dry-run") {
err = labelFunc(info.Object, overwrite, resourceVersion, lbls, remove)
if err != nil {
return err
}
outputObj = info.Object
} else {
obj, err := info.Mapping.ConvertToVersion(info.Object, info.Mapping.GroupVersionKind.GroupVersion().String())
if err != nil {
return err
}
name, namespace := info.Name, info.Namespace
oldData, err := json.Marshal(obj)
if err != nil {
return err
}
meta, err := api.ObjectMetaFor(obj)
for _, label := range remove {
if _, ok := meta.Labels[label]; !ok {
fmt.Fprintf(out, "label %q not found.\n", label)
}
}
if err := labelFunc(obj, overwrite, resourceVersion, lbls, remove); err != nil {
return err
}
if cmdutil.ShouldRecord(cmd, info) {
if err := cmdutil.RecordChangeCause(obj, f.Command()); err != nil {
return err
}
}
newData, err := json.Marshal(obj)
if err != nil {
//.........这里部分代码省略.........
示例14: CompletePause
func (o *PauseConfig) CompletePause(f cmdutil.Factory, cmd *cobra.Command, out io.Writer, args []string) error {
if len(args) == 0 && cmdutil.IsFilenameEmpty(o.Filenames) {
return cmdutil.UsageError(cmd, cmd.Use)
}
o.Mapper, o.Typer = f.Object()
o.Encoder = f.JSONEncoder()
o.Pauser = f.Pauser
o.Out = out
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
r := resource.NewBuilder(o.Mapper, o.Typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(enforceNamespace, &o.FilenameOptions).
ResourceTypeOrNameArgs(true, args...).
ContinueOnError().
Latest().
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
o.Infos, err = r.Infos()
if err != nil {
return err
}
return nil
}
示例15: modifyCertificateCondition
func (options *CertificateOptions) modifyCertificateCondition(f cmdutil.Factory, out io.Writer, modify func(csr *certificates.CertificateSigningRequest) (*certificates.CertificateSigningRequest, string)) error {
var found int
mapper, typer := f.Object()
c, err := f.ClientSet()
if err != nil {
return err
}
r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
ContinueOnError().
FilenameParam(false, &options.FilenameOptions).
ResourceNames("certificatesigningrequest", options.csrNames...).
RequireObject(true).
Flatten().
Latest().
Do()
err = r.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
csr := info.Object.(*certificates.CertificateSigningRequest)
csr, verb := modify(csr)
csr, err = c.Certificates().
CertificateSigningRequests().
UpdateApproval(csr)
if err != nil {
return err
}
found++
cmdutil.PrintSuccess(mapper, options.outputStyle == "name", out, info.Mapping.Resource, info.Name, false, verb)
return nil
})
if found == 0 {
fmt.Fprintf(out, "No resources found\n")
}
return err
}