-
Notifications
You must be signed in to change notification settings - Fork 940
/
parseduration.go
91 lines (73 loc) · 2.15 KB
/
parseduration.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
// Code duplicated directly from commands/util.go
package common
import (
"strconv"
"strings"
"time"
"unicode"
"emperror.dev/errors"
)
// Parses a time string like 1day3h
func ParseDuration(str string) (time.Duration, error) {
var dur time.Duration
currentNumBuf := ""
currentModifierBuf := ""
// Parse the time
for _, v := range str {
// Ignore whitespace
if unicode.Is(unicode.White_Space, v) {
continue
}
if unicode.IsNumber(v) {
// If we reached a number and the modifier was also set, parse the last duration component before starting a new one
if currentModifierBuf != "" {
if currentNumBuf == "" {
currentNumBuf = "1"
}
d, err := parseDurationComponent(currentNumBuf, currentModifierBuf)
if err != nil {
return d, err
}
dur += d
currentNumBuf = ""
currentModifierBuf = ""
}
currentNumBuf += string(v)
} else {
currentModifierBuf += string(v)
}
}
if currentNumBuf != "" {
d, err := parseDurationComponent(currentNumBuf, currentModifierBuf)
if err != nil {
return dur, errors.WrapIf(err, "not a duration")
}
dur += d
}
return dur, nil
}
func parseDurationComponent(numStr, modifierStr string) (time.Duration, error) {
parsedNum, err := strconv.ParseInt(numStr, 10, 64)
if err != nil {
return 0, err
}
parsedDur := time.Duration(parsedNum)
if strings.HasPrefix(modifierStr, "s") {
parsedDur = parsedDur * time.Second
} else if modifierStr == "" || (strings.HasPrefix(modifierStr, "m") && (len(modifierStr) < 2 || modifierStr[1] != 'o')) {
parsedDur = parsedDur * time.Minute
} else if strings.HasPrefix(modifierStr, "h") {
parsedDur = parsedDur * time.Hour
} else if strings.HasPrefix(modifierStr, "d") {
parsedDur = parsedDur * time.Hour * 24
} else if strings.HasPrefix(modifierStr, "w") {
parsedDur = parsedDur * time.Hour * 24 * 7
} else if strings.HasPrefix(modifierStr, "mo") {
parsedDur = parsedDur * time.Hour * 24 * 30
} else if strings.HasPrefix(modifierStr, "y") {
parsedDur = parsedDur * time.Hour * 24 * 365
} else {
return parsedDur, errors.New("couldn't figure out what '" + numStr + modifierStr + "` was")
}
return parsedDur, nil
}