From 48d00f807e2baecd2d4014c4646a8de285e663fb Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Sat, 17 Dec 2022 10:27:07 +1100 Subject: [PATCH] Fixed xml comment in array of scalars #1465 --- pkg/yqlib/decoder_xml.go | 14 ++++++++++---- pkg/yqlib/xml_test.go | 5 +++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/pkg/yqlib/decoder_xml.go b/pkg/yqlib/decoder_xml.go index 79c8b922089..ac70e403d3d 100644 --- a/pkg/yqlib/decoder_xml.go +++ b/pkg/yqlib/decoder_xml.go @@ -58,7 +58,7 @@ func (dec *xmlDecoder) createMap(n *xmlNode) (*yaml.Node, error) { yamlNode := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"} if len(n.Data) > 0 { - log.Debug("creating content node for map") + log.Debugf("creating content node for map: %v", dec.prefs.ContentName) label := dec.prefs.ContentName labelNode := createScalarNode(label, label) labelNode.HeadComment = dec.processComment(n.HeadComment) @@ -78,7 +78,7 @@ func (dec *xmlDecoder) createMap(n *xmlNode) (*yaml.Node, error) { labelNode.HeadComment = dec.processComment(n.HeadComment) } - + log.Debugf("label=%v, i=%v, keyValuePair.FootComment: %v", label, i, keyValuePair.FootComment) labelNode.FootComment = dec.processComment(keyValuePair.FootComment) log.Debug("len of children in %v is %v", label, len(children)) @@ -337,8 +337,14 @@ func applyFootComment(elem *element, commentStr string) { if len(elem.n.Children) > 0 { lastChildIndex := len(elem.n.Children) - 1 childKv := elem.n.Children[lastChildIndex] - log.Debug("got a foot comment for %v: [%v]", childKv.K, commentStr) - childKv.FootComment = joinComments([]string{elem.n.FootComment, commentStr}, " ") + log.Debug("got a foot comment, putting on last child for %v: [%v]", childKv.K, commentStr) + // if it's an array of scalars, put the foot comment on the scalar itself + if len(childKv.V) > 0 && len(childKv.V[0].Children) == 0 { + nodeToUpdate := childKv.V[len(childKv.V)-1] + nodeToUpdate.FootComment = joinComments([]string{nodeToUpdate.FootComment, commentStr}, " ") + } else { + childKv.FootComment = joinComments([]string{elem.n.FootComment, commentStr}, " ") + } } else { log.Debug("got a foot comment for %v: [%v]", elem.label, commentStr) elem.n.FootComment = joinComments([]string{elem.n.FootComment, commentStr}, " ") diff --git a/pkg/yqlib/xml_test.go b/pkg/yqlib/xml_test.go index 042cf244cd1..2e9badf47b5 100644 --- a/pkg/yqlib/xml_test.go +++ b/pkg/yqlib/xml_test.go @@ -259,6 +259,11 @@ var xmlScenarios = []formatScenario{ input: "valueanotherValue ", expected: "root:\n # comment\n - value\n - anotherValue\n", }, + { + skipDoc: true, + input: "quicksoftsquishy", + expected: "root:\n cats:\n cat:\n - quick\n - soft\n # kitty_comment\n\n - squishy\n", + }, { description: "Parse xml: simple", subdescription: "Notice how all the values are strings, see the next example on how you can fix that.",