-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathtime.go
More file actions
297 lines (247 loc) · 7.54 KB
/
time.go
File metadata and controls
297 lines (247 loc) · 7.54 KB
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package configtype
import (
"encoding/json"
"errors"
"fmt"
"math"
"regexp"
"strconv"
"time"
"github.com/invopop/jsonschema"
)
// Time is a wrapper around time.Time that should be used in config
// when a time type is required. We wrap the time.Time type so that
// the spec can be extended in the future to support other types of times
type Time struct {
input string
time time.Time
duration *timeDuration
hashNowFunc func() time.Time
}
func ParseTime(s string) (Time, error) {
var t Time
t.input = s
var err error
switch {
case timeNowRegexp.MatchString(s):
t.duration = new(timeDuration)
*t.duration = newTimeDuration(0)
case timeRFC3339Regexp.MatchString(s):
t.time, err = time.Parse(time.RFC3339, s)
case dateRegexp.MatchString(s):
t.time, err = time.Parse(time.DateOnly, s)
case baseDurationRegexp.MatchString(s), humanRelativeDurationRegexp.MatchString(s):
t.duration = new(timeDuration)
*t.duration, err = parseTimeDuration(s)
default:
return t, fmt.Errorf("invalid time format: %s", s)
}
return t, err
}
var (
timeRFC3339Pattern = `^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(.(\d{1,9}))?(Z|((-|\+)\d{2}:\d{2}))$`
timeRFC3339Regexp = regexp.MustCompile(timeRFC3339Pattern)
timeNowPattern = `^now$`
timeNowRegexp = regexp.MustCompile(timeNowPattern)
datePattern = `^\d{4}-\d{2}-\d{2}$`
dateRegexp = regexp.MustCompile(datePattern)
numberRegexp = regexp.MustCompile(`^[0-9]+$`)
baseDurationSegmentPattern = `[-+]?([0-9]*(\.[0-9]*)?[a-z]+)+` // copied from time.ParseDuration
baseDurationPattern = fmt.Sprintf(`^%s$`, baseDurationSegmentPattern)
baseDurationRegexp = regexp.MustCompile(baseDurationPattern)
humanDurationSignsPattern = `ago|from\s+now`
humanDurationUnitsPattern = `nanoseconds?|ns|microseconds?|us|µs|μs|milliseconds?|ms|seconds?|s|minutes?|m|hours?|h|days?|d|months?|M|years?|Y`
humanDurationUnitsRegex = regexp.MustCompile(fmt.Sprintf(`^%s$`, humanDurationUnitsPattern))
humanDurationSegmentPattern = fmt.Sprintf(`(([0-9]+\s+(%[1]s)|%[2]s))`, humanDurationUnitsPattern, baseDurationSegmentPattern)
humanRelativeDurationPattern = fmt.Sprintf(`^%[1]s(\s+%[1]s)*\s+(%[2]s)$`, humanDurationSegmentPattern, humanDurationSignsPattern)
humanRelativeDurationRegexp = regexp.MustCompile(humanRelativeDurationPattern)
whitespaceRegexp = regexp.MustCompile(`\s+`)
timePattern = patternCases(
timeNowPattern,
timeRFC3339Pattern,
datePattern,
baseDurationPattern,
humanRelativeDurationPattern,
)
)
func (Time) JSONSchema() *jsonschema.Schema {
return &jsonschema.Schema{
Type: "string",
Pattern: timePattern,
Title: "CloudQuery configtype.Time",
Description: "Allows for defining timestamps in both absolute(RFC3339) and relative formats. " +
"Absolute timestamp example: `2024-01-01T12:00:00+00:00`.\n" +
"Relative timestamps can take this format:\n" +
"- `now`\n" +
"- `x seconds [ago|from now]`\n" +
"- `x minutes [ago|from now]`\n" +
"- `x hours [ago|from now]`\n" +
"- `x days [ago|from now]`\n" +
"`until` field usage:\n" +
"- `until: now`\n" +
"- `until: 2 days ago`\n" +
"- `until: 10 months 3 days 4h20m from now`\n" +
"- `until: 2024-01-01T12:00:00+00:00`",
}
}
func (t *Time) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
tim, err := ParseTime(s)
if err != nil {
return err
}
*t = tim
return nil
}
func (t Time) MarshalJSON() ([]byte, error) {
return json.Marshal(t.input)
}
func (t Time) AsTime(now time.Time) time.Time {
if t.duration != nil {
sign := t.duration.sign
return now.Add(
t.duration.duration*time.Duration(sign),
).AddDate(
t.duration.years*sign,
t.duration.months*sign,
t.duration.days*sign,
)
}
return t.time
}
func (t Time) IsZero() bool {
return t.duration == nil && t.time.IsZero()
}
func (t Time) String() string {
return t.input
}
func (t Time) Hash() (uint64, error) {
nowFunc := t.hashNowFunc
if nowFunc == nil {
nowFunc = time.Now
}
at := t.AsTime(nowFunc())
return uint64(at.UnixNano()), nil
}
func (t *Time) SetHashNowFunc(f func() time.Time) {
t.hashNowFunc = f
}
type timeDuration struct {
input string
relative bool
sign int
duration time.Duration
days int
months int
years int
}
func newTimeDuration(d time.Duration) timeDuration {
return timeDuration{
input: d.String(),
sign: 1,
duration: d,
}
}
func parseTimeDuration(s string) (timeDuration, error) {
var d timeDuration
d.input = s
var inValue bool
var value int64
var inSign bool
parts := whitespaceRegexp.Split(s, -1)
var err error
for _, part := range parts {
switch {
case inSign:
if part != "now" {
return timeDuration{}, fmt.Errorf("invalid duration format: invalid sign specifier: %q", part)
}
d.sign = 1
inSign = false
case inValue:
if !humanDurationUnitsRegex.MatchString(part) {
return timeDuration{}, fmt.Errorf("invalid duration format: invalid unit specifier: %q", part)
}
err = d.addUnit(part, value)
if err != nil {
return timeDuration{}, fmt.Errorf("invalid duration format: %w", err)
}
value = 0
inValue = false
case part == "ago":
if d.sign != 0 {
return timeDuration{}, errors.New("invalid duration format: more than one sign specifier")
}
d.sign = -1
case part == "from":
if d.sign != 0 {
return timeDuration{}, errors.New("invalid duration format: more than one sign specifier")
}
inSign = true
case numberRegexp.MatchString(part):
value, err = strconv.ParseInt(part, 10, 64)
if err != nil {
return timeDuration{}, fmt.Errorf("invalid duration format: invalid value specifier: %q", part)
}
inValue = true
case baseDurationRegexp.MatchString(part):
duration, err := time.ParseDuration(part)
if err != nil {
return timeDuration{}, fmt.Errorf("invalid duration format: invalid value specifier: %q", part)
}
d.duration += duration
default:
return timeDuration{}, fmt.Errorf("invalid duration format: invalid value: %q", part)
}
}
d.relative = d.sign != 0
if !d.relative {
d.sign = 1
}
return d, nil
}
func (d *timeDuration) addUnit(unit string, number int64) error {
switch unit {
case "nanosecond", "nanoseconds", "ns":
d.duration += time.Nanosecond * time.Duration(number)
case "microsecond", "microseconds", "us", "μs", "µs":
d.duration += time.Microsecond * time.Duration(number)
case "millisecond", "milliseconds":
d.duration += time.Millisecond * time.Duration(number)
case "second", "seconds":
d.duration += time.Second * time.Duration(number)
case "minute", "minutes":
d.duration += time.Minute * time.Duration(number)
case "hour", "hours":
d.duration += time.Hour * time.Duration(number)
case "day", "days":
if number < math.MinInt || number > math.MaxInt {
return fmt.Errorf("invalid %s value: %d. Out of bounds", unit, number)
}
d.days += int(number)
case "month", "months":
if number < math.MinInt || number > math.MaxInt {
return fmt.Errorf("invalid %s value: %d. Out of bounds", unit, number)
}
d.months += int(number)
case "year", "years":
if number < math.MinInt || number > math.MaxInt {
return fmt.Errorf("invalid %s value: %d. Out of bounds", unit, number)
}
d.years += int(number)
default:
return fmt.Errorf("invalid unit: %q", unit)
}
return nil
}
func (d timeDuration) Duration() time.Duration {
duration := d.duration
duration += time.Duration(d.days) * 24 * time.Hour
duration += time.Duration(d.months) * 30 * 24 * time.Hour
duration += time.Duration(d.years) * 365 * 24 * time.Hour
duration *= time.Duration(d.sign)
return duration
}