/
applyOn.go
75 lines (63 loc) · 1.58 KB
/
applyOn.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
package model
import (
"errors"
"fmt"
"strings"
)
const (
ApplyOnAlways = ApplyOn("always")
ApplyOnCreate = ApplyOn("create")
ApplyOnUpdate = ApplyOn("update")
ApplyOnNever = ApplyOn("never")
)
var (
ErrIllegalApplyOn = errors.New("illegal apply-on")
validApplyOnValues = map[ApplyOn]bool{ApplyOnAlways: true, ApplyOnCreate: true, ApplyOnUpdate: true, ApplyOnNever: true}
)
type ApplyOn string
func (instance *ApplyOn) Set(plain string) error {
return instance.UnmarshalText([]byte(plain))
}
func (instance ApplyOn) String() string {
if exist := validApplyOnValues[instance]; !exist {
return fmt.Sprintf("illegal-apply-on-%s", string(instance))
}
return string(instance)
}
func (instance ApplyOn) MarshalText() (text []byte, err error) {
if exist := validApplyOnValues[instance]; !exist {
return nil, fmt.Errorf("%w: %s", ErrIllegalApplyOn, string(instance))
}
return []byte(instance), nil
}
func (instance ApplyOn) OnUpdate() bool {
switch instance {
case ApplyOnUpdate, ApplyOnAlways:
return true
default:
return false
}
}
func (instance ApplyOn) OnCreate() bool {
switch instance {
case ApplyOnCreate, ApplyOnAlways:
return true
default:
return false
}
}
func (instance *ApplyOn) UnmarshalText(text []byte) error {
switch strings.ToLower(string(text)) {
case "true", "enabled", "on":
*instance = ApplyOnAlways
return nil
case "false", "disabled", "off":
*instance = ApplyOnNever
return nil
}
if exist := validApplyOnValues[ApplyOn(text)]; !exist {
return fmt.Errorf("%w: %s", ErrIllegalApplyOn, string(text))
}
*instance = ApplyOn(text)
return nil
}