Skip to content

Commit

Permalink
Implement Stringer interface for Pairs and KVs (prometheus#3256)
Browse files Browse the repository at this point in the history
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 <george.robinson@grafana.com>
  • Loading branch information
grobinson-grafana authored and radek-ryckowski committed Nov 6, 2023
1 parent 2a9c923 commit 8d2993c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
17 changes: 17 additions & 0 deletions template/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions template/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"}

Expand Down

0 comments on commit 8d2993c

Please sign in to comment.