-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcronexpr_describe.go
More file actions
593 lines (522 loc) · 14.8 KB
/
Copy pathcronexpr_describe.go
File metadata and controls
593 lines (522 loc) · 14.8 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
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
package cronexpr
import (
"fmt"
"regexp"
"strconv"
"strings"
"time"
)
// DescribeOptions controls how a cron expression is described.
type DescribeOptions struct {
// Short uses abbreviated names ("Mon" vs "Monday", "Jan" vs "January").
Short bool
// SourceLocation is the cron schedule's timezone (nil = UTC).
SourceLocation *time.Location
// TargetLocation is the display timezone (nil = UTC).
TargetLocation *time.Location
}
var (
descDayNames = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
descDayShortNames = []string{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
descMonthNames = []string{"", "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"}
descMonthShortNames = []string{"", "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
)
// Describe returns a human-readable description of the cron expression.
// If opts is nil, defaults are used (long names, UTC timezone).
func (expr *Expression) Describe(opts *DescribeOptions) string {
if opts == nil {
opts = &DescribeOptions{}
}
srcLoc := opts.SourceLocation
if srcLoc == nil {
srcLoc = time.UTC
}
targetLoc := opts.TargetLocation
if targetLoc == nil {
targetLoc = time.UTC
}
fields := descParseFields(expr.normalized)
if fields == nil {
return expr.normalized
}
dNames := descDayNames
mNames := descMonthNames
if opts.Short {
dNames = descDayShortNames
mNames = descMonthShortNames
}
var parts []string
timeDesc, dayOffset := describeTime(fields, srcLoc, targetLoc, opts.Short)
if timeDesc != "" {
parts = append(parts, timeDesc)
}
dateDesc := describeDate(fields, dayOffset, dNames, mNames, opts.Short)
if dateDesc != "" {
parts = append(parts, dateDesc)
}
if len(parts) == 0 {
return "Every minute"
}
return strings.Join(parts, ", ")
}
// descFields holds the raw field strings from the normalized cron expression.
type descFields struct {
seconds string
minutes string
hours string
dayOfMonth string
month string
dayOfWeek string
}
// descParseFields splits the normalized cron string into fields.
// Returns nil if the field count is unexpected.
func descParseFields(normalized string) *descFields {
parts := strings.Fields(normalized)
var f descFields
switch len(parts) {
case 5: // minute hour dom month dow
f.seconds = "0"
f.minutes = parts[0]
f.hours = parts[1]
f.dayOfMonth = parts[2]
f.month = parts[3]
f.dayOfWeek = parts[4]
case 6: // second minute hour dom month dow
f.seconds = parts[0]
f.minutes = parts[1]
f.hours = parts[2]
f.dayOfMonth = parts[3]
f.month = parts[4]
f.dayOfWeek = parts[5]
case 7: // second minute hour dom month dow year
f.seconds = parts[0]
f.minutes = parts[1]
f.hours = parts[2]
f.dayOfMonth = parts[3]
f.month = parts[4]
f.dayOfWeek = parts[5]
// year ignored for description
default:
return nil
}
// Normalize ? to *
f.dayOfMonth = strings.ReplaceAll(f.dayOfMonth, "?", "*")
f.dayOfWeek = descNormalizeDow(f.dayOfWeek)
f.month = descNormalizeMonth(f.month)
f.minutes = strings.ReplaceAll(f.minutes, "?", "*")
f.hours = strings.ReplaceAll(f.hours, "?", "*")
return &f
}
var descDayMap = map[string]string{
"sun": "0", "mon": "1", "tue": "2", "wed": "3",
"thu": "4", "fri": "5", "sat": "6",
}
var descMonthMap = map[string]string{
"jan": "1", "feb": "2", "mar": "3", "apr": "4",
"may": "5", "jun": "6", "jul": "7", "aug": "8",
"sep": "9", "oct": "10", "nov": "11", "dec": "12",
}
func descNormalizeDow(s string) string {
s = strings.ToLower(s)
s = strings.ReplaceAll(s, "?", "*")
for name, num := range descDayMap {
s = strings.ReplaceAll(s, name, num)
}
if s == "7" {
s = "0"
}
return s
}
func descNormalizeMonth(s string) string {
s = strings.ToLower(s)
for name, num := range descMonthMap {
s = strings.ReplaceAll(s, name, num)
}
return strings.ReplaceAll(s, "?", "*")
}
// describeTime returns the time description and a day offset (-1, 0, or 1) for TZ conversion.
func describeTime(f *descFields, srcLoc, targetLoc *time.Location, short bool) (string, int) {
// Intervals are timezone-agnostic
if f.hours == "*" && f.minutes != "*" {
if interval, ok := descParseInterval(f.minutes); ok {
if interval == 1 {
if short {
return "Every min", 0
}
return "Every minute", 0
}
if short {
return fmt.Sprintf("Every %d mins", interval), 0
}
return fmt.Sprintf("Every %d minutes", interval), 0
}
// Specific minute, every hour (e.g. @hourly = "0 * * * *")
minDesc := describeMinutes(f.minutes, short)
return minDesc + ", every hour", 0
}
if f.minutes == "*" && f.hours != "*" {
if interval, ok := descParseInterval(f.hours); ok {
everyMin := "Every minute"
if short {
everyMin = "Every min"
}
if interval == 1 {
return everyMin + ", every hour", 0
}
return fmt.Sprintf("%s, every %d hours", everyMin, interval), 0
}
}
if f.hours == "*" && f.minutes == "*" {
return "Every minute", 0
}
if interval, ok := descParseInterval(f.hours); ok {
minDesc := describeMinutes(f.minutes, short)
if interval == 1 {
return minDesc + ", every hour", 0
}
return fmt.Sprintf("%s, every %d hours", minDesc, interval), 0
}
// Specific times — need timezone conversion
if descIsList(f.hours) {
hours := descSplitList(f.hours)
var times []string
var dayOffset int
for _, h := range hours {
t, offset := descFormatTimeWithTZ(h, f.minutes, srcLoc, targetLoc, short)
times = append(times, t)
dayOffset = offset
}
return "At " + descJoinWithAnd(times), dayOffset
}
if descIsRange(f.hours) {
start, end := descParseRange(f.hours)
minDesc := describeMinutes(f.minutes, short)
startFmt, dayOffset := descFormatHourWithTZ(start, srcLoc, targetLoc, short)
endFmt, _ := descFormatHourWithTZ(end, srcLoc, targetLoc, short)
return fmt.Sprintf("%s, %s–%s", minDesc, startFmt, endFmt), dayOffset
}
t, dayOffset := descFormatTimeWithTZ(f.hours, f.minutes, srcLoc, targetLoc, short)
return "At " + t, dayOffset
}
func describeMinutes(minutes string, short bool) string {
if minutes == "*" || minutes == "0" {
if short {
return "At min 0"
}
return "At minute 0"
}
if interval, ok := descParseInterval(minutes); ok {
if interval == 1 {
if short {
return "Every min"
}
return "Every minute"
}
if short {
return fmt.Sprintf("Every %d mins", interval)
}
return fmt.Sprintf("Every %d minutes", interval)
}
m, _ := strconv.Atoi(minutes)
if short {
return fmt.Sprintf("At min %d", m)
}
return fmt.Sprintf("At minute %d", m)
}
// describeDate generates date/day description, adjusting DOW by dayOffset for TZ conversion.
func describeDate(f *descFields, dayOffset int, dNames, mNames []string, short bool) string {
var parts []string
dowDesc := describeDayOfWeek(f.dayOfWeek, dayOffset, dNames)
domDesc := describeDayOfMonth(f.dayOfMonth, short)
monthDesc := describeMonth(f.month, mNames)
switch {
case domDesc != "" && dowDesc != "":
if monthDesc != "" {
parts = append(parts, domDesc, "and "+dowDesc, monthDesc)
} else {
parts = append(parts, domDesc, "and "+dowDesc)
}
case domDesc != "":
if monthDesc != "" {
parts = append(parts, domDesc, monthDesc)
} else {
parts = append(parts, domDesc)
}
case dowDesc != "":
parts = append(parts, dowDesc)
if monthDesc != "" {
parts = append(parts, monthDesc)
}
case monthDesc != "":
parts = append(parts, monthDesc)
}
if len(parts) == 0 {
return ""
}
return strings.Join(parts, " ")
}
func describeDayOfWeek(dow string, dayOffset int, names []string) string {
if dow == "*" {
return ""
}
// Last DOW pattern (e.g., 5L = last Friday)
if strings.HasSuffix(dow, "l") || strings.HasSuffix(dow, "L") {
day := strings.TrimSuffix(strings.TrimSuffix(dow, "l"), "L")
d, _ := strconv.Atoi(day)
if d >= 0 && d <= 6 {
d = descAdjustDay(d, dayOffset)
return fmt.Sprintf("on the last %s of the month", names[d])
}
}
// Nth DOW pattern (e.g., 1#2 = second Monday)
if strings.Contains(dow, "#") {
parts := strings.Split(dow, "#")
if len(parts) == 2 {
day, _ := strconv.Atoi(parts[0])
nth, _ := strconv.Atoi(parts[1])
if day >= 0 && day <= 6 && nth >= 1 && nth <= 5 {
day = descAdjustDay(day, dayOffset)
ordinal := []string{"", "first", "second", "third", "fourth", "fifth"}[nth]
return fmt.Sprintf("on the %s %s of the month", ordinal, names[day])
}
}
}
if descIsRange(dow) {
start, end := descParseRange(dow)
startDay, _ := strconv.Atoi(start)
endDay, _ := strconv.Atoi(end)
if startDay >= 0 && startDay <= 6 && endDay >= 0 && endDay <= 6 {
startDay = descAdjustDay(startDay, dayOffset)
endDay = descAdjustDay(endDay, dayOffset)
return fmt.Sprintf("%s–%s", names[startDay], names[endDay])
}
}
if descIsList(dow) {
days := descSplitList(dow)
var dayNamesList []string
for _, d := range days {
if n, err := strconv.Atoi(d); err == nil && n >= 0 && n <= 6 {
n = descAdjustDay(n, dayOffset)
dayNamesList = append(dayNamesList, names[n])
}
}
return descJoinWithAnd(dayNamesList) + " only"
}
d, err := strconv.Atoi(dow)
if err == nil && d >= 0 && d <= 6 {
d = descAdjustDay(d, dayOffset)
return descDayNames[d] + " only"
}
return ""
}
func describeDayOfMonth(dom string, short bool) string {
if dom == "*" {
return ""
}
if strings.ToLower(dom) == "l" {
if short {
return "last day of month"
}
return "on the last day of the month"
}
if strings.HasSuffix(strings.ToUpper(dom), "W") {
day := strings.TrimSuffix(strings.TrimSuffix(dom, "w"), "W")
d, _ := strconv.Atoi(day)
if short {
return fmt.Sprintf("weekday nearest the %s", descOrdinal(d))
}
return fmt.Sprintf("on the weekday nearest the %s of the month", descOrdinal(d))
}
if descIsRange(dom) {
start, end := descParseRange(dom)
startN, _ := strconv.Atoi(start)
endN, _ := strconv.Atoi(end)
if short {
return fmt.Sprintf("days %s–%s", start, descOrdinal(endN))
}
return fmt.Sprintf("on the %s–%s of the month", descOrdinal(startN), descOrdinal(endN))
}
if descIsList(dom) {
days := descSplitList(dom)
var ordinals []string
for _, d := range days {
n, _ := strconv.Atoi(d)
ordinals = append(ordinals, descOrdinal(n))
}
if short {
return "on the " + descJoinWithAnd(ordinals)
}
return "on the " + descJoinWithAnd(ordinals) + " of the month"
}
if interval, ok := descParseInterval(dom); ok {
if interval == 1 {
return "every day"
}
return fmt.Sprintf("every %d days", interval)
}
d, _ := strconv.Atoi(dom)
if short {
return fmt.Sprintf("on the %s", descOrdinal(d))
}
return fmt.Sprintf("on the %s of the month", descOrdinal(d))
}
// descOrdinal returns an integer with its English ordinal suffix (1st, 2nd, 3rd, etc.).
func descOrdinal(n int) string {
if n%100 >= 11 && n%100 <= 13 {
return strconv.Itoa(n) + "th"
}
switch n % 10 {
case 1:
return strconv.Itoa(n) + "st"
case 2:
return strconv.Itoa(n) + "nd"
case 3:
return strconv.Itoa(n) + "rd"
default:
return strconv.Itoa(n) + "th"
}
}
func describeMonth(month string, names []string) string {
if month == "*" {
return ""
}
if descIsRange(month) {
start, end := descParseRange(month)
startMonth, _ := strconv.Atoi(start)
endMonth, _ := strconv.Atoi(end)
if startMonth >= 1 && startMonth <= 12 && endMonth >= 1 && endMonth <= 12 {
return fmt.Sprintf("%s–%s", names[startMonth], names[endMonth])
}
}
if descIsList(month) {
months := descSplitList(month)
var monthNamesList []string
for _, m := range months {
if n, err := strconv.Atoi(m); err == nil && n >= 1 && n <= 12 {
monthNamesList = append(monthNamesList, names[n])
}
}
return "in " + descJoinWithAnd(monthNamesList)
}
m, err := strconv.Atoi(month)
if err == nil && m >= 1 && m <= 12 {
return "only in " + names[m]
}
return ""
}
// Helpers
var descIntervalRe = regexp.MustCompile(`^\*/(\d+)$`)
func descParseInterval(s string) (int, bool) {
matches := descIntervalRe.FindStringSubmatch(s)
if len(matches) == 2 {
n, _ := strconv.Atoi(matches[1])
return n, true
}
return 0, false
}
func descIsRange(s string) bool {
return strings.Contains(s, "-") && !strings.HasPrefix(s, "-")
}
func descParseRange(s string) (string, string) {
if before, after, ok := strings.Cut(s, "-"); ok {
return before, after
}
return s, s
}
func descIsList(s string) bool {
return strings.Contains(s, ",")
}
func descSplitList(s string) []string {
return strings.Split(s, ",")
}
func descJoinWithAnd(items []string) string {
switch len(items) {
case 0:
return ""
case 1:
return items[0]
case 2:
return items[0] + " and " + items[1]
default:
return strings.Join(items[:len(items)-1], ", ") + ", and " + items[len(items)-1]
}
}
// descAdjustDay shifts a day-of-week (0-6) by offset, wrapping around.
func descAdjustDay(day, offset int) int {
day = (day + offset) % 7
if day < 0 {
day += 7
}
return day
}
// descFormatTimeWithTZ converts hour:minute from srcLoc to targetLoc in 12-hour format.
// Returns formatted time and day offset (-1, 0, or 1) if conversion crossed a day boundary.
func descFormatTimeWithTZ(hour, minute string, srcLoc, targetLoc *time.Location, short bool) (string, int) {
h, err := strconv.Atoi(hour)
if err != nil {
return hour + ":" + minute, 0
}
m, _ := strconv.Atoi(minute)
now := time.Now()
srcTime := time.Date(now.Year(), now.Month(), now.Day(), h, m, 0, 0, srcLoc)
targetTime := srcTime.In(targetLoc)
dayOffset := targetTime.Day() - srcTime.Day()
if dayOffset > 1 {
dayOffset = -1
} else if dayOffset < -1 {
dayOffset = 1
}
targetH := targetTime.Hour()
period := "AM"
displayHour := targetH
if targetH >= 12 {
period = "PM"
if targetH > 12 {
displayHour = targetH - 12
}
}
if displayHour == 0 {
displayHour = 12
}
if short && m == 0 {
return fmt.Sprintf("%d%s", displayHour, period), dayOffset
}
if short {
return fmt.Sprintf("%d:%02d%s", displayHour, m, period), dayOffset
}
return fmt.Sprintf("%d:%02d %s", displayHour, m, period), dayOffset
}
// descFormatHourWithTZ converts hour from srcLoc to targetLoc in 12-hour format.
func descFormatHourWithTZ(hour string, srcLoc, targetLoc *time.Location, short bool) (string, int) {
h, err := strconv.Atoi(hour)
if err != nil {
return hour + ":00", 0
}
now := time.Now()
srcTime := time.Date(now.Year(), now.Month(), now.Day(), h, 0, 0, 0, srcLoc)
targetTime := srcTime.In(targetLoc)
dayOffset := targetTime.Day() - srcTime.Day()
if dayOffset > 1 {
dayOffset = -1
} else if dayOffset < -1 {
dayOffset = 1
}
targetH := targetTime.Hour()
period := "AM"
displayHour := targetH
if targetH >= 12 {
period = "PM"
if targetH > 12 {
displayHour = targetH - 12
}
}
if displayHour == 0 {
displayHour = 12
}
if short {
return fmt.Sprintf("%d%s", displayHour, period), dayOffset
}
return fmt.Sprintf("%d:00 %s", displayHour, period), dayOffset
}