-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.go
71 lines (62 loc) · 1.8 KB
/
helpers.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
package main
import (
"strconv"
"strings"
"time"
log "github.com/sirupsen/logrus"
)
// BySchedule is a type for sorting by the schedule
type BySchedule []string
// parseDuration parses durations of days, weeks and months (in the most simplistic way)
// since time.ParseDuration only supports up to hours https://github.com/golang/go/issues/11473
// If there's a parsing error, return 0 and the error. Originally, this returned MAXINT64 and the
// error, but time.ParseDuration(foo) returns 0 on error and I wanted to stay consistent.
func parseDuration(d string) (time.Duration, error) {
switch {
case strings.HasSuffix(d, "d"):
t := strings.TrimSuffix(d, "d")
num, err := strconv.ParseInt(t, 10, 64)
if err != nil {
return time.Duration(0), err
}
return time.Duration(num*24) * time.Hour, nil
case strings.HasSuffix(d, "w"):
t := strings.TrimSuffix(d, "w")
num, err := strconv.ParseInt(t, 10, 64)
if err != nil {
return time.Duration(0), err
}
return time.Duration(num*7*24) * time.Hour, nil
case strings.HasSuffix(d, "mo"):
t := strings.TrimSuffix(d, "mo")
num, err := strconv.ParseInt(t, 10, 64)
if err != nil {
return time.Duration(0), err
}
return time.Duration(num*30*24) * time.Hour, nil
default:
return time.ParseDuration(d)
}
}
// Len is required to satisfy sort.Interface
func (s BySchedule) Len() int {
return len(s)
}
// Swap is required to satisfy sort.Interface
func (s BySchedule) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
// Less is required to satisfy sort.Interface
func (s BySchedule) Less(i, j int) bool {
di, err := parseDuration(s[i])
if err != nil {
log.Errorf("Failed to parse duration %s", s[i])
return false
}
dj, err := parseDuration(s[j])
if err != nil {
log.Errorf("Failed to parse duration %s", s[j])
return false
}
return di < dj
}