From fc77c0e61aac40c4336f54d121909cd9547ceef5 Mon Sep 17 00:00:00 2001 From: Puneet Dixit <236133619+puneetdixit200@users.noreply.github.com> Date: Fri, 22 May 2026 12:28:49 +0530 Subject: [PATCH] Fix toYamlPretty integer output Signed-off-by: Puneet Dixit <236133619+puneetdixit200@users.noreply.github.com> --- pkg/engine/funcs.go | 33 ++++++++++++++++++++++++++++++++- pkg/engine/funcs_test.go | 4 ++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/pkg/engine/funcs.go b/pkg/engine/funcs.go index 431f82f63..af8b969e4 100644 --- a/pkg/engine/funcs.go +++ b/pkg/engine/funcs.go @@ -129,7 +129,7 @@ func toYAMLPretty(v any) string { var data bytes.Buffer encoder := goYaml.NewEncoder(&data) encoder.SetIndent(2) - err := encoder.Encode(v) + err := encoder.Encode(normalizeYAMLScalars(v)) if err != nil { // Swallow errors inside of a template. @@ -138,6 +138,37 @@ func toYAMLPretty(v any) string { return strings.TrimSuffix(data.String(), "\n") } +func normalizeYAMLScalars(v any) any { + switch typedValue := v.(type) { + case map[string]any: + normalized := make(map[string]any, len(typedValue)) + for key, value := range typedValue { + normalized[key] = normalizeYAMLScalars(value) + } + return normalized + case map[any]any: + normalized := make(map[any]any, len(typedValue)) + for key, value := range typedValue { + normalized[key] = normalizeYAMLScalars(value) + } + return normalized + case []any: + normalized := make([]any, len(typedValue)) + for index, value := range typedValue { + normalized[index] = normalizeYAMLScalars(value) + } + return normalized + case float64: + // sigs.k8s.io/yaml may unmarshal integer YAML values as float64. + if typedValue == math.Trunc(typedValue) && + typedValue > float64(math.MinInt64) && + typedValue < float64(math.MaxInt64) { + return int64(typedValue) + } + } + return v +} + // fromYAML converts a YAML document into a map[string]interface{}. // // This is not a general-purpose YAML parser, and will not parse all valid diff --git a/pkg/engine/funcs_test.go b/pkg/engine/funcs_test.go index cf6a8d5c9..66ffa334b 100644 --- a/pkg/engine/funcs_test.go +++ b/pkg/engine/funcs_test.go @@ -40,6 +40,10 @@ func TestFuncs(t *testing.T) { tpl: `{{ toYamlPretty . }}`, expect: "baz:\n - 1\n - 2\n - 3", vars: map[string]any{"baz": []int{1, 2, 3}}, + }, { + tpl: `{{ toYamlPretty (fromYaml .) }}`, + expect: "foo: 1000000", + vars: "foo: !!int 1000000", }, { tpl: `{{ toToml . }}`, expect: "foo = \"bar\"\n",