From 11d0b57c977426908f2141f1eea33048abd14131 Mon Sep 17 00:00:00 2001 From: George Robinson Date: Wed, 22 Feb 2023 11:38:15 +0000 Subject: [PATCH] Implement Stringer interface for Pairs and KVs (#3256) This commit implements the Stringer interface for Pairs and KVs. It changes how Pairs are printed in templates from map[name1:value1 name2:value2] to name1=value1, name2=value2. KVs work similar, but are first sorted into pairs before being printed. Signed-off-by: George Robinson --- template/template.go | 17 +++++++++++++++++ template/template_test.go | 7 +++++++ 2 files changed, 24 insertions(+) diff --git a/template/template.go b/template/template.go index c7a6639f..4ad24f26 100644 --- a/template/template.go +++ b/template/template.go @@ -187,6 +187,19 @@ func (ps Pairs) Values() []string { return vs } +func (ps Pairs) String() string { + b := strings.Builder{} + for i, p := range ps { + b.WriteString(p.Name) + b.WriteRune('=') + b.WriteString(p.Value) + if i < len(ps)-1 { + b.WriteString(", ") + } + } + return b.String() +} + // KV is a set of key/value string pairs. type KV map[string]string @@ -239,6 +252,10 @@ func (kv KV) Values() []string { return kv.SortedPairs().Values() } +func (kv KV) String() string { + return kv.SortedPairs().String() +} + // Data is the data passed to notification templates and webhook pushes. // // End-users should not be exposed to Go's type system, as this will confuse them and prevent diff --git a/template/template_test.go b/template/template_test.go index 884e497b..03cbc45b 100644 --- a/template/template_test.go +++ b/template/template_test.go @@ -48,6 +48,13 @@ func TestPairValues(t *testing.T) { require.EqualValues(t, expected, pairs.Values()) } +func TestPairsString(t *testing.T) { + pairs := Pairs{{"name1", "value1"}} + require.Equal(t, "name1=value1", pairs.String()) + pairs = append(pairs, Pair{"name2", "value2"}) + require.Equal(t, "name1=value1, name2=value2", pairs.String()) +} + func TestKVSortedPairs(t *testing.T) { kv := KV{"d": "dVal", "b": "bVal", "c": "cVal"}