@@ -102,6 +102,21 @@ func LoadDynamicYamlFromString(input string) (*DynamicYaml, error) {
102102 return dynamicYaml , nil
103103}
104104
105+ // SetTopComment sets the topmost comment in the resulting yaml
106+ func (d * DynamicYaml ) SetTopComment (comment string ) error {
107+ if d == nil {
108+ return nil
109+ }
110+
111+ if d .node == nil {
112+ return fmt .Errorf ("DynamicYaml has not been loaded yet" )
113+ }
114+
115+ d .node .HeadComment = comment
116+
117+ return nil
118+ }
119+
105120func (d * DynamicYaml ) GetByParts (parts ... string ) (key , value * yaml.Node ) {
106121 if len (d .node .Content ) == 0 {
107122 return nil , nil
@@ -608,9 +623,10 @@ func (d *DynamicYaml) mergeSingle(y *DynamicYaml) {
608623 valueNode := values .Content [i + 1 ]
609624
610625 alreadyExists := false
611- var jValue * yaml.Node = nil
626+ var jKey * yaml.Node
627+ var jValue * yaml.Node
612628 for j := 0 ; j < len (destination .Content )- 1 ; j ++ {
613- jKey : = destination .Content [j ]
629+ jKey = destination .Content [j ]
614630 jValue = destination .Content [j + 1 ]
615631
616632 if keyNode .Value == jKey .Value {
@@ -620,6 +636,14 @@ func (d *DynamicYaml) mergeSingle(y *DynamicYaml) {
620636 }
621637
622638 if alreadyExists {
639+ if jKey != nil {
640+ // Always replace the comments with the new comment values
641+ // This makes it less generic, but it makes the source YAML comments
642+ // always overwrite any custom yaml, which is the expected behavior.
643+ jKey .HeadComment = keyNode .HeadComment
644+ jKey .LineComment = keyNode .LineComment
645+ jKey .FootComment = keyNode .FootComment
646+ }
623647 mergeNodes (jValue , valueNode )
624648 } else {
625649 destination .Content = append (destination .Content , keyNode )
0 commit comments