-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathparser.go
More file actions
399 lines (360 loc) · 9.55 KB
/
parser.go
File metadata and controls
399 lines (360 loc) · 9.55 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
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
package cron
import (
"errors"
"fmt"
"log"
"math"
"strconv"
"strings"
"time"
)
// Parse returns a new crontab schedule representing the given spec.
// It panics with a descriptive error if the spec is not valid.
//
// It accepts
// - Full crontab specs, e.g. "* * * * * ?"
// - Descriptors, e.g. "@midnight", "@every 1h30m"
func Parse(spec string) Schedule {
schedule, err := ParseWithError(spec)
if err != nil {
log.Panic(err)
}
return schedule
}
// ParseWithError returns a new crontab schedule representing the given spec.
// Returns error if the spec is not valid.
//
// It accepts
// - Full crontab specs, e.g. "* * * * * ?"
// - Descriptors, e.g. "@midnight", "@every 1h30m"
// - Timezone prefix, e.g. "CRON_TZ=Asia/Shanghai 0 30 8 * * *"
// or "TZ=America/New_York @daily"
func ParseWithError(spec string) (Schedule, error) {
if len(spec) == 0 {
return nil, errors.New("empty spec string")
}
// Extract CRON_TZ= or TZ= prefix
var loc *time.Location
if strings.HasPrefix(spec, "CRON_TZ=") || strings.HasPrefix(spec, "TZ=") {
eqIdx := strings.IndexByte(spec, '=')
rest := spec[eqIdx+1:]
spIdx := strings.IndexByte(rest, ' ')
if spIdx < 0 {
return nil, fmt.Errorf("CRON_TZ/TZ= prefix requires a space before the cron expression: %s", spec)
}
tzName := rest[:spIdx]
if len(tzName) == 0 {
return nil, fmt.Errorf("empty timezone name in prefix: %s", spec)
}
var err error
loc, err = time.LoadLocation(tzName)
if err != nil {
return nil, fmt.Errorf("invalid timezone %q: %w", tzName, err)
}
spec = strings.TrimSpace(rest[spIdx+1:])
if len(spec) == 0 {
return nil, errors.New("empty spec string after timezone prefix")
}
}
var schedule Schedule
var err error
if spec[0] == '@' {
schedule, err = parseDescriptorWithError(spec)
} else {
schedule, err = parseSpecWithError(spec)
}
if err != nil {
return nil, err
}
if loc != nil {
return &TZSchedule{schedule: schedule, location: loc}, nil
}
return schedule, nil
}
// parseSpecWithError parses a standard cron spec (not a descriptor).
func parseSpecWithError(spec string) (Schedule, error) {
// Zero-alloc whitespace field splitting using a stack array.
var fields [6]string
fieldCount := 0
i := 0
n := len(spec)
for fieldCount < 6 && i < n {
for i < n && (spec[i] == ' ' || spec[i] == '\t') {
i++
}
if i >= n {
break
}
start := i
for i < n && spec[i] != ' ' && spec[i] != '\t' {
i++
}
fields[fieldCount] = spec[start:i]
fieldCount++
}
// Check for extra fields beyond 6
for i < n && (spec[i] == ' ' || spec[i] == '\t') {
i++
}
if i < n {
fieldCount = 7
}
if fieldCount != 5 && fieldCount != 6 {
return nil, fmt.Errorf("expected 5 or 6 fields, found %d: %s", fieldCount, spec)
}
// If a sixth field is not provided (DayOfWeek), then it is equivalent to star.
if fieldCount == 5 {
fields[5] = "*"
}
var err error
schedule := &SpecSchedule{}
if schedule.Second, err = getFieldWithError(fields[0], seconds); err != nil {
return nil, err
}
if schedule.Minute, err = getFieldWithError(fields[1], minutes); err != nil {
return nil, err
}
if schedule.Hour, err = getFieldWithError(fields[2], hours); err != nil {
return nil, err
}
if schedule.Dom, err = getFieldWithError(fields[3], dom); err != nil {
return nil, err
}
if schedule.Month, err = getFieldWithError(fields[4], months); err != nil {
return nil, err
}
if schedule.Dow, err = getFieldWithError(fields[5], dow); err != nil {
return nil, err
}
return schedule, nil
}
// getField returns an Int with the bits set representing all of the times that
// the field represents. A "field" is a comma-separated list of "ranges".
func getField(field string, r bounds) uint64 {
bits, err := getFieldWithError(field, r)
if err != nil {
log.Panic(err)
}
return bits
}
// getFieldWithError returns an Int with the bits set representing all of the times that
// the field represents. A "field" is a comma-separated list of "ranges".
func getFieldWithError(field string, r bounds) (uint64, error) {
// Zero-alloc comma splitting using IndexByte.
var bits uint64
for len(field) > 0 {
idx := strings.IndexByte(field, ',')
var expr string
if idx < 0 {
expr = field
field = ""
} else {
expr = field[:idx]
field = field[idx+1:]
}
if len(expr) == 0 {
continue
}
b, err := getRangeWithError(expr, r)
if err != nil {
return 0, err
}
bits |= b
}
return bits, nil
}
// getRange returns the bits indicated by the given expression:
//
// number | number "-" number [ "/" number ]
func getRange(expr string, r bounds) uint64 {
bits, err := getRangeWithError(expr, r)
if err != nil {
log.Panic(err)
}
return bits
}
// getRangeWithError returns the bits indicated by the given expression:
//
// number | number "-" number [ "/" number ]
func getRangeWithError(expr string, r bounds) (uint64, error) {
var start, end, step uint
// Zero-alloc: split on "/" using IndexByte
rangePart := expr
stepPart := ""
hasStep := false
if slashIdx := strings.IndexByte(expr, '/'); slashIdx >= 0 {
rangePart = expr[:slashIdx]
rest := expr[slashIdx+1:]
if strings.IndexByte(rest, '/') >= 0 {
return 0, fmt.Errorf("too many slashes: %s", expr)
}
stepPart = rest
hasStep = true
}
// Zero-alloc: split rangePart on "-" using IndexByte
lowPart := rangePart
highPart := ""
hasHigh := false
if hyphenIdx := strings.IndexByte(rangePart, '-'); hyphenIdx >= 0 {
lowPart = rangePart[:hyphenIdx]
rest := rangePart[hyphenIdx+1:]
if strings.IndexByte(rest, '-') >= 0 {
return 0, fmt.Errorf("too many hyphens: %s", expr)
}
highPart = rest
hasHigh = true
}
singleDigit := !hasHigh
var extraStar uint64
if lowPart == "*" || lowPart == "?" {
start = r.min
end = r.max
extraStar = starBit
} else {
var err error
start, err = parseIntOrNameWithError(lowPart, r.names)
if err != nil {
return 0, err
}
if hasHigh {
end, err = parseIntOrNameWithError(highPart, r.names)
if err != nil {
return 0, err
}
} else {
end = start
}
}
if !hasStep {
step = 1
} else {
var err error
step, err = mustParseIntWithError(stepPart)
if err != nil {
return 0, err
}
if step == 0 {
return 0, fmt.Errorf("step must be > 0: %s", expr)
}
// Special handling: "N/step" means "N-max/step".
if singleDigit {
end = r.max
}
}
if start < r.min {
return 0, fmt.Errorf("beginning of range (%d) below minimum (%d): %s", start, r.min, expr)
}
if end > r.max {
return 0, fmt.Errorf("end of range (%d) above maximum (%d): %s", end, r.max, expr)
}
if start > end {
return 0, fmt.Errorf("beginning of range (%d) beyond end of range (%d): %s", start, end, expr)
}
return getBits(start, end, step) | extraStar, nil
}
// parseIntOrNameWithError returns the (possibly-named) integer contained in expr.
func parseIntOrNameWithError(expr string, names map[string]uint) (uint, error) {
if names != nil {
if namedInt, ok := names[strings.ToLower(expr)]; ok {
return namedInt, nil
}
}
return mustParseIntWithError(expr)
}
// mustParseIntWithError parses the given expression as an int or returns error.
func mustParseIntWithError(expr string) (uint, error) {
num, err := strconv.Atoi(expr)
if err != nil {
return 0, fmt.Errorf("failed to parse int from %s: %s", expr, err)
}
if num < 0 {
return 0, fmt.Errorf("negative number (%d) not allowed: %s", num, expr)
}
return uint(num), nil
}
// getBits sets all bits in the range [min, max], modulo the given step size.
func getBits(min, max, step uint) uint64 {
var bits uint64
// If step is 1, use shifts.
if step == 1 {
bits := max - min + 1
if bits >= 64 {
return math.MaxUint64
}
return (uint64(1)<<bits - 1) << min
}
// Else, use a simple loop.
for i := min; i <= max; i += step {
bits |= 1 << i
}
return bits
}
// all returns all bits within the given bounds. (plus the star bit)
func all(r bounds) uint64 {
return getBits(r.min, r.max, 1) | starBit
}
// parseDescriptorWithError returns a pre-defined schedule for the expression, or error
// if none matches.
func parseDescriptorWithError(spec string) (Schedule, error) {
switch spec {
case "@yearly", "@annually":
return &SpecSchedule{
Second: 1 << seconds.min,
Minute: 1 << minutes.min,
Hour: 1 << hours.min,
Dom: 1 << dom.min,
Month: 1 << months.min,
Dow: all(dow),
}, nil
case "@monthly":
return &SpecSchedule{
Second: 1 << seconds.min,
Minute: 1 << minutes.min,
Hour: 1 << hours.min,
Dom: 1 << dom.min,
Month: all(months),
Dow: all(dow),
}, nil
case "@weekly":
return &SpecSchedule{
Second: 1 << seconds.min,
Minute: 1 << minutes.min,
Hour: 1 << hours.min,
Dom: all(dom),
Month: all(months),
Dow: 1 << dow.min,
}, nil
case "@daily", "@midnight":
return &SpecSchedule{
Second: 1 << seconds.min,
Minute: 1 << minutes.min,
Hour: 1 << hours.min,
Dom: all(dom),
Month: all(months),
Dow: all(dow),
}, nil
case "@hourly":
return &SpecSchedule{
Second: 1 << seconds.min,
Minute: 1 << minutes.min,
Hour: all(hours),
Dom: all(dom),
Month: all(months),
Dow: all(dow),
}, nil
case "@reboot":
return &RebootSchedule{}, nil
}
const every = "@every "
if strings.HasPrefix(spec, every) {
duration, err := time.ParseDuration(spec[len(every):])
if err != nil {
return nil, fmt.Errorf("failed to parse duration %s: %s", spec, err)
}
if duration < time.Second {
return nil, fmt.Errorf("cron/constantdelay: delays of less than a second are not supported: %s", duration.String())
}
return Every(duration), nil
}
return nil, fmt.Errorf("unrecognized descriptor: %s", spec)
}