1
0
mirror of https://github.com/docker/cli.git synced 2026-01-06 05:41:44 +03:00

templates: add formatJSON func

Move the function used to format as JSON to a separate function instead
of definining it inline.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn
2025-04-18 00:27:31 +02:00
parent be97096566
commit c24b62f19c

View File

@@ -13,18 +13,7 @@ import (
// basicFunctions are the set of initial
// functions provided to every template.
var basicFunctions = template.FuncMap{
"json": func(v any) string {
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
err := enc.Encode(v)
if err != nil {
panic(err)
}
// Remove the trailing new line added by the encoder
return strings.TrimSpace(buf.String())
},
"json": formatJSON,
"split": strings.Split,
"join": strings.Join,
"title": strings.Title, //nolint:nolintlint,staticcheck // strings.Title is deprecated, but we only use it for ASCII, so replacing with golang.org/x/text is out of scope
@@ -103,3 +92,16 @@ func truncateWithLength(source string, length int) string {
}
return source[:length]
}
func formatJSON(v any) string {
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
err := enc.Encode(v)
if err != nil {
panic(err)
}
// Remove the trailing new line added by the encoder
return strings.TrimSpace(buf.String())
}