From 77998d1bb3d80edbc9359c6f6d11100346045c23 Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Sun, 27 Nov 2022 17:58:37 +1100 Subject: [PATCH] XML Decoder: Fixed processing comments in empty XML #1446 --- pkg/yqlib/decoder_xml.go | 15 ++++++++++++--- pkg/yqlib/xml_test.go | 5 +++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/pkg/yqlib/decoder_xml.go b/pkg/yqlib/decoder_xml.go index ea32bcca3c8..c9eaf7cd5b1 100644 --- a/pkg/yqlib/decoder_xml.go +++ b/pkg/yqlib/decoder_xml.go @@ -58,6 +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") label := dec.prefs.ContentName labelNode := createScalarNode(label, label) labelNode.HeadComment = dec.processComment(n.HeadComment) @@ -87,13 +88,21 @@ func (dec *xmlDecoder) createMap(n *xmlNode) (*yaml.Node, error) { return nil, err } } else { + log.Debug("before hack, this is the data len: %", len(children[0].Data)) // comment hack for maps of scalars // if the value is a scalar, the head comment of the scalar needs to go on the key? // add tests for as well as multiple of inputXmlWithComments > yaml if len(children[0].Children) == 0 && children[0].HeadComment != "" { - log.Debug("scalar comment hack") - labelNode.HeadComment = labelNode.HeadComment + "\n" + strings.TrimSpace(children[0].HeadComment) - children[0].HeadComment = "" + if len(children[0].Data) > 0 { + + log.Debug("scalar comment hack") + labelNode.HeadComment = labelNode.HeadComment + "\n" + strings.TrimSpace(children[0].HeadComment) + children[0].HeadComment = "" + } else { + // child is null, put the headComment as a linecomment for reasons + children[0].LineComment = children[0].HeadComment + children[0].HeadComment = "" + } } valueNode, err = dec.convertToYamlNode(children[0]) if err != nil { diff --git a/pkg/yqlib/xml_test.go b/pkg/yqlib/xml_test.go index 0da5baffa70..462bffae780 100644 --- a/pkg/yqlib/xml_test.go +++ b/pkg/yqlib/xml_test.go @@ -249,6 +249,11 @@ var xmlScenarios = []formatScenario{ input: " value", expected: "\n# comment\nroot: value\n", //needs fix }, + { + skipDoc: true, + input: " ", + expected: "root: # comment\n", + }, { skipDoc: true, input: "valueanotherValue ",