This repository has been archived on 2023-11-25. You can view files and clone it, but cannot push or open issues or pull requests.
kreaper/reaper/types.go

60 lines
959 B
Go
Raw Normal View History

2022-04-13 12:34:27 +00:00
package reaper
import (
"errors"
"flag"
"strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2022-04-13 19:00:32 +00:00
"k8s.io/apimachinery/pkg/labels"
2022-04-13 12:34:27 +00:00
)
var ErrNotAVAlidTarget = errors.New("not a valid target")
var _ flag.Value = (*Target)(nil)
2022-04-13 19:00:32 +00:00
func ParseTarget(val string) (Target, error) {
t := Target(val)
if _, err := t.Selector(); err != nil {
return "", err
}
return t, nil
}
2022-04-13 12:34:27 +00:00
type Target string
2022-04-13 19:00:32 +00:00
func (t Target) Selector() (labels.Selector, error) {
2022-04-13 12:34:27 +00:00
s := string(t)
if s == "" {
return nil, ErrNotAVAlidTarget
}
key, val, found := strings.Cut(s, "=")
if !found {
return nil, ErrNotAVAlidTarget
}
2022-04-13 19:00:32 +00:00
sel := &metav1.LabelSelector{
2022-04-13 12:34:27 +00:00
MatchLabels: map[string]string{
key: val,
},
2022-04-13 19:00:32 +00:00
}
return metav1.LabelSelectorAsSelector(sel)
2022-04-13 12:34:27 +00:00
}
func (t Target) String() string {
return string(t)
}
func (t *Target) Set(s string) error {
2022-04-14 16:20:52 +00:00
tmp := Target(s)
if _, err := tmp.Selector(); err != nil {
return err
}
2022-04-13 12:34:27 +00:00
val := (*string)(t)
*val = s
return nil
}