From 8b7de70d1ee855c36e5cb63353ee069722bb5352 Mon Sep 17 00:00:00 2001 From: tison Date: Tue, 28 Oct 2025 22:48:37 +0800 Subject: [PATCH] Add mustToTOML template functions and let toTOML return empty string on error Signed-off-by: tison --- pkg/engine/funcs.go | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/pkg/engine/funcs.go b/pkg/engine/funcs.go index a97f8f104..bc3d3f54a 100644 --- a/pkg/engine/funcs.go +++ b/pkg/engine/funcs.go @@ -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, @@ -155,9 +156,22 @@ func fromYAMLArray(str string) []interface{} { func toTOML(v interface{}) string { b := bytes.NewBuffer(nil) e := toml.NewEncoder(b) - err := e.Encode(v) - if err != nil { - return err.Error() + if err := e.Encode(v); err != nil { + return "" + } + 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 need to ensure that the +// output TOML is valid. +func mustToTOML(v interface{}) string { + b := bytes.NewBuffer(nil) + e := toml.NewEncoder(b) + if err := e.Encode(v); err != nil { + panic(err) } return b.String() }