This repository has been archived by the owner on Apr 7, 2024. It is now read-only.
forked from hashicorp/cronexpr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cronexpr.go
459 lines (403 loc) · 12 KB
/
cronexpr.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
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/*!
* Copyright 2013 Raymond Hill
*
* Modifications 2020 - HashiCorp
*
* Project: github.com/gorhill/cronexpr
* File: cronexpr.go
* Version: 1.0
* License: pick the one which suits you :
* GPL v3 see <https://www.gnu.org/licenses/gpl.html>
* APL v2 see <http://www.apache.org/licenses/LICENSE-2.0>
*
*/
// Package cronexpr parses cron time expressions.
package cronexpr
/******************************************************************************/
import (
"fmt"
"sort"
"time"
)
/******************************************************************************/
// A Expression represents a specific cron time expression as defined at
// <https://github.com/gorhill/cronexpr#implementation>
type Expression struct {
expression string
secondList []int
minuteList []int
hourList []int
daysOfMonth map[int]bool
workdaysOfMonth map[int]bool
lastDayOfMonth bool
lastWorkdayOfMonth bool
daysOfMonthRestricted bool
actualDaysOfMonthList []int
monthList []int
daysOfWeek map[int]bool
specificWeekDaysOfWeek map[int]bool
lastWeekDaysOfWeek map[int]bool
daysOfWeekRestricted bool
yearList []int
timeZone *time.Location
}
/******************************************************************************/
// MustParse returns a new Expression pointer. It expects a well-formed cron
// expression. If a malformed cron expression is supplied, it will `panic`.
// See <https://github.com/gorhill/cronexpr#implementation> for documentation
// about what is a well-formed cron expression from this library's point of
// view.
func MustParse(cronLine string) *Expression {
expr, err := Parse(cronLine)
if err != nil {
panic(err)
}
return expr
}
func MustParseSystemd(cronLine string) *Expression {
expr, err := ParseSystemd(cronLine)
if err != nil {
panic(err)
}
return expr
}
/******************************************************************************/
// Parse returns a new Expression pointer. An error is returned if a malformed
// cron expression is supplied.
// See <https://github.com/gorhill/cronexpr#implementation> for documentation
// about what is a well-formed cron expression from this library's point of
// view.
func Parse(cronLine string) (*Expression, error) {
// Maybe one of the built-in aliases is being used
cron := cronNormalizer.Replace(cronLine)
indices := fieldFinder.FindAllStringIndex(cron, -1)
fieldCount := len(indices)
if fieldCount < 5 {
return nil, fmt.Errorf("missing field(s)")
}
// ignore fields beyond 7th
if fieldCount > 7 {
fieldCount = 7
}
var expr = Expression{}
var field = 0
var err error
// second field (optional)
if fieldCount == 7 {
err = expr.secondFieldHandler(cron[indices[field][0]:indices[field][1]])
if err != nil {
return nil, err
}
field += 1
} else {
expr.secondList = []int{0}
}
// minute field
err = expr.minuteFieldHandler(cron[indices[field][0]:indices[field][1]])
if err != nil {
return nil, err
}
field += 1
// hour field
err = expr.hourFieldHandler(cron[indices[field][0]:indices[field][1]])
if err != nil {
return nil, err
}
field += 1
// day of month field
err = expr.domFieldHandler(cron[indices[field][0]:indices[field][1]])
if err != nil {
return nil, err
}
field += 1
// month field
err = expr.monthFieldHandler(cron[indices[field][0]:indices[field][1]])
if err != nil {
return nil, err
}
field += 1
// day of week field
err = expr.dowFieldHandler(cron[indices[field][0]:indices[field][1]])
if err != nil {
return nil, err
}
field += 1
// year field
if field < fieldCount {
err = expr.yearFieldHandler(cron[indices[field][0]:indices[field][1]])
if err != nil {
return nil, err
}
} else {
expr.yearList = yearDescriptor.defaultList
}
return &expr, nil
}
func ParseSystemd(systemdLine string) (*Expression, error) {
var expr = Expression{
expression: systemdLine,
}
if err := expr.normalyzeSystemd(); err != nil {
return nil, fmt.Errorf("invalid expression, %s", err)
}
indices := fieldFinder.FindAllStringIndex(expr.expression, -1)
fieldCount := len(indices)
fieldI := 0
var err error
if fieldCount > 4 {
return nil, fmt.Errorf("too much field(s)")
}
// Try parse weekday field
if expr.validateField(fieldI, WeekDayField, indices) {
// parse weekday
err = expr.dowFieldHandler(expr.expression[indices[fieldI][0]:indices[fieldI][1]])
if err != nil {
return nil, err
}
fieldI++
} else {
// weekdays *
err = expr.dowFieldHandler("*")
}
// Try parse date field
if expr.validateField(fieldI, DayField, indices) {
// parse date
field := 1
dateString := expr.expression[indices[fieldI][0]:indices[fieldI][1]]
DateIndices := entryDateFinder.FindAllStringIndex(dateString, -1)
// day of month field
err = expr.domFieldHandler(dateString[DateIndices[len(DateIndices)-field][0]:DateIndices[len(DateIndices)-field][1]])
if err != nil {
return nil, err
}
field += 1
// month field
if len(DateIndices)-field >= 0 {
err = expr.monthFieldHandler(dateString[DateIndices[len(DateIndices)-field][0]:DateIndices[len(DateIndices)-field][1]])
if err != nil {
return nil, err
}
field += 1
} else {
expr.monthList = monthDescriptor.defaultList
}
// year field
if len(DateIndices)-field >= 0 {
yearString := dateString[DateIndices[len(DateIndices)-field][0]:DateIndices[len(DateIndices)-field][1]]
if len(yearString) == 2 {
yearString = "20" + yearString
}
err = expr.yearFieldHandler(yearString)
if err != nil {
return nil, err
}
} else {
expr.yearList = yearDescriptor.defaultList
}
fieldI++
} else {
_ = expr.domFieldHandler("*")
expr.monthList = monthDescriptor.defaultList
expr.yearList = yearDefaultList
}
// Try parse date time
if expr.validateField(fieldI, TimeField, indices) {
// parse time
field := 0
timeString := expr.expression[indices[fieldI][0]:indices[fieldI][1]]
TimeIndices := entryTimeFinder.FindAllStringIndex(timeString, -1)
// hour field
err = expr.hourFieldHandler(timeString[TimeIndices[field][0]:TimeIndices[field][1]])
if err != nil {
return nil, err
}
field += 1
// minute field
err = expr.minuteFieldHandler(timeString[TimeIndices[field][0]:TimeIndices[field][1]])
if err != nil {
return nil, err
}
field += 1
// seconds field
if field < len(TimeIndices) {
err = expr.secondFieldHandler(timeString[TimeIndices[field][0]:TimeIndices[field][1]])
if err != nil {
return nil, err
}
} else {
err = expr.secondFieldHandler("00")
if err != nil {
return nil, err
}
}
fieldI++
} else {
// time *
err = expr.secondFieldHandler("00")
if err != nil {
return nil, err
}
err = expr.minuteFieldHandler("00")
if err != nil {
return nil, err
}
err = expr.hourFieldHandler("00")
if err != nil {
return nil, err
}
}
if fieldI < fieldCount {
if expr.expression[indices[fieldI][0]:indices[fieldI][1]] != "" {
// try parse timezone
expr.timeZone = time.FixedZone(expr.expression[indices[fieldI][0]:indices[fieldI][1]], 0)
}
}
return &expr, nil
}
/******************************************************************************/
// Next returns the closest time instant immediately following `fromTime` which
// matches the cron expression `expr`.
//
// The `time.Location` of the returned time instant is the same as that of
// `fromTime`.
//
// The zero value of time.Time is returned if no matching time instant exists
// or if a `fromTime` is itself a zero value.
func (expr *Expression) Next(fromTime time.Time) time.Time {
// Special case
if fromTime.IsZero() {
return fromTime
}
loc := fromTime.Location()
if expr.timeZone != nil {
loc = expr.timeZone
}
t := fromTime.Add(time.Second - time.Duration(fromTime.Nanosecond())*time.Nanosecond)
WRAP:
// let's find the next date that satisfies condition
v := t.Year()
if i := sort.SearchInts(expr.yearList, v); i == len(expr.yearList) {
return time.Time{}
} else if v != expr.yearList[i] {
t = time.Date(expr.yearList[i], time.Month(expr.monthList[0]), 1, 0, 0, 0, 0, loc)
}
v = int(t.Month())
if i := sort.SearchInts(expr.monthList, v); i == len(expr.monthList) {
// try again with a new year
t = time.Date(t.Year()+1, time.Month(expr.monthList[0]), 1, 0, 0, 0, 0, loc)
goto WRAP
} else if v != expr.monthList[i] {
t = time.Date(t.Year(), time.Month(expr.monthList[i]), 1, 0, 0, 0, 0, loc)
}
expr.actualDaysOfMonthList = expr.calculateActualDaysOfMonth(t.Year(), int(t.Month()))
if len(expr.actualDaysOfMonthList) == 0 {
t = time.Date(t.Year(), t.Month()+1, 1, 0, 0, 0, 0, loc)
goto WRAP
}
v = t.Day()
if i := sort.SearchInts(expr.actualDaysOfMonthList, v); i == len(expr.actualDaysOfMonthList) {
t = time.Date(t.Year(), t.Month()+1, 1, 0, 0, 0, 0, loc)
goto WRAP
} else if v != expr.actualDaysOfMonthList[i] {
t = time.Date(t.Year(), t.Month(), expr.actualDaysOfMonthList[i], 0, 0, 0, 0, loc)
// in San Palo, before 2019, there may be no midnight (or multiple midnights)
// due to DST
if t.Hour() != 0 {
if t.Hour() > 12 {
t = t.Add(time.Duration(24-t.Hour()) * time.Hour)
} else {
t = t.Add(time.Duration(-t.Hour()) * time.Hour)
}
}
}
if timeZoneInDay(t) {
goto SLOW_CLOCK
}
// Fast path where hours/minutes behave as expected trivially
v = t.Hour()
if i := sort.SearchInts(expr.hourList, v); i == len(expr.hourList) {
t = time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, loc)
goto WRAP
} else if v != expr.hourList[i] {
t = time.Date(t.Year(), t.Month(), t.Day(), expr.hourList[i], expr.minuteList[0], expr.secondList[0], 0, loc)
}
v = t.Minute()
if i := sort.SearchInts(expr.minuteList, v); i == len(expr.minuteList) {
t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour()+1, 0, 0, 0, loc)
goto WRAP
} else if v != expr.minuteList[i] {
t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), expr.minuteList[i], expr.secondList[0], 0, loc)
}
v = t.Second()
if i := sort.SearchInts(expr.secondList, v); i == len(expr.secondList) {
t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute()+1, 0, 0, loc)
goto WRAP
} else if v != expr.secondList[i] {
t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), expr.secondList[i], 0, loc)
}
return t
SLOW_CLOCK:
// daylight saving effect is here, where odd things happen:
// An hour may have 60 minutes, 30 minutes or 90 minutes;
// partial hours may "repeat"!
for !sortContains(expr.hourList, t.Hour()) {
hourBefore := t.Hour()
t = t.Add(time.Hour)
if hourBefore == t.Hour() {
t = t.Add(time.Hour)
}
t = t.Truncate(time.Minute)
if t.Minute() != 0 {
t = t.Add(-1 * time.Minute * time.Duration(t.Minute()))
}
if t.Hour() == 0 {
t = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, loc)
goto WRAP
}
}
for !sortContains(expr.minuteList, t.Minute()) {
hoursBefore := t.Hour()
t = t.Truncate(time.Minute).Add(time.Minute)
if hoursBefore != t.Hour() {
goto WRAP
}
}
v = t.Second()
t = t.Truncate(time.Minute)
if i := sort.SearchInts(expr.secondList, v); i == len(expr.secondList) {
t = t.Add(time.Minute)
goto WRAP
} else {
t = t.Add(time.Duration(expr.secondList[i]) * time.Second)
}
return t
}
/******************************************************************************/
// NextN returns a slice of `n` closest time instants immediately following
// `fromTime` which match the cron expression `expr`.
//
// The time instants in the returned slice are in chronological ascending order.
// The `time.Location` of the returned time instants is the same as that of
// `fromTime`.
//
// A slice with len between [0-`n`] is returned, that is, if not enough existing
// matching time instants exist, the number of returned entries will be less
// than `n`.
func (expr *Expression) NextN(fromTime time.Time, n uint) []time.Time {
nextTimes := make([]time.Time, 0, n)
if n > 0 {
fromTime = expr.Next(fromTime)
for {
if fromTime.IsZero() {
break
}
nextTimes = append(nextTimes, fromTime)
n -= 1
if n == 0 {
break
}
fromTime = expr.Next(fromTime)
}
}
return nextTimes
}