Use literal block scalar style for exporting multiline content

This commit is contained in:
Prathamesh Musale 2025-12-11 13:07:49 +05:30
parent e5e0d5e117
commit e6b323eedb

View File

@ -591,6 +591,24 @@ func removeEmptyInterfaces(obj interface{}) interface{} {
}
// Convert JSON to YAML.
// setLiteralStyleForMultilineStrings walks through a yaml.Node tree and sets
// multiline strings to use literal style (|) for better readability
func setLiteralStyleForMultilineStrings(node *yaml.Node) {
if node == nil {
return
}
// If this is a scalar string node with newlines, use literal style
if node.Kind == yaml.ScalarNode && node.Tag == "!!str" && strings.Contains(node.Value, "\n") {
node.Style = yaml.LiteralStyle // Use | for multiline strings
}
// Recursively process child nodes
for _, child := range node.Content {
setLiteralStyleForMultilineStrings(child)
}
}
func jsonToYaml(j []byte, spaces int) ([]byte, error) {
// Convert the JSON to an object.
var jsonObj interface{}
@ -604,10 +622,20 @@ func jsonToYaml(j []byte, spaces int) ([]byte, error) {
return nil, err
}
jsonObj = removeEmptyInterfaces(jsonObj)
// Create a yaml.Node to have control over string styles
var node yaml.Node
if err := node.Encode(jsonObj); err != nil {
return nil, err
}
// Set literal style for multiline strings (e.g., ConfigMap data)
setLiteralStyleForMultilineStrings(&node)
var b bytes.Buffer
encoder := yaml.NewEncoder(&b)
encoder.SetIndent(spaces)
if err := encoder.Encode(jsonObj); err != nil {
if err := encoder.Encode(&node); err != nil {
return nil, err
}
return b.Bytes(), nil