本文整理汇总了Golang中k8s/io/kubernetes/pkg/kubectl/resource.NewFlattenListVisitor函数的典型用法代码示例。如果您正苦于以下问题:Golang NewFlattenListVisitor函数的具体用法?Golang NewFlattenListVisitor怎么用?Golang NewFlattenListVisitor使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewFlattenListVisitor函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: visitToCreate
func visitToCreate(updates *resource.Info, mapper meta.RESTMapper, resourceMapper *resource.Mapper, out, errOut io.Writer, defaultVersion unversioned.GroupVersion, results *editResults, file string) error {
createVisitor := resource.NewFlattenListVisitor(updates, resourceMapper)
err := createVisitor.Visit(func(info *resource.Info, incomingErr error) error {
results.version = defaultVersion
if err := createAndRefresh(info); err != nil {
return err
}
cmdutil.PrintSuccess(mapper, false, out, info.Mapping.Resource, info.Name, false, "created")
return nil
})
return err
}
示例2: visitAnnotation
func visitAnnotation(cmd *cobra.Command, f cmdutil.Factory, updates *resource.Info, resourceMapper *resource.Mapper, encoder runtime.Encoder) ([]runtime.Object, error) {
mutatedObjects := []runtime.Object{}
annotationVisitor := resource.NewFlattenListVisitor(updates, resourceMapper)
// iterate through all items to apply annotations
err := annotationVisitor.Visit(func(info *resource.Info, incomingErr error) error {
// put configuration annotation in "updates"
if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info, encoder); err != nil {
return err
}
if cmdutil.ShouldRecord(cmd, info) {
if err := cmdutil.RecordChangeCause(info.Object, f.Command()); err != nil {
return err
}
}
mutatedObjects = append(mutatedObjects, info.Object)
return nil
})
return mutatedObjects, err
}
示例3: RunEdit
//.........这里部分代码省略.........
// 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))
lines, err := hasLines(bytes.NewBuffer(edited))
if err != nil {
return preservedFile(err, file, cmd.Out())
}
if bytes.Equal(original, edited) {
if len(results.edit) > 0 {
preservedFile(nil, file, cmd.Out())
} else {
os.Remove(file)
}
fmt.Fprintln(cmd.Out(), "Edit cancelled, no changes made.")
return nil
}
if !lines {
if len(results.edit) > 0 {
preservedFile(nil, file, cmd.Out())
} else {
os.Remove(file)
}
fmt.Fprintln(cmd.Out(), "Edit cancelled, saved file was empty.")
return nil
}
results = editResults{
file: file,
}
// parse the edited file
updates, err := rmap.InfoForData(edited, "edited-file")
if err != nil {
results.header.reasons = append(results.header.reasons, editReason{
head: fmt.Sprintf("The edited file had a syntax error: %v", err),
})
continue
}
visitor := resource.NewFlattenListVisitor(updates, rmap)
// need to make sure the original namespace wasn't changed while editing
if err = visitor.Visit(resource.RequireNamespace(cmdNamespace)); err != nil {
return preservedFile(err, file, cmd.Out())
}
// attempt to calculate a delta for merging conflicts
delta, err := jsonmerge.NewDelta(original, edited)
if err != nil {
glog.V(4).Infof("Unable to calculate diff, no merge is possible: %v", err)
delta = nil
} else {
delta.AddPreconditions(jsonmerge.RequireKeyUnchanged("apiVersion"))
results.delta = delta
results.version = defaultVersion
}
err = visitor.Visit(func(info *resource.Info) error {
data, err := info.Mapping.Codec.Encode(info.Object)
if err != nil {
return err
}
updated, err := resource.NewHelper(info.Client, info.Mapping).Replace(info.Namespace, info.Name, false, data)
if err != nil {
fmt.Fprintln(cmd.Out(), results.AddError(err, info))
return nil
}
info.Refresh(updated, true)
fmt.Fprintf(out, "%s/%s\n", info.Mapping.Resource, info.Name)
return nil
})
if err != nil {
return preservedFile(err, file, cmd.Out())
}
if results.retryable > 0 {
fmt.Fprintf(cmd.Out(), "You can run `%s update -f %s` to try this update again.\n", fullName, file)
return errExit
}
if results.conflict > 0 {
fmt.Fprintf(cmd.Out(), "You must update your local resource version and run `%s update -f %s` to overwrite the remote changes.\n", fullName, file)
return errExit
}
if len(results.edit) == 0 {
if results.notfound == 0 {
os.Remove(file)
} else {
fmt.Fprintf(cmd.Out(), "The edits you made on deleted resources have been saved to %q\n", file)
}
return nil
}
// loop again and edit the remaining items
infos = results.edit
}
return nil
}
示例4: RunEdit
//.........这里部分代码省略.........
preservedFile(nil, file, out)
} else {
os.Remove(file)
}
fmt.Fprintln(out, "Edit cancelled, saved file was empty.")
continue
}
results = editResults{
file: file,
}
// parse the edited file
updates, err := resourceMapper.InfoForData(edited, "edited-file")
if err != nil {
return fmt.Errorf("The edited file had a syntax error: %v", err)
}
// put configuration annotation in "updates"
if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), updates, encoder); err != nil {
return preservedFile(err, file, out)
}
if cmdutil.ShouldRecord(cmd, updates) {
err = cmdutil.RecordChangeCause(updates.Object, f.Command())
if err != nil {
return err
}
}
// encode updates back to "edited" since we'll only generate patch from "edited"
if edited, err = runtime.Encode(encoder, updates.Object); err != nil {
return preservedFile(err, file, out)
}
visitor := resource.NewFlattenListVisitor(updates, resourceMapper)
// need to make sure the original namespace wasn't changed while editing
if err = visitor.Visit(resource.RequireNamespace(cmdNamespace)); err != nil {
return preservedFile(err, file, out)
}
// use strategic merge to create a patch
originalJS, err := yaml.ToJSON(original)
if err != nil {
return preservedFile(err, file, out)
}
editedJS, err := yaml.ToJSON(edited)
if err != nil {
return preservedFile(err, file, out)
}
patch, err := strategicpatch.CreateStrategicMergePatch(originalJS, editedJS, obj)
// TODO: change all jsonmerge to strategicpatch
// for checking preconditions
preconditions := []jsonmerge.PreconditionFunc{}
if err != nil {
glog.V(4).Infof("Unable to calculate diff, no merge is possible: %v", err)
return preservedFile(err, file, out)
} else {
preconditions = append(preconditions, jsonmerge.RequireKeyUnchanged("apiVersion"))
preconditions = append(preconditions, jsonmerge.RequireKeyUnchanged("kind"))
preconditions = append(preconditions, jsonmerge.RequireMetadataKeyUnchanged("name"))
results.version = defaultVersion
}
if hold, msg := jsonmerge.TestPreconditionsHold(patch, preconditions); !hold {
fmt.Fprintf(out, "error: %s", msg)
return preservedFile(nil, file, out)
示例5: RunEdit
//.........这里部分代码省略.........
glog.V(4).Infof("User edited:\n%s", string(edited))
// Compare content without comments
if bytes.Equal(stripComments(original), stripComments(edited)) {
os.Remove(file)
fmt.Fprintln(errOut, "Edit cancelled, no changes made.")
return nil
}
lines, err := hasLines(bytes.NewBuffer(edited))
if err != nil {
return preservedFile(err, file, errOut)
}
if !lines {
os.Remove(file)
fmt.Fprintln(errOut, "Edit cancelled, saved file was empty.")
return nil
}
results = editResults{
file: file,
}
// parse the edited file
updates, err := resourceMapper.InfoForData(edited, "edited-file")
if err != nil {
// syntax error
containsError = true
results.header.reasons = append(results.header.reasons, editReason{head: fmt.Sprintf("The edited file had a syntax error: %v", err)})
continue
}
// not a syntax error as it turns out...
containsError = false
namespaceVisitor := resource.NewFlattenListVisitor(updates, resourceMapper)
// need to make sure the original namespace wasn't changed while editing
if err = namespaceVisitor.Visit(resource.RequireNamespace(cmdNamespace)); err != nil {
return preservedFile(err, file, errOut)
}
mutatedObjects := []runtime.Object{}
annotationVisitor := resource.NewFlattenListVisitor(updates, resourceMapper)
// iterate through all items to apply annotations
if err = annotationVisitor.Visit(func(info *resource.Info, incomingErr error) error {
// put configuration annotation in "updates"
if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info, encoder); err != nil {
return err
}
if cmdutil.ShouldRecord(cmd, info) {
if err := cmdutil.RecordChangeCause(info.Object, f.Command()); err != nil {
return err
}
}
mutatedObjects = append(mutatedObjects, info.Object)
return nil
}); err != nil {
return preservedFile(err, file, errOut)
}
// if we mutated a list in the visitor, persist the changes on the overall object
if meta.IsListType(updates.Object) {
meta.SetList(updates.Object, mutatedObjects)
}
patchVisitor := resource.NewFlattenListVisitor(updates, resourceMapper)
示例6: RunEdit
//.........这里部分代码省略.........
continue outter
}
results = editResults{
file: file,
}
// parse the edited file
updates, err := resourceMapper.InfoForData(edited, "edited-file")
if err != nil {
// syntax error
containsError = true
results.header.reasons = append(results.header.reasons, editReason{head: fmt.Sprintf("The edited file had a syntax error: %v", err)})
continue
}
// not a syntax error as it turns out...
containsError = false
// put configuration annotation in "updates"
if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), updates, encoder); err != nil {
return preservedFile(err, file, errOut)
}
if cmdutil.ShouldRecord(cmd, updates) {
err = cmdutil.RecordChangeCause(updates.Object, f.Command())
if err != nil {
return err
}
}
editedCopy := edited
if editedCopy, err = runtime.Encode(encoder, updates.Object); err != nil {
return preservedFile(err, file, errOut)
}
visitor := resource.NewFlattenListVisitor(updates, resourceMapper)
// need to make sure the original namespace wasn't changed while editing
if err = visitor.Visit(resource.RequireNamespace(cmdNamespace)); err != nil {
return preservedFile(err, file, errOut)
}
// use strategic merge to create a patch
originalJS, err := yaml.ToJSON(original)
if err != nil {
return preservedFile(err, file, errOut)
}
editedJS, err := yaml.ToJSON(editedCopy)
if err != nil {
return preservedFile(err, file, errOut)
}
patch, err := strategicpatch.CreateStrategicMergePatch(originalJS, editedJS, obj)
// TODO: change all jsonmerge to strategicpatch
// for checking preconditions
preconditions := []jsonmerge.PreconditionFunc{}
if err != nil {
glog.V(4).Infof("Unable to calculate diff, no merge is possible: %v", err)
return preservedFile(err, file, errOut)
} else {
preconditions = append(preconditions, jsonmerge.RequireKeyUnchanged("apiVersion"))
preconditions = append(preconditions, jsonmerge.RequireKeyUnchanged("kind"))
preconditions = append(preconditions, jsonmerge.RequireMetadataKeyUnchanged("name"))
results.version = defaultVersion
}
if hold, msg := jsonmerge.TestPreconditionsHold(patch, preconditions); !hold {
fmt.Fprintf(errOut, "error: %s\n", msg)
return preservedFile(nil, file, errOut)
示例7: RunEdit
// RunEdit contains all the necessary functionality for the OpenShift cli edit command.
func (o *EditOptions) RunEdit() error {
r := o.builder.Flatten().Do()
results := editResults{}
infos, err := r.Infos()
if err != nil {
return err
}
for {
obj, err := resource.AsVersionedObject(infos, false, o.version)
if err != nil {
return preservedFile(err, results.file, o.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, o.out)
}
if err := o.printer.PrintObj(obj, buf); err != nil {
return preservedFile(err, results.file, o.out)
}
original := buf.Bytes()
// launch the editor
edit := editor.NewDefaultEditor()
edited, file, err := edit.LaunchTempFile("oc-edit-", o.ext, buf)
if err != nil {
return preservedFile(err, results.file, o.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))
lines, err := hasLines(bytes.NewBuffer(edited))
if err != nil {
return preservedFile(err, file, o.out)
}
if bytes.Equal(original, edited) {
if len(results.edit) > 0 {
preservedFile(nil, file, o.out)
} else {
os.Remove(file)
}
fmt.Fprintln(o.out, "Edit cancelled, no changes made.")
return nil
}
if !lines {
if len(results.edit) > 0 {
preservedFile(nil, file, o.out)
} else {
os.Remove(file)
}
fmt.Fprintln(o.out, "Edit cancelled, saved file was empty.")
return nil
}
results = editResults{
file: file,
}
// parse the edited file
updates, err := o.rmap.InfoForData(edited, "edited-file")
if err != nil {
results.header.reasons = append(results.header.reasons, editReason{
head: fmt.Sprintf("The edited file had a syntax error: %v", err),
})
continue
}
visitor := resource.NewFlattenListVisitor(updates, o.rmap)
// need to make sure the original namespace wasn't changed while editing
if err = visitor.Visit(resource.RequireNamespace(o.namespace)); err != nil {
return preservedFile(err, file, o.out)
}
// attempt to calculate a delta for merging conflicts
delta, err := jsonmerge.NewDelta(original, edited)
if err != nil {
glog.V(4).Infof("Unable to calculate diff, no merge is possible: %v", err)
delta = nil
} else {
delta.AddPreconditions(jsonmerge.RequireKeyUnchanged("apiVersion"))
results.delta = delta
results.version = o.version
}
err = visitor.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
data, err := info.Mapping.Codec.Encode(info.Object)
if err != nil {
//.........这里部分代码省略.........
示例8: visitToPatch
func visitToPatch(originalObj runtime.Object, updates *resource.Info, mapper meta.RESTMapper, resourceMapper *resource.Mapper, encoder runtime.Encoder, out, errOut io.Writer, defaultVersion unversioned.GroupVersion, results *editResults, file string) error {
patchVisitor := resource.NewFlattenListVisitor(updates, resourceMapper)
err := patchVisitor.Visit(func(info *resource.Info, incomingErr error) error {
currOriginalObj := originalObj
// if we're editing a list, then navigate the list to find the item that we're currently trying to edit
if meta.IsListType(originalObj) {
currOriginalObj = nil
editObjUID, err := meta.NewAccessor().UID(info.Object)
if err != nil {
return err
}
listItems, err := meta.ExtractList(originalObj)
if err != nil {
return err
}
// iterate through the list to find the item with the matching UID
for i := range listItems {
originalObjUID, err := meta.NewAccessor().UID(listItems[i])
if err != nil {
return err
}
if editObjUID == originalObjUID {
currOriginalObj = listItems[i]
break
}
}
if currOriginalObj == nil {
return fmt.Errorf("no original object found for %#v", info.Object)
}
}
originalSerialization, err := runtime.Encode(encoder, currOriginalObj)
if err != nil {
return err
}
editedSerialization, err := runtime.Encode(encoder, info.Object)
if err != nil {
return err
}
// compute the patch on a per-item basis
// use strategic merge to create a patch
originalJS, err := yaml.ToJSON(originalSerialization)
if err != nil {
return err
}
editedJS, err := yaml.ToJSON(editedSerialization)
if err != nil {
return err
}
if reflect.DeepEqual(originalJS, editedJS) {
// no edit, so just skip it.
cmdutil.PrintSuccess(mapper, false, out, info.Mapping.Resource, info.Name, false, "skipped")
return nil
}
preconditions := []strategicpatch.PreconditionFunc{strategicpatch.RequireKeyUnchanged("apiVersion"),
strategicpatch.RequireKeyUnchanged("kind"), strategicpatch.RequireMetadataKeyUnchanged("name")}
patch, err := strategicpatch.CreateTwoWayMergePatch(originalJS, editedJS, currOriginalObj, preconditions...)
if err != nil {
glog.V(4).Infof("Unable to calculate diff, no merge is possible: %v", err)
if strategicpatch.IsPreconditionFailed(err) {
return fmt.Errorf("%s", "At least one of apiVersion, kind and name was changed")
}
return err
}
results.version = defaultVersion
patched, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, api.StrategicMergePatchType, patch)
if err != nil {
fmt.Fprintln(out, results.addError(err, info))
return nil
}
info.Refresh(patched, true)
cmdutil.PrintSuccess(mapper, false, out, info.Mapping.Resource, info.Name, false, "edited")
return nil
})
return err
}
示例9: runEdit
//.........这里部分代码省略.........
}
err = schema.ValidateBytes(stripComments(edited))
if err != nil {
results = editResults{
file: file,
}
containsError = true
fmt.Fprintln(out, results.addError(errors.NewInvalid(api.Kind(""), "", field.ErrorList{field.Invalid(nil, "The edited file failed validation", fmt.Sprintf("%v", err))}), infos[0]))
continue
}
// Compare content without comments
if bytes.Equal(stripComments(original), stripComments(edited)) {
os.Remove(file)
fmt.Fprintln(errOut, "Edit cancelled, no changes made.")
return nil
}
lines, err := hasLines(bytes.NewBuffer(edited))
if err != nil {
return preservedFile(err, file, errOut)
}
if !lines {
os.Remove(file)
fmt.Fprintln(errOut, "Edit cancelled, saved file was empty.")
return nil
}
results = editResults{
file: file,
}
// parse the edited file
updates, err := resourceMapper.InfoForData(edited, "edited-file")
if err != nil {
// syntax error
containsError = true
results.header.reasons = append(results.header.reasons, editReason{head: fmt.Sprintf("The edited file had a syntax error: %v", err)})
continue
}
// not a syntax error as it turns out...
containsError = false
namespaceVisitor := resource.NewFlattenListVisitor(updates, resourceMapper)
// need to make sure the original namespace wasn't changed while editing
if err = namespaceVisitor.Visit(resource.RequireNamespace(cmdNamespace)); err != nil {
return preservedFile(err, file, errOut)
}
// iterate through all items to apply annotations
mutatedObjects, err := visitAnnotation(cmd, f, updates, resourceMapper, encoder)
if err != nil {
return preservedFile(err, file, errOut)
}
// if we mutated a list in the visitor, persist the changes on the overall object
if meta.IsListType(updates.Object) {
meta.SetList(updates.Object, mutatedObjects)
}
switch editMode {
case NormalEditMode:
err = visitToPatch(originalObj, updates, mapper, resourceMapper, encoder, out, errOut, defaultVersion, &results, file)
case EditBeforeCreateMode:
err = visitToCreate(updates, mapper, resourceMapper, out, errOut, defaultVersion, &results, file)
default:
err = fmt.Errorf("Not supported edit mode %q", editMode)
}
if err != nil {
return preservedFile(err, results.file, errOut)
}
// Handle all possible errors
//
// 1. retryable: propose kubectl replace -f
// 2. notfound: indicate the location of the saved configuration of the deleted resource
// 3. invalid: retry those on the spot by looping ie. reloading the editor
if results.retryable > 0 {
fmt.Fprintf(errOut, "You can run `%s replace -f %s` to try this update again.\n", filepath.Base(os.Args[0]), file)
return cmdutil.ErrExit
}
if results.notfound > 0 {
fmt.Fprintf(errOut, "The edits you made on deleted resources have been saved to %q\n", file)
return cmdutil.ErrExit
}
if len(results.edit) == 0 {
if results.notfound == 0 {
os.Remove(file)
} else {
fmt.Fprintf(out, "The edits you made on deleted resources have been saved to %q\n", file)
}
return nil
}
if len(results.header.reasons) > 0 {
containsError = true
}
}
}
示例10: doEdit
//.........这里部分代码省略.........
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,
}
// parse the edited file
updates, err := rmap.InfoForData(edited, "edited-file")
if err != nil {
return preservedFile(err, file, out)
}
visitor := resource.NewFlattenListVisitor(updates, rmap)
// need to make sure the original namespace wasn't changed while editing
if err := visitor.Visit(resource.RequireNamespace(cmdNamespace)); err != nil {
return preservedFile(err, file, out)
}
err = process(visitor, original, edited, obj, updates, file, &results, mapper, defaultVersion)
if err != nil {
return preservedFile(err, file, out)
}
if results.retryable > 0 {
fmt.Fprintf(out, "You can run `kubectl replace -f %s` to try this update again.\n", file)
return errExit
}
if results.conflict > 0 {
fmt.Fprintf(out, "You must update your local resource version and run `kubectl replace -f %s` to overwrite the remote changes.\n", file)
return errExit
}
if len(results.edit) == 0 {
if results.notfound == 0 {
os.Remove(file)
} else {
fmt.Fprintf(out, "The edits you made on deleted resources have been saved to %q\n", file)
}
return nil
}
// loop again and edit the remaining items
infos = results.edit
}
return nil
}