From 9907ef7e14ff171565162a9ee3942340f4232526 Mon Sep 17 00:00:00 2001 From: Tom Wright Date: Tue, 29 Aug 2023 16:24:48 +0100 Subject: [PATCH] Fix an issue that caused yaml strings to be read as numbers --- dencoding/yaml_encoder.go | 14 ++++++++++++-- internal/command/put_test.go | 9 +++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/dencoding/yaml_encoder.go b/dencoding/yaml_encoder.go index 586521d0..de9c45ff 100644 --- a/dencoding/yaml_encoder.go +++ b/dencoding/yaml_encoder.go @@ -4,6 +4,7 @@ import ( "github.com/tomwright/dasel/v2/util" "gopkg.in/yaml.v3" "io" + "strconv" ) // YAMLEncoder wraps a standard yaml encoder to implement custom ordering logic. @@ -104,8 +105,17 @@ func yamlSliceToNode(value []any) (*yaml.Node, error) { } func yamlScalarToNode(value any) (*yaml.Node, error) { - return &yaml.Node{ + res := &yaml.Node{ Kind: yaml.ScalarNode, Value: util.ToString(value), - }, nil + } + switch v := value.(type) { + case string: + // If the string can be evaluated as a number, quote it. + if _, err := strconv.ParseInt(v, 0, 64); err == nil { + res.Style = yaml.DoubleQuotedStyle + return res, nil + } + } + return res, nil } diff --git a/internal/command/put_test.go b/internal/command/put_test.go index 699d0474..da14bb38 100644 --- a/internal/command/put_test.go +++ b/internal/command/put_test.go @@ -163,4 +163,13 @@ func TestPutCommand(t *testing.T) { nil, nil, )) + + // https://github.com/TomWright/dasel/issues/327 + t.Run("Yaml0xStringQuoted", runTest( + []string{"put", "-r", "yaml", "-t", "string", "--pretty=false", "-v", "0x12_11", "t"}, + []byte(`t:`), + newline([]byte(`t: "0x12_11"`)), + nil, + nil, + )) }