feat(engine): add mustToToml template function

Add `mustToToml` that panics on marshal error, consistent with
`mustToYaml` and `mustToJson`. This makes it possible for chart authors
to get a hard failure when TOML serialization fails, rather than having
to inspect the output manually.

`toToml` behavior is unchanged in this commit.

Closes #31430

Signed-off-by: Ilya Kiselev <kis-ilya-a@yandex.ru>
pull/31957/head
Ilya Kiselev 4 months ago
parent 42f78ba60e
commit b075f7a35d

@ -50,6 +50,7 @@ func funcMap() template.FuncMap {
// Add some extra functionality
extra := template.FuncMap{
"toToml": toTOML,
"mustToToml": mustToTOML,
"fromToml": fromTOML,
"toYaml": toYAML,
"mustToYaml": mustToYAML,
@ -162,6 +163,21 @@ func toTOML(v any) string {
return b.String()
}
// mustToTOML takes an interface, marshals it to toml, and returns a string.
// It will panic if there is an error.
//
// This is designed to be called from a template when you need to ensure that the
// output TOML is valid.
func mustToTOML(v any) string {
b := bytes.NewBuffer(nil)
e := toml.NewEncoder(b)
err := e.Encode(v)
if err != nil {
panic(err)
}
return b.String()
}
// fromTOML converts a TOML document into a map[string]interface{}.
//
// This is not a general-purpose TOML parser, and will not parse all valid

@ -159,6 +159,13 @@ keyInElement1 = "valueInElement1"`,
tpl: `{{ toJson . }}`,
expect: "", // should return empty string and swallow error
vars: loopMap,
}, {
tpl: `{{ mustToToml . }}`,
vars: map[int]string{1: "one"}, // non-string key is invalid in TOML
}, {
tpl: `{{ mustToToml . }}`,
expect: "foo = \"bar\"\n", // should succeed and return TOML string
vars: map[string]string{"foo": "bar"},
},
}

Loading…
Cancel
Save