Skip to content

Commit 1870ede

Browse files
committed
Allow --format=json as an alias of --format={{json .}}
Signed-off-by: Akihiro Suda <[email protected]>
1 parent e57b5f7 commit 1870ede

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

templates/templates.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,11 @@ var HeaderFunctions = template.FuncMap{
6161
},
6262
}
6363

64+
// aliases for convenience
65+
var aliases = map[string]string{
66+
"json": "{{json .}}",
67+
}
68+
6469
// Parse creates a new anonymous template with the basic functions
6570
// and parses the given format.
6671
func Parse(format string) (*template.Template, error) {
@@ -76,6 +81,9 @@ func New(tag string) *template.Template {
7681
// NewParse creates a new tagged template with the basic functions
7782
// and parses the given format.
7883
func NewParse(tag, format string) (*template.Template, error) {
84+
if alias, ok := aliases[format]; ok {
85+
format = alias
86+
}
7987
return New(tag).Parse(format)
8088
}
8189

templates/templates_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,26 @@ func TestNewParse(t *testing.T) {
3939
assert.Check(t, is.Equal(want, b.String()))
4040
}
4141

42+
func TestParseJSON(t *testing.T) {
43+
f := func(t testing.TB, format string) {
44+
tm, err := Parse(format)
45+
assert.NilError(t, err)
46+
var b bytes.Buffer
47+
m := map[string]int{
48+
"foo": 42,
49+
}
50+
assert.NilError(t, tm.Execute(&b, m))
51+
want := `{"foo":42}`
52+
assert.Check(t, is.Equal(want, b.String()))
53+
}
54+
t.Run("CanonicalForm", func(t *testing.T) {
55+
f(t, "{{json .}}")
56+
})
57+
t.Run("ConvenienceForm", func(t *testing.T) {
58+
f(t, "json")
59+
})
60+
}
61+
4262
func TestParseTruncateFunction(t *testing.T) {
4363
source := "tupx5xzf6hvsrhnruz5cr8gwp"
4464

0 commit comments

Comments
 (0)