From 54b8ec50a45ae4b475f6432f5ba23d7c0101d6ca Mon Sep 17 00:00:00 2001 From: reginaldalfret Date: Mon, 19 Oct 2026 23:32:07 +0530 Subject: [PATCH] Fix implicit null converted to empty string in flow mappings --- formatters/basic/formatter_test.go | 14 +++++++------- pkg/yaml/emitterc.go | 4 ++-- pkg/yaml/node_test.go | 11 +++++++++++ 3 files changed, 20 insertions(+), 9 deletions(-) diff --git a/formatters/basic/formatter_test.go b/formatters/basic/formatter_test.go index 9ec0c880..c9b9641d 100644 --- a/formatters/basic/formatter_test.go +++ b/formatters/basic/formatter_test.go @@ -235,6 +235,11 @@ map: map: *a : 1`, }, + { + name: "retains implicit null in flow mapping", + input: `a: {b: }`, + expect: `a: {b:}`, + }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { @@ -397,12 +402,7 @@ func TestRetainLineBreaksLongLine(t *testing.T) { func stripTrailingNewline(s string) string { // strip trailing \n or \r\n characters - if len(s) > 0 { - if s[len(s)-1] == '\n' { - s = s[:len(s)-1] - } else if len(s) > 1 && s[len(s)-2] == '\r' { - s = s[:len(s)-2] - } - } + s = strings.TrimSuffix(s, "\r\n") + s = strings.TrimSuffix(s, "\n") return s } diff --git a/pkg/yaml/emitterc.go b/pkg/yaml/emitterc.go index 3a1aede9..e0b3201c 100644 --- a/pkg/yaml/emitterc.go +++ b/pkg/yaml/emitterc.go @@ -1056,7 +1056,7 @@ func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event emitter.flow_level == 0 && !emitter.scalar_data.block_plain_allowed { style = yaml_SINGLE_QUOTED_SCALAR_STYLE } - if len(emitter.scalar_data.value) == 0 && (emitter.flow_level > 0 || emitter.simple_key_context) { + if len(emitter.scalar_data.value) == 0 && emitter.simple_key_context { style = yaml_SINGLE_QUOTED_SCALAR_STYLE } if no_tag && !event.implicit { @@ -1312,7 +1312,7 @@ func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { if len(value) == 0 { emitter.scalar_data.multiline = false - emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.flow_plain_allowed = true emitter.scalar_data.block_plain_allowed = true emitter.scalar_data.single_quoted_allowed = true emitter.scalar_data.block_allowed = false diff --git a/pkg/yaml/node_test.go b/pkg/yaml/node_test.go index 24a1dcc6..5d722130 100644 --- a/pkg/yaml/node_test.go +++ b/pkg/yaml/node_test.go @@ -2856,6 +2856,17 @@ func (s *S) TestNodeOmitEmpty(c *C) { c.Assert(err, ErrorMatches, "yaml: cannot encode node with unknown kind 0") } +func (s *S) TestFlowMappingImplicitNull(c *C) { + input := "a: {b: }\n" + var n yaml.Node + err := yaml.Unmarshal([]byte(input), &n) + c.Assert(err, IsNil) + + data, err := yaml.Marshal(&n) + c.Assert(err, IsNil) + c.Assert(string(data), Equals, "a: {b:}\n") +} + func fprintComments(out io.Writer, node *yaml.Node, indent string) { switch node.Kind { case yaml.ScalarNode: