set.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. Copyright 2019 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package yaml
  14. import (
  15. "fmt"
  16. "gopkg.in/yaml.v3"
  17. )
  18. // SetNode sets the given path to the given yaml Node, creating mapping nodes along the way.
  19. func SetNode(root *yaml.Node, val yaml.Node, path ...string) error {
  20. currNode, path, err := asCloseAsPossible(root, path...)
  21. if err != nil {
  22. return err
  23. }
  24. if len(path) > 0 {
  25. if currNode.Kind != yaml.MappingNode {
  26. return fmt.Errorf("unexpected non-mapping before path %v", path)
  27. }
  28. for ; len(path) > 0; path = path[1:] {
  29. keyNode := yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Style: yaml.DoubleQuotedStyle, Value: path[0]}
  30. nextNode := &yaml.Node{Kind: yaml.MappingNode}
  31. currNode.Content = append(currNode.Content, &keyNode, nextNode)
  32. currNode = nextNode
  33. }
  34. }
  35. *currNode = val
  36. return nil
  37. }
  38. // DeleteNode deletes the node at the given path in the given tree of mapping nodes.
  39. // It's a noop if the path doesn't exist.
  40. func DeleteNode(root *yaml.Node, path ...string) error {
  41. if len(path) == 0 {
  42. return fmt.Errorf("must specify a path to delete")
  43. }
  44. pathToParent, keyToDelete := path[:len(path)-1], path[len(path)-1]
  45. parentNode, path, err := asCloseAsPossible(root, pathToParent...)
  46. if err != nil {
  47. return err
  48. }
  49. if len(path) > 0 {
  50. // no-op, parent node doesn't exist
  51. return nil
  52. }
  53. if parentNode.Kind != yaml.MappingNode {
  54. return fmt.Errorf("unexpected non-mapping node")
  55. }
  56. for i := 0; i < len(parentNode.Content)/2; i++ {
  57. keyNode := parentNode.Content[i*2]
  58. if keyNode.Value == keyToDelete {
  59. parentNode.Content = append(parentNode.Content[:i*2], parentNode.Content[i*2+2:]...)
  60. return nil
  61. }
  62. }
  63. // no-op, key not found in parent node
  64. return nil
  65. }