saffron 0.1.0

A Quartz-like cron parser used as part of Cron Triggers in Cloudflare Workers
Documentation
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
use crate::describe::{display, Language};
use crate::parse::*;
use chrono::NaiveTime;
use core::fmt::{self, Display, Formatter};

fn postfixed<T: Into<usize>>(x: T) -> impl Display {
    let x: usize = x.into();
    display(move |f| match x % 100 {
        1 => write!(f, "{}st", x),
        2 => write!(f, "{}nd", x),
        3 => write!(f, "{}rd", x),
        20..=99 => match x % 10 {
            1 => write!(f, "{}st", x),
            2 => write!(f, "{}nd", x),
            3 => write!(f, "{}rd", x),
            _ => write!(f, "{}th", x),
        },
        _ => write!(f, "{}th", x),
    })
}

fn weekday<T: Into<chrono::Weekday>>(x: T) -> impl Display {
    use chrono::Weekday::*;
    let x: chrono::Weekday = x.into();
    display(move |f| match x {
        Mon => write!(f, "Monday"),
        Tue => write!(f, "Tuesday"),
        Wed => write!(f, "Wednesday"),
        Thu => write!(f, "Thursday"),
        Fri => write!(f, "Friday"),
        Sat => write!(f, "Saturday"),
        Sun => write!(f, "Sunday"),
    })
}

/// Specifies whether to display times with a 12 hour or 24 hour clock.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HourFormat {
    /// Format using a 12 hour clock (i.e. 6:30 PM)
    Hour12,
    /// Format using a 24 hour clock (i.e. 18:30)
    Hour24,
}

impl Default for HourFormat {
    fn default() -> Self {
        HourFormat::Hour12
    }
}

/// English language formatting
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct English {
    /// Configures how hours are formatted in descriptions
    pub hour: HourFormat,
}

impl English {
    /// Creates a new instance of the english configuration with its default values
    pub const fn new() -> Self {
        Self {
            hour: HourFormat::Hour12,
        }
    }
}

impl Default for English {
    fn default() -> Self {
        Self::new()
    }
}

