-
Notifications
You must be signed in to change notification settings - Fork 0
/
duration.go
138 lines (110 loc) · 2.22 KB
/
duration.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package restic
import (
"fmt"
"strconv"
"strings"
"unicode"
"github.com/konidev20/rapi/internal/errors"
)
// Duration is similar to time.Duration, except it only supports larger ranges
// like hours, days, months, and years.
type Duration struct {
Hours, Days, Months, Years int
}
func (d Duration) String() string {
var s string
if d.Years != 0 {
s += fmt.Sprintf("%dy", d.Years)
}
if d.Months != 0 {
s += fmt.Sprintf("%dm", d.Months)
}
if d.Days != 0 {
s += fmt.Sprintf("%dd", d.Days)
}
if d.Hours != 0 {
s += fmt.Sprintf("%dh", d.Hours)
}
return s
}
func nextNumber(input string) (num int, rest string, err error) {
if len(input) == 0 {
return 0, "", nil
}
var (
n string
negative bool
)
if input[0] == '-' {
negative = true
input = input[1:]
}
for i, s := range input {
if !unicode.IsNumber(s) {
rest = input[i:]
break
}
n += string(s)
}
if len(n) == 0 {
return 0, input, errors.New("no number found")
}
num, err = strconv.Atoi(n)
if err != nil {
panic(err)
}
if negative {
num = -num
}
return num, rest, nil
}
// ParseDuration parses a duration from a string. The format is `6y5m234d37h`
func ParseDuration(s string) (Duration, error) {
var (
d Duration
num int
err error
)
s = strings.TrimSpace(s)
for s != "" {
num, s, err = nextNumber(s)
if err != nil {
return Duration{}, err
}
if len(s) == 0 {
return Duration{}, errors.Errorf("no unit found after number %d", num)
}
switch s[0] {
case 'y':
d.Years = num
case 'm':
d.Months = num
case 'd':
d.Days = num
case 'h':
d.Hours = num
default:
return Duration{}, errors.Errorf("invalid unit %q found after number %d", s[0], num)
}
s = s[1:]
}
return d, nil
}
// Set calls ParseDuration and updates d.
func (d *Duration) Set(s string) error {
v, err := ParseDuration(s)
if err != nil {
return err
}
*d = v
return nil
}
// Type returns the type of Duration, usable within github.com/spf13/pflag and
// in help texts.
func (d Duration) Type() string {
return "duration"
}
// Zero returns true if the duration is empty (all values are set to zero).
func (d Duration) Zero() bool {
return d.Years == 0 && d.Months == 0 && d.Days == 0 && d.Hours == 0
}