-
Notifications
You must be signed in to change notification settings - Fork 53
/
labels.go
89 lines (78 loc) · 2.23 KB
/
labels.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
81
82
83
84
85
86
87
88
89
package core
import (
"strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
type LabelSelectorOperator string
const (
LabelSelectorOpIn LabelSelectorOperator = "In"
LabelSelectorOpNotIn LabelSelectorOperator = "NotIn"
LabelSelectorOpExists LabelSelectorOperator = "Exists"
LabelSelectorOpDoesNotExist LabelSelectorOperator = "DoesNotExist"
NameLabel = "opni.io/name"
)
func (ls *LabelSelector) ExpressionString() string {
if ls == nil {
return ""
}
expressions := make([]string, 0, len(ls.MatchLabels)+len(ls.MatchExpressions))
for k, v := range ls.MatchLabels {
expressions = append(expressions, (&LabelSelectorRequirement{
Key: k,
Operator: string(LabelSelectorOpIn),
Values: []string{v},
}).ExpressionString())
}
for _, expr := range ls.MatchExpressions {
if expr == nil {
continue
}
expressions = append(expressions, expr.ExpressionString())
}
return strings.Join(expressions, " && ")
}
func (lsr *LabelSelectorRequirement) ExpressionString() string {
if lsr == nil {
return ""
}
switch lsr.Operator {
case string(LabelSelectorOpExists), string(LabelSelectorOpDoesNotExist):
return keyWithOperatorSymbol(lsr.Key, lsr.Operator)
default:
return keyWithOperatorSymbol(lsr.Key, lsr.Operator) + " {" + strings.Join(lsr.Values, ",") + "}"
}
}
func keyWithOperatorSymbol(key string, operator string) string {
switch LabelSelectorOperator(operator) {
case LabelSelectorOpIn:
return key + " ∈"
case LabelSelectorOpNotIn:
return key + " ∉"
case LabelSelectorOpExists:
return "∃ " + key
case LabelSelectorOpDoesNotExist:
return "∄ " + key
default:
return key + " ?"
}
}
func (ls *LabelSelector) ToLabelSelector() *metav1.LabelSelector {
if ls == nil {
return nil
}
s := &metav1.LabelSelector{
MatchLabels: ls.MatchLabels,
MatchExpressions: []metav1.LabelSelectorRequirement{},
}
for _, expr := range ls.MatchExpressions {
s.MatchExpressions = append(s.MatchExpressions, metav1.LabelSelectorRequirement{
Key: expr.Key,
Operator: metav1.LabelSelectorOperator(expr.Operator),
Values: expr.Values,
})
}
return s
}
func (ls *LabelSelector) IsEmpty() bool {
return ls == nil || (len(ls.MatchLabels) == 0 && len(ls.MatchExpressions) == 0)
}