impl English {
    fn minute(&self, h: OrsExpr<Minute>) -> impl Display {
        display(move |f| match h {
            OrsExpr::One(minute) => write!(f, "{}", u8::from(minute)),
            OrsExpr::Range(start, end) => {
                write!(f, "{} through {}", u8::from(start), u8::from(end))
            }
            OrsExpr::Step { start, end, step } => write!(
                f,
                "every {} minute from {} through {}",
                postfixed(u8::from(step)),
                u8::from(start),
                u8::from(end)
            ),
        })
    }
    fn hour<'a>(&'a self, h: OrsExpr<Hour>) -> impl Display + 'a {
        display(move |f| match h {
            OrsExpr::One(hour) => write!(
                f,
                "between {} and {}",
                self.time(hour, 0),
                self.time(hour, 59)
            ),
            OrsExpr::Range(start, end) => write!(
                f,
                "between {} and {}",
                self.time(start, 0),
                self.time(end, 59)
            ),
            OrsExpr::Step { start, end, step } => write!(
                f,
                "every {} hour between {} and {}",
                postfixed(u8::from(step)),
                self.time(start, 0),
                self.time(end, 59)
            ),
        })
    }
    fn month(&self, h: OrsExpr<Month>) -> impl Display {
        display(move |f| match h {
            OrsExpr::One(month) => write!(f, "{}", chrono::Month::from(month).name()),
            OrsExpr::Range(start, end) => write!(
                f,
                "{} to {}",
                chrono::Month::from(start).name(),
                chrono::Month::from(end).name()
            ),
            OrsExpr::Step { start, end, step } => write!(
                f,
                "every {} month from {} to {}",
                postfixed(u8::from(step)),
                chrono::Month::from(start).name(),
                chrono::Month::from(end).name()
            ),
        })
    }
    fn day_of_week(&self, h: OrsExpr<DayOfWeek>) -> impl Display {
        display(move |f| match h {
            OrsExpr::One(dow) => write!(f, "{}", weekday(dow)),
            OrsExpr::Range(start, end) => write!(f, "{} through {}", weekday(start), weekday(end)),
            OrsExpr::Step { start, end, step } => write!(
                f,
                "every {} weekday {} through {}",
                postfixed(u8::from(step)),
                weekday(start),
                weekday(end)
            ),
        })
    }
    fn day_of_month(&self, h: OrsExpr<DayOfMonth>) -> impl Display {
        display(move |f| match h {
            OrsExpr::One(dom) => write!(f, "{}", postfixed(u8::from(dom) + 1)),
            OrsExpr::Range(start, end) => write!(
                f,
                "{} to {}",
                postfixed(u8::from(start) + 1),
                postfixed(u8::from(end) + 1)
            ),
            OrsExpr::Step { start, end, step } => write!(
                f,
                "every {} day from the {} to the {}",
                postfixed(u8::from(step)),
                postfixed(u8::from(start) + 1),
                postfixed(u8::from(end) + 1)
            ),
        })
    }
    fn time<H: Into<u8>, M: Into<u8>>(&self, hour: H, minute: M) -> impl Display {
        let time = NaiveTime::from_hms(hour.into() as u32, minute.into() as u32, 0);
        let fmt = match self.hour {
            HourFormat::Hour12 => "%-I:%M %p",
            HourFormat::Hour24 => "%H:%M",
        };
        time.format(fmt)
    }
}
impl Language for English {
    fn fmt_expr(&self, expr: &CronExpr, f: &mut Formatter) -> fmt::Result {
        match (&expr.minutes, &expr.hours) {
            (Expr::All, Expr::All) => write!(f, "Every minute")?,
            (Expr::All, Expr::Many(Exprs { first, tail })) => {
                let first = first.normalize();
                write!(f, "Every minute ")?;
                match tail.as_slice() {
                    [] => write!(f, "{}", self.hour(first))?,
                    [second] => write!(
                        f,
                        "{} and {}",
                        self.hour(first),
                        self.hour(second.normalize())
                    )?,
                    [middle @ .., last] => {
                        write!(f, "{}, ", self.hour(first))?;
                        for expr in middle {
                            write!(f, "{}, ", self.hour(expr.normalize()))?;
                        }
                        write!(f, "and {}", self.hour(last.normalize()))?;
                    }
                }
            }
            (Expr::Many(Exprs { first, tail }), Expr::All) => {
                let first = first.normalize();
                match tail.as_slice() {
                    [] => match first {
                        OrsExpr::One(value) => match u8::from(value) {
                            0 => write!(f, "Every hour"),
                            1 => write!(f, "At 1 minute past the hour"),
                            v => write!(f, "At {} minutes past the hour", v),
                        }?,
                        OrsExpr::Range(start, end) => write!(
                            f,
                            "Minutes {} through {} past the hour",
                            u8::from(start),
                            u8::from(end)
                        )?,
                        OrsExpr::Step { start, end, step } => write!(
                            f,
                            "Every {} minute starting from minute {} to minute {} past the hour",
                            postfixed(u8::from(step)),
                            u8::from(start),
                            u8::from(end),
                        )?,
                    },
                    [second] => write!(
                        f,
                        "At {} and {} minutes past the hour",
                        self.minute(first),
                        self.minute(second.normalize())
                    )?,
                    [middle @ .., last] => {
                        write!(f, "At {}, ", self.minute(first))?;
                        for expr in middle {
                            write!(f, "{}, ", self.minute(expr.normalize()))?;
                        }
                        write!(
                            f,
                            "and {} minutes past the hour",
                            self.minute(last.normalize())
                        )?;
                    }
                }
            }
            (
                Expr::Many(Exprs {
                    first: first_minute,
                    tail: tail_minutes,
                }),
                Expr::Many(Exprs {
                    first: first_hour,
                    tail: tail_hours,
                }),
            ) => {
                let first_minute = first_minute.normalize();
                let tail_minutes = tail_minutes.as_slice();
                let first_hour = first_hour.normalize();
                let tail_hours = tail_hours.as_slice();
                if let (OrsExpr::One(minute), [], OrsExpr::One(hour), []) =
                    (first_minute, tail_minutes, first_hour, tail_hours)
                {
                    write!(f, "At {}", self.time(hour, minute))?;
                } else {
                    match tail_minutes {
                        [] => write!(
                            f,
                            "At {} minutes past the hour, ",
                            self.minute(first_minute)
                        )?,
                        [second] => write!(
                            f,
                            "At {} and {} minutes past the hour, ",
                            self.minute(first_minute),
                            self.minute(second.normalize())
                        )?,
                        [middle @ .., last] => {
                            write!(f, "At {}, ", self.minute(first_minute))?;
                            for expr in middle {
                                write!(f, "{}, ", self.minute(expr.normalize()))?;
                            }
                            write!(f, "and {}, ", self.minute(last.normalize()))?;
                        }
                    }

                    match tail_hours {
                        [] => write!(f, "{}", self.hour(first_hour))?,
                        [second] => write!(
                            f,
                            "{} and {}",
                            self.hour(first_hour),
                            self.hour(second.normalize())
                        )?,
                        [middle @ .., last] => {
                            write!(f, "{}, ", self.hour(first_hour))?;
                            for expr in middle {
                                write!(f, "{}, ", self.hour(expr.normalize()))?;
                            }
                            write!(f, "and {}", self.hour(last.normalize()))?;
                        }
                    }
                }
            }
        }

        match &expr.doms {
            DayOfMonthExpr::All => {}
            &DayOfMonthExpr::ClosestWeekday(day) => write!(
                f,
                " on the closest weekday to the {}",
                postfixed(u8::from(day) + 1)
            )?,
            DayOfMonthExpr::Last(Last::Day) => write!(f, " on the last day")?,
            DayOfMonthExpr::Last(Last::Weekday) => write!(f, " on the last weekday")?,
            &DayOfMonthExpr::Last(Last::Offset(offset)) => {
                write!(f, " on the {} to last day", postfixed(u8::from(offset) + 1))?
            }
            &DayOfMonthExpr::Last(Last::OffsetWeekday(offset)) => write!(
                f,
                " on the closest weekday to the {} to last day",
                postfixed(u8::from(offset) + 1)
            )?,
            DayOfMonthExpr::Many(Exprs { first, tail }) => {
                let first = first.normalize();
                match tail.as_slice() {
                    [] => write!(f, " on the {}", self.day_of_month(first))?,
                    [second] => write!(
                        f,
                        " on the {} and {}",
                        self.day_of_month(first),
                        self.day_of_month(second.normalize())
                    )?,
                    [middle @ .., last] => {
                        write!(f, " on the {}, ", self.day_of_month(first))?;
                        for expr in middle {
                            write!(f, "{}, ", self.day_of_month(expr.normalize()))?;
                        }
                        write!(f, "and {}", self.day_of_month(last.normalize()))?;
                    }
                }
            }
        }

        match (&expr.doms, &expr.dows) {
            (DayOfMonthExpr::All, _) | (_, DayOfWeekExpr::All) => {}
            _ => write!(f, " and")?,
        }

        match &expr.dows {
            DayOfWeekExpr::All => {}
            &DayOfWeekExpr::Last(day) => write!(f, " on the last {}", weekday(day))?,
            &DayOfWeekExpr::Nth(day, nth) => {
                write!(f, " on the {} {}", postfixed(u8::from(nth)), weekday(day))?
            }
            DayOfWeekExpr::Many(Exprs { first, tail }) => {
                let first = first.normalize();
                match tail.as_slice() {
                    [] => write!(f, " on {}", self.day_of_week(first))?,
                    [second] => write!(
                        f,
                        " on {} and {}",
                        self.day_of_week(first),
                        self.day_of_week(second.normalize())
                    )?,
                    [middle @ .., last] => {
                        write!(f, " on {}, ", self.day_of_week(first))?;
                        for expr in middle {
                            write!(f, "{}, ", self.day_of_week(expr.normalize()))?;
                        }
                        write!(f, "and {}", self.day_of_week(last.normalize()))?;
                    }
                }
            }
        }

        let Exprs { first, tail } = match (&expr.doms, &expr.months, &expr.dows) {
            (DayOfMonthExpr::All, Expr::All, DayOfWeekExpr::All)
            | (DayOfMonthExpr::All, Expr::All, DayOfWeekExpr::Many(_)) => return Ok(()),
            (_, Expr::All, _) => {
                write!(f, " of every month")?;
                return Ok(());
            }
            (DayOfMonthExpr::All, Expr::Many(exprs), DayOfWeekExpr::All) => {
                write!(f, " every day in ")?;
                exprs
            }
            (_, Expr::Many(exprs), _) => {
                write!(f, " of ")?;
                exprs
            }
        };

        let first = first.normalize();
        match tail.as_slice() {
            [] => write!(f, "{}", self.month(first))?,
            [second] => write!(
                f,
                "{} and {}",
                self.month(first),
                self.month(second.normalize())
            )?,
            [middle @ .., last] => {
                write!(f, "{}, ", self.month(first))?;
                for expr in middle {
                    write!(f, "{}, ", self.month(expr.normalize()))?;
                }
                write!(f, "and {}", self.month(last.normalize()))?;
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(not(feature = "std"))]
    use alloc::string::ToString;

    const CFG_24_HOURS: English = English {
        hour: HourFormat::Hour24,
        ..English::new()
    };

    #[track_caller]
    fn assert_cfg(cfg: English, cron: &str, expected: &str) {
        let expr: CronExpr = cron.parse().expect("Valid cron expression");
        let description = expr.describe(cfg).to_string();

        assert_eq!(description, expected);
    }

    #[track_caller]
    fn assert(cron: &str, expected: &str) {
        let expr: CronExpr = cron.parse().expect("Valid cron expression");
        let description = expr.describe(English::new()).to_string();

        assert_eq!(description, expected);
    }

    #[test]
    fn time() {
        assert("* * * * *", "Every minute");
        assert("0 * * * *", "Every hour");
        assert("0 0 * * *", "At 12:00 AM");
        assert_cfg(CFG_24_HOURS, "0 0 * * *", "At 00:00");
        assert("0,1 * * * *", "At 0 and 1 minutes past the hour");
        assert(
            "0,1-5,10-30/2 * * * *",
            "At 0, 1 through 5, and every 2nd minute from 10 through 30 minutes past the hour",
        );
        assert(
            "0 2,3 * * *",
            "At 0 minutes past the hour, between 2:00 AM and 2:59 AM and between 3:00 AM and 3:59 AM",
        );
        assert(
            "0 2,5-10,*/2 * * *",
            "At 0 minutes past the hour, between 2:00 AM and 2:59 AM, between 5:00 AM and 10:59 AM, and every 2nd hour between 12:00 AM and 11:59 PM",
        );
    }

    #[test]
    fn day_of_month() {
        assert("* * L * *", "Every minute on the last day of every month");
        assert(
            "* * LW * *",
            "Every minute on the last weekday of every month",
        );
        assert(
            "* * L-1 * *",
            "Every minute on the 2nd to last day of every month",
        );
        assert(
            "* * L-1W * *",
            "Every minute on the closest weekday to the 2nd to last day of every month",
        );
        assert(
            "* * 15W * *",
            "Every minute on the closest weekday to the 15th of every month",
        );
        assert("* * 15 * *", "Every minute on the 15th of every month");
        assert(
            "* * 1,15 * *",
            "Every minute on the 1st and 15th of every month",
        );
        assert(
            "* * 1,10-20,20/2 * *",
            "Every minute on the 1st, 10th to 20th, and every 2nd day from the 20th to the 31st of every month"
        );
    }

    #[test]
    fn months() {
        assert("* * * FEB *", "Every minute every day in February");
        assert(
            "* * * JAN,FEB *",
            "Every minute every day in January and February",
        );
        assert(
            "* * * JAN,JUN-AUG,*/2 *",
            "Every minute every day in January, June to August, and every 2nd month from January to December"
        );
    }

    #[test]
    fn complex() {
        // test some complex expressions with all fields filled
        assert(
            "0 0 LW */2 FRIL",
            "At 12:00 AM on the last weekday and on the last Friday of every 2nd month from January to December"
        );
        assert(
            "0 0,12 L FEB FRI",
            "At 0 minutes past the hour, between 12:00 AM and 12:59 AM and between 12:00 PM and 12:59 PM on the last day and on Friday of February"
        );
    }

    #[test]
    fn day_of_week() {
        assert(
            "* * * * MONL",
            "Every minute on the last Monday of every month",
        );
        assert(
            "* * * * MON#5",
            "Every minute on the 5th Monday of every month",
        );
        assert("* * * * MON", "Every minute on Monday");
        assert("* * * * SUN,SAT", "Every minute on Sunday and Saturday");
        assert("* * * * */3,SAT,MON-FRI", "Every minute on every 3rd weekday Sunday through Saturday, Saturday, and Monday through Friday");
    }
}