2023-05-10 14:31:27 +02:00
|
|
|
package yaml_utils
|
|
|
|
|
|
|
|
import (
|
2023-06-08 08:45:07 +02:00
|
|
|
"errors"
|
2023-05-10 14:31:27 +02:00
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"gopkg.in/yaml.v3"
|
|
|
|
)
|
|
|
|
|
|
|
|
// takes a yaml document in bytes, a path to a key, and a value to set. The value must be a scalar.
|
2023-06-08 08:38:46 +02:00
|
|
|
func UpdateYamlValue(yamlBytes []byte, path []string, value string) ([]byte, error) {
|
2023-05-10 14:31:27 +02:00
|
|
|
// Parse the YAML file.
|
|
|
|
var node yaml.Node
|
|
|
|
err := yaml.Unmarshal(yamlBytes, &node)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to parse YAML: %w", err)
|
|
|
|
}
|
|
|
|
|
2023-06-08 08:36:13 +02:00
|
|
|
// Empty document: need to create the top-level map ourselves
|
|
|
|
if len(node.Content) == 0 {
|
|
|
|
node.Content = append(node.Content, &yaml.Node{
|
|
|
|
Kind: yaml.MappingNode,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-05-10 14:31:27 +02:00
|
|
|
body := node.Content[0]
|
|
|
|
|
2023-06-08 08:45:07 +02:00
|
|
|
if body.Kind != yaml.MappingNode {
|
|
|
|
return yamlBytes, errors.New("yaml document is not a dictionary")
|
|
|
|
}
|
|
|
|
|
2023-06-08 09:00:31 +02:00
|
|
|
if err := updateYamlNode(body, path, value); err != nil {
|
|
|
|
return yamlBytes, err
|
|
|
|
}
|
2023-05-10 14:31:27 +02:00
|
|
|
|
|
|
|
// Convert the updated YAML node back to YAML bytes.
|
|
|
|
updatedYAMLBytes, err := yaml.Marshal(body)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to convert YAML node to bytes: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return updatedYAMLBytes, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Recursive function to update the YAML node.
|
2023-06-08 09:00:31 +02:00
|
|
|
func updateYamlNode(node *yaml.Node, path []string, value string) error {
|
2023-05-10 14:31:27 +02:00
|
|
|
if len(path) == 0 {
|
2023-06-08 09:00:31 +02:00
|
|
|
if node.Kind != yaml.ScalarNode {
|
|
|
|
return errors.New("yaml node is not a scalar")
|
|
|
|
}
|
2023-05-10 14:31:27 +02:00
|
|
|
node.Value = value
|
2023-06-08 09:00:31 +02:00
|
|
|
return nil
|
2023-05-10 14:31:27 +02:00
|
|
|
}
|
|
|
|
|
2023-06-08 09:09:59 +02:00
|
|
|
if node.Kind != yaml.MappingNode {
|
|
|
|
return errors.New("yaml node in path is not a dictionary")
|
|
|
|
}
|
|
|
|
|
2023-05-10 14:31:27 +02:00
|
|
|
key := path[0]
|
|
|
|
for i := 0; i < len(node.Content)-1; i += 2 {
|
|
|
|
if node.Content[i].Value == key {
|
2023-06-08 09:00:31 +02:00
|
|
|
return updateYamlNode(node.Content[i+1], path[1:], value)
|
2023-05-10 14:31:27 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// if the key doesn't exist, we'll add it
|
|
|
|
node.Content = append(node.Content, &yaml.Node{
|
|
|
|
Kind: yaml.ScalarNode,
|
|
|
|
Value: key,
|
|
|
|
}, &yaml.Node{
|
|
|
|
Kind: yaml.ScalarNode,
|
|
|
|
Value: value,
|
|
|
|
})
|
2023-06-08 09:00:31 +02:00
|
|
|
return nil
|
2023-05-10 14:31:27 +02:00
|
|
|
}
|