forked from grafana/loki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
labelset.go
80 lines (71 loc) · 1.58 KB
/
labelset.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package flagext
import (
"bytes"
"encoding/csv"
"fmt"
"strings"
"github.com/prometheus/common/model"
)
// LabelSet is a labelSet that can be used as a flag.
type LabelSet struct {
model.LabelSet `yaml:",inline"`
}
// String implements flag.Value
// Format: a=1,b=2
func (v LabelSet) String() string {
if v.LabelSet == nil {
return ""
}
records := make([]string, 0, len(v.LabelSet)>>1)
for k, v := range v.LabelSet {
records = append(records, string(k)+"="+string(v))
}
var buf bytes.Buffer
w := csv.NewWriter(&buf)
if err := w.Write(records); err != nil {
panic(err)
}
w.Flush()
return "[" + strings.TrimSpace(buf.String()) + "]"
}
// Set implements flag.Value
func (v *LabelSet) Set(s string) error {
var ss []string
n := strings.Count(s, "=")
switch n {
case 0:
return fmt.Errorf("%s must be formatted as key=value", s)
case 1:
ss = append(ss, strings.Trim(s, `"`))
default:
r := csv.NewReader(strings.NewReader(s))
var err error
ss, err = r.Read()
if err != nil {
return err
}
}
out := model.LabelSet{}
for _, pair := range ss {
kv := strings.SplitN(pair, "=", 2)
if len(kv) != 2 {
return fmt.Errorf("%s must be formatted as key=value", pair)
}
out[model.LabelName(kv[0])] = model.LabelValue(kv[1])
}
if err := out.Validate(); err != nil {
return err
}
v.LabelSet = out
return nil
}
// UnmarshalYAML the Unmarshaler interface of the yaml pkg.
func (v *LabelSet) UnmarshalYAML(unmarshal func(interface{}) error) error {
lbSet := model.LabelSet{}
err := unmarshal(&lbSet)
if err != nil {
return err
}
v.LabelSet = lbSet
return nil
}