forked from raystack/optimus
-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.go
69 lines (58 loc) · 1.32 KB
/
parser.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
package duration
import (
"regexp"
"strconv"
"strings"
"github.com/goto/optimus/internal/errors"
)
var validationRegex = regexp.MustCompile(`^$|^None$|^-?\d+[hdwMy]$`)
func From(str string) (Duration, error) {
if str == "" || strings.EqualFold(str, "None") {
return Duration{
unit: None,
count: 0,
}, nil
}
unitIndex := len(str) - 1
unitStr := str[unitIndex:]
unit, err := UnitFrom(unitStr)
if err != nil {
return Duration{}, err
}
count, err := CountFrom(str[0:unitIndex])
if err != nil {
return Duration{}, err
}
return NewDuration(count, unit), nil
}
func Validate(str string) error {
if !validationRegex.MatchString(str) {
return errors.InvalidArgument("window", "invalid string for duration "+str)
}
return nil
}
func UnitFrom(u string) (Unit, error) {
switch u {
case string(None):
return None, nil
case string(Hour):
return Hour, nil
case string(Day):
return Day, nil
case string(Week):
return Week, nil
case string(Month):
return Month, nil
case string(Year):
return Year, nil
default:
return "", errors.InvalidArgument("window", "invalid value for unit "+u+", accepted values are [h,d,w,M,y]")
}
}
func CountFrom(c string) (int, error) {
v, err := strconv.Atoi(c)
if err != nil {
return 0, errors.InvalidArgument("window", "invalid value: "+err.Error())
}
return v, nil
}