From 1870ede745a932a69fc576e6fe878d15dc3cfcfa Mon Sep 17 00:00:00 2001 From: Akihiro Suda Date: Mon, 1 Nov 2021 14:38:49 +0900 Subject: [PATCH] Allow `--format=json` as an alias of `--format={{json .}}` Signed-off-by: Akihiro Suda --- templates/templates.go | 8 ++++++++ templates/templates_test.go | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/templates/templates.go b/templates/templates.go index 0e8dd1536874..d75a65095b90 100644 --- a/templates/templates.go +++ b/templates/templates.go @@ -61,6 +61,11 @@ var HeaderFunctions = template.FuncMap{ }, } +// aliases for convenience +var aliases = map[string]string{ + "json": "{{json .}}", +} + // Parse creates a new anonymous template with the basic functions // and parses the given format. func Parse(format string) (*template.Template, error) { @@ -76,6 +81,9 @@ func New(tag string) *template.Template { // NewParse creates a new tagged template with the basic functions // and parses the given format. func NewParse(tag, format string) (*template.Template, error) { + if alias, ok := aliases[format]; ok { + format = alias + } return New(tag).Parse(format) } diff --git a/templates/templates_test.go b/templates/templates_test.go index de71ef610c3c..0a83610eb6d1 100644 --- a/templates/templates_test.go +++ b/templates/templates_test.go @@ -39,6 +39,26 @@ func TestNewParse(t *testing.T) { assert.Check(t, is.Equal(want, b.String())) } +func TestParseJSON(t *testing.T) { + f := func(t testing.TB, format string) { + tm, err := Parse(format) + assert.NilError(t, err) + var b bytes.Buffer + m := map[string]int{ + "foo": 42, + } + assert.NilError(t, tm.Execute(&b, m)) + want := `{"foo":42}` + assert.Check(t, is.Equal(want, b.String())) + } + t.Run("CanonicalForm", func(t *testing.T) { + f(t, "{{json .}}") + }) + t.Run("ConvenienceForm", func(t *testing.T) { + f(t, "json") + }) +} + func TestParseTruncateFunction(t *testing.T) { source := "tupx5xzf6hvsrhnruz5cr8gwp"