diff --git a/model/labelset.go b/model/labelset.go index 6eda08a7..9fc8632a 100644 --- a/model/labelset.go +++ b/model/labelset.go @@ -27,6 +27,15 @@ import ( // match. type LabelSet map[LabelName]LabelValue +// RemoveEmptyLabels removes labels that have empty values. +func (ls LabelSet) RemoveEmptyLabels() { + for k, v := range ls { + if string(v) == "" { + delete(ls, k) + } + } +} + // Validate checks whether all names and values in the label set // are valid. func (ls LabelSet) Validate() error { diff --git a/model/labelset_test.go b/model/labelset_test.go new file mode 100644 index 00000000..210392ad --- /dev/null +++ b/model/labelset_test.go @@ -0,0 +1,21 @@ +package model + +import "testing" + +func TestRemoveEmptyLabels(t *testing.T) { + ls := LabelSet{ + LabelName("one"): LabelValue("two"), + LabelName("three"): LabelValue("four"), + LabelName("five"): LabelValue(""), + } + + ls.RemoveEmptyLabels() + + if _, prs := ls["five"]; prs { + t.Errorf(`key "five" not removed from map`) + } + + if len(ls) != 2 { + t.Errorf("expected 2 keys in labelset; found %d:\n%v\n", len(ls), ls) + } +}