-
Notifications
You must be signed in to change notification settings - Fork 88
/
ttl.go
93 lines (83 loc) · 2.24 KB
/
ttl.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
90
91
92
93
package snapshot
import (
"fmt"
"regexp"
"strconv"
"strings"
"github.com/pkg/errors"
snapshottypes "github.com/replicatedhq/kots/pkg/kotsadmsnapshot/types"
)
var ttlMatch = regexp.MustCompile(`^\d+(s|m|h)$`)
func ParseTTL(s string) (*snapshottypes.ParsedTTL, error) {
parsedTTLResponse := &snapshottypes.ParsedTTL{}
matches := ttlMatch.FindStringSubmatch(s)
if len(matches) < 2 {
return nil, errors.New("Failed to get a valid match")
}
unit := matches[1]
quantity := strings.Split(ttlMatch.FindStringSubmatch(s)[0], unit)
quantityInt, err := strconv.ParseInt(quantity[0], 10, 64)
if err != nil {
return nil, errors.Wrap(err, "failed to parseInt quanitity")
}
switch unit {
case "s":
parsedTTLResponse.Quantity = quantityInt
parsedTTLResponse.Unit = "seconds"
break
case "m":
parsedTTLResponse.Quantity = quantityInt
parsedTTLResponse.Unit = "minutes"
break
case "h":
if quantityInt/8766 >= 1 && quantityInt%8766 == 0 {
parsedTTLResponse.Quantity = quantityInt / 8766
parsedTTLResponse.Unit = "years"
break
}
if quantityInt/720 >= 1 && quantityInt%720 == 0 {
parsedTTLResponse.Quantity = quantityInt / 720
parsedTTLResponse.Unit = "months"
break
}
if quantityInt/168 >= 1 && quantityInt%168 == 0 {
parsedTTLResponse.Quantity = quantityInt / 168
parsedTTLResponse.Unit = "weeks"
break
}
if quantityInt/24 >= 1 && quantityInt%24 == 0 {
parsedTTLResponse.Quantity = quantityInt / 24
parsedTTLResponse.Unit = "days"
break
}
parsedTTLResponse.Quantity = quantityInt
parsedTTLResponse.Unit = "hours"
break
default:
return nil, fmt.Errorf("unsupported unit type")
}
return parsedTTLResponse, nil
}
func FormatTTL(quantity string, unit string) (string, error) {
n, err := strconv.Atoi(quantity)
if err != nil {
return "", err
}
switch unit {
case "seconds":
return fmt.Sprintf("%ds", n), nil
case "minutes":
return fmt.Sprintf("%dm", n), nil
case "hours":
return fmt.Sprintf("%dh", n), nil
case "days":
return fmt.Sprintf("%dh", n*24), nil
case "weeks":
return fmt.Sprintf("%dh", n*168), nil
case "months":
return fmt.Sprintf("%dh", n*720), nil
case "years":
return fmt.Sprintf("%dh", n*8766), nil
}
return "", fmt.Errorf("Invalid snapshot TTL: %d %s", n, unit)
}