rtimelog 1.1.1

System for tracking time in a text-log-based format.
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
//! Module implementing parsing of human-readable text into a [`DateRange`].
//!
//! # Examples
//!
//! ```rust
//! use timelog::date::{DateRange, RangeParser};
//! use timelog::Result;
//!
//! # fn main() -> Result<()> {
//! let parser = RangeParser::default();
//! let range = parser.parse_from_str("last week")?;
//! print!("Dates: {} up to {}", range.start(), range.end());
//! #   Ok(())
//! # }
//! ```
//!
//! # Description
//!
//! The [`RangeParser`] converts a description of relative or absolute dates into a
//! range of dates expressed as a half-open range including the start date, but excluding
//! the end date.
//!
//! # Date Range Descriptors
//!
//! A date range descriptor can be supplied to the parser either as a &str containing the
//! descriptor or as an iterator returning separate words of the descriptor.
//!
//! The parser can handle date range descriptors of the following forms:
//!
//! A single date in one of the following forms:
//!
//! * yyyy-mm-dd
//! * today
//! * yesterday
//! * a day of the week: sunday, monday, tuesday, wednesday, ... etc.
//!
//! All but the first of the above strings parse to dates relative to the base date of the
//! parser. "Today" is the current date. "Yesterday" is the day before the current date. The
//! weekdays are the last instance of that day before today.
//!
//! This will result in a range spanning one day.
//!
//! A pair of dates in the forms above.
//!
//! This pair results in a range that covers the two supplied dates. If the dates are in order,
//! the start is the first date and end is the day after the second date. If the dates are out of
//! order, the parse will return an empty range.
//!
//! A range description in one of the following forms:
//!
//! * a month name: january, february, march, ... etc.
//! * a short (3 char) month name: jan, feb, mar, ... etc.
//! * a relative timeframe: (this|last) (week|month|year)
//! * the string "ytd"
//!
//! If the parser is given a month name, the range will cover the whole month with that name
//! before today.
//!
//! If the parser is given "this" followed by "week", "month", or "year", the resultant range
//! covers:
//!
//! * week: from the last Sunday to Saturday of this week,
//! * month: from the first day of the current month to last day of the month,
//! * year: from the January 1 of the current year to the last day of the year.
//!
//! If the parser is given "last" followed by "week", "month", or "year", the resultant range
//! covers:
//!
//! * week: from the two Sundays ago to last Saturday,
//! * month: from the first of the month before this one to the last day of that month,
//! * year: from January 1 of the year before the current one to December 31 of the same year.
//!
//! If the parser receives the string "ytd", the range will be from January 1 of the current year
//! up to today.

use chrono::Weekday;

use crate::date::{self, Date, DateError, DateRange};

/// Struct implementing the parser to generate a [`Date`] from a date description.
pub struct DateParser {
    base: Date
}

impl Default for DateParser {
    /// Return a [`DateParser`], parsing relative to today.
    fn default() -> Self { Self { base: Date::today() } }
}

impl DateParser {
    // Return a [`RangeParser`] with the specified base date.
    //
    // Explicitly not public, since it's used for testing.
    fn new(base: Date) -> Self { Self { base } }

    /// Parse the supplied string to return a [`Date`] if successful.
    ///
    /// # Errors
    ///
    /// - Return [`DateError::InvalidDate`] if the specification for a single day is not valid.
    /// - Return [`DateError::InvalidDaySpec`] if overall range specification is not valid.
    pub fn parse(&self, datespec: &str) -> date::Result<Date> {
        match datespec {
            "today" => Ok(self.base),
            "yesterday" => Ok(self.base.pred()),
            "sunday" | "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday" => {
                Ok(self.base.find_previous(weekday_from_str(datespec)?))
            }
            _ => datespec.parse()
        }
    }
}

/// Struct implementing the parser to generate a [`DateRange`] from a date range description.
pub struct RangeParser {
    base: Date
}

impl Default for RangeParser {
    /// Return a [`RangeParser`], parsing relative to today.
    fn default() -> Self { Self { base: Date::today() } }
}

// Convert weekday string into appropriate Weekday variant.
fn weekday_from_str(day: &str) -> date::Result<Weekday> {
    match day {
        "sunday"    => Ok(Weekday::Sun),
        "monday"    => Ok(Weekday::Mon),
        "tuesday"   => Ok(Weekday::Tue),
        "wednesday" => Ok(Weekday::Wed),
        "thursday"  => Ok(Weekday::Thu),
        "friday"    => Ok(Weekday::Fri),
        "saturday"  => Ok(Weekday::Sat),
        _ => Err(DateError::InvalidDaySpec(day.to_string()))
    }
}

fn month_from_name(name: &str) -> Option<u32> {
    let month = match name {
        "january" | "jan" => 1,
        "february" | "feb" => 2,
        "march" | "mar" => 3,
        "april" | "apr" => 4,
        "may" => 5,
        "june" | "jun" => 6,
        "july" | "jul" => 7,
        "august" | "aug" => 8,
        "september" | "sep" | "sept" => 9,
        "october" | "oct" => 10,
        "november" | "nov" => 11,
        "december" | "dec" => 12,
        _ => return None
    };
    Some(month)
}

impl RangeParser {
    // Return a [`RangeParser`] with the specified base date.
    #[cfg(test)]
    pub fn new(base: Date) -> Self { Self { base } }

    /// Parse the supplied string to return a [`DateRange`] if successful.
    ///
    /// # Errors
    ///
    /// - Return [`DateError::InvalidDate`] if the specification for a single day is not valid.
    /// - Return [`DateError::InvalidDaySpec`] if overall range specification is not valid.
    pub fn parse_from_str(&self, datespec: &str) -> date::Result<DateRange> {
        if datespec.is_empty() { return Ok(self.base.into()); }
        let mut iter = datespec.split_ascii_whitespace();
        self.parse(&mut iter).map(|(r, _)| r)
    }

    /// Parse the tokens from the supplied string iterator to return a tuple containing
    /// a [`DateRange`] and the last unused token if successful.
    ///
    /// # Errors
    ///
    /// - Return [`DateError::InvalidDate`] if the specification for a single day is not valid.
    /// - Return [`DateError::InvalidDaySpec`] if overall range specification is not valid.
    pub fn parse<'a, I>(&self, datespec: &mut I) -> date::Result<(DateRange, &'a str)>
    where
        I: Iterator<Item = &'a str>
    {
        let Some(token) = datespec.next() else {
            return Ok((self.base.into(), ""));
        };
        let ltoken = token.to_ascii_lowercase();
        // Parse month name
        if let Some(range) = self.month_range(ltoken.as_str()) {
            return Ok((range, ""));
        }

        let base = self.base;
        let range_opt = match ltoken.as_str() {
            "ytd" => {
                let start = base.year_start();
                DateRange::new_opt(start, base.succ())
            }
            "this" => {
                let Some(token) = datespec.next() else {
                    return Err(DateError::InvalidDaySpec(token.into()));
                };
                let ltoken = token.to_ascii_lowercase();
                match ltoken.as_str() {
                    "week" => DateRange::new_opt(base.week_start(), base.week_end().succ()),
                    "month" => DateRange::new_opt(base.month_start(), base.month_end().succ()),
                    "year" => DateRange::new_opt(base.year_start(), base.year_end().succ()),
                    _ => return Err(DateError::InvalidDaySpec(token.into()))
                }
            }
            "last" => {
                let Some(token) = datespec.next() else {
                    return Err(DateError::InvalidDate);
                };
                let ltoken = token.to_ascii_lowercase();
                match ltoken.as_str() {
                    "week" => {
                        let date = base.week_start();
                        DateRange::new_opt(date.pred().week_start(), date)
                    }
                    "month" => {
                        let date = base.month_start().pred().month_start();
                        DateRange::new_opt(date, date.month_end().succ())
                    }
                    "year" => {
                        let date = Date::new(base.year() - 1, 1, 1)?;
                        DateRange::new_opt(date, date.year_end().succ())
                    }
                    _ => return Err(DateError::InvalidDaySpec(token.into()))
                }
            }
            _ => None
        };

        if let Some(date_range) = range_opt {
            return Ok((date_range, ""));
        }

        // Parse one or two dates
        let dparser = DateParser::new(self.base);
        let Ok(start) = dparser.parse(&ltoken) else {
            return Ok((self.base.into(), token));
        };
        if let Some(token) = datespec.next() {
            let ltoken = token.to_ascii_lowercase();
            if let Ok(end) = dparser.parse(&ltoken) {
                let range = DateRange::new_opt(start, end.succ())
                    .ok_or(DateError::WrongDateOrder)?;
                return Ok((range, ""));
            }
            else {
                return Ok((start.into(), token));
            }
        }

        Ok((start.into(), ""))
    }

    // Utility method to parse a month name
    fn month_range(&self, token: &str) -> Option<DateRange> {
        let month = month_from_name(token)?;
        let this = self.base.month();
        let year = self.base.year();
        let year = if month < this { year } else { year - 1 };

        let start = Date::new(year, month, 1).ok()?;
        Some(DateRange { start, end: start.month_end().succ() })
    }
}

#[cfg(test)]
mod tests {
    use once_cell::sync::Lazy;
    use assert2::{assert, let_assert};
    use rstest::rstest;

    use super::*;
    use crate::date::{DateTime, Weekday};

    static BASE_DATE: Lazy<Date> = Lazy::new(
        || Date::new(2022, 11, 15).expect("Hardcoded value") // tuesday
    );
    static YESTERDAY: Lazy<Date> = Lazy::new(
        ||Date::new(2022, 11, 14).expect("Hardcoded date must work")
    );
    static HARD_DATE: Lazy<Date> = Lazy::new(
        ||Date::new(2022, 10, 20).expect("Hardcoded date must work")
    );

    // DateParser tests

    #[rstest]
    #[case("today", Date::today(), "today")]
    #[case("yesterday", Date::today().pred(), "yesterday")]
    fn test_date_parse(#[case]input: &str, #[case]expected: Date, #[case]msg: &str) {
        let p = DateParser::default();
        let_assert!(Ok(actual) = p.parse(input));
        assert!(actual == expected, "{msg}");
    }

    #[test]
    fn test_date_parse_weekdays() {
        let max_dur = DateTime::days(7);
        #[rustfmt::skip]
        let days: [&str; 7] = [
            "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"
        ];
        let today = Date::today();
        let midnight = Date::today().day_end();
        let p = DateParser::default();
        days.iter().for_each(|&day| {
            let_assert!(Ok(date) = p.parse(day), "parse {day}");
            assert!(date < today);

            let end_of_date = date.day_end();
            let_assert!(Ok(dur) = midnight - end_of_date, "end {day}");
            assert!(dur <= max_dur);
        });
    }

    // RangeParser tests

    fn test_range_parser() -> RangeParser { RangeParser::new(*BASE_DATE) }

    #[test]
    fn test_parse_default() {
        let p = RangeParser::default();
        let expect: DateRange = DateRange::default();
        let_assert!(Ok(actual) = p.parse_from_str(""));
        assert!(actual == expect);
    }

    #[rstest]
    #[case("", (*BASE_DATE).into(), "new")]
    #[case("today", (*BASE_DATE).into(), "today")]
    #[case("yesterday", (*YESTERDAY).into(), "yesterday")]
    #[case("2022-10-20", (*HARD_DATE).into(), "actual date")]
    #[case("monday", DateRange::from(BASE_DATE.find_previous(Weekday::Mon)), "dayname")]
    #[case("wednesday", DateRange::from(BASE_DATE.find_previous(Weekday::Wed)), "later dayname")]
    fn test_date_range_parser_one_day(#[case]input: &str, #[case]expect: DateRange, #[case]msg: &str) {
        let p = test_range_parser();
        let_assert!(Ok(actual) = p.parse_from_str(input));
        assert!(actual == expect, "{msg}");
    }

    // two date parses

    #[test]
    fn test_dates_both_dates() {
        let_assert!(Ok(start) = Date::new(2021, 12, 1));
        let_assert!(Ok(end) = Date::new(2021, 12, 8));
        let expected = DateRange::new(start, end);

        let p = test_range_parser();
        let_assert!(Ok(actual) = p.parse_from_str("2021-12-01 2021-12-07"));
        assert!(actual == expected);
    }

    #[test]
    fn test_dates_both_dates_desc() {
        let_assert!(Ok(start) = Date::new(2022, 11, 13));
        let expected = DateRange::new(start, BASE_DATE.succ());

        let p = test_range_parser();
        let_assert!(Ok(actual) = p.parse_from_str("sunday today"));
        assert!(actual == expected);
    }

    // relative range parses

    #[rstest]
    #[case("january", Date::new(2022, 1, 1), Date::new(2022, 2, 1))]
    #[case("jan", Date::new(2022, 1, 1), Date::new(2022, 2, 1))]
    #[case("february", Date::new(2022, 2, 1), Date::new(2022, 3, 1))]
    #[case("feb", Date::new(2022, 2, 1), Date::new(2022, 3, 1))]
    #[case("march", Date::new(2022, 3, 1), Date::new(2022, 4, 1))]
    #[case("mar", Date::new(2022, 3, 1), Date::new(2022, 4, 1))]
    #[case("april", Date::new(2022, 4, 1), Date::new(2022, 5, 1))]
    #[case("apr", Date::new(2022, 4, 1), Date::new(2022, 5, 1))]
    #[case("may", Date::new(2022, 5, 1), Date::new(2022, 6, 1))]
    #[case("june", Date::new(2022, 6, 1), Date::new(2022, 7, 1))]
    #[case("jun", Date::new(2022, 6, 1), Date::new(2022, 7, 1))]
    #[case("july", Date::new(2022, 7, 1), Date::new(2022, 8, 1))]
    #[case("jul", Date::new(2022, 7, 1), Date::new(2022, 8, 1))]
    #[case("august", Date::new(2022, 8, 1), Date::new(2022, 9, 1))]
    #[case("aug", Date::new(2022, 8, 1), Date::new(2022, 9, 1))]
    #[case("september", Date::new(2022, 9, 1), Date::new(2022, 10, 1))]
    #[case("sep", Date::new(2022, 9, 1), Date::new(2022, 10, 1))]
    #[case("october", Date::new(2022, 10, 1), Date::new(2022, 11, 1))]
    #[case("oct", Date::new(2022, 10, 1), Date::new(2022, 11, 1))]
    #[case("november", Date::new(2021, 11, 1), Date::new(2021, 12, 1))]
    #[case("nov", Date::new(2021, 11, 1), Date::new(2021, 12, 1))]
    #[case("december", Date::new(2021, 12, 1), Date::new(2022, 1, 1))]
    #[case("dec", Date::new(2021, 12, 1), Date::new(2022, 1, 1))]
    fn test_month_name(
        #[case]name: &str,
        #[case]start_opt: Result<Date, DateError>,
        #[case]end_opt: Result<Date, DateError>
    ) {
        let p = test_range_parser();
        let_assert!(Ok(start) = start_opt.as_ref());
        let_assert!(Ok(end) = end_opt.as_ref());
        let expected = DateRange::new(*start, *end);
        let_assert!(Ok(actual) = p.parse_from_str(name));
        assert!(actual == expected);
    }

    #[rstest]
    #[case("this week", Date::new(2022, 11, 13), Date::new(2022, 11, 20))]
    #[case("this month", Date::new(2022, 11, 1), Date::new(2022, 12, 1))]
    #[case("this year", Date::new(2022, 1, 1), Date::new(2023, 1, 1))]
    #[case("ytd", Date::new(2022, 1, 1), Ok(BASE_DATE.succ()))]
    #[case("last week", Date::new(2022, 11, 6), Date::new(2022, 11, 13))]
    #[case("last month", Date::new(2022, 10, 1), Date::new(2022, 11, 1))]
    #[case("last year", Date::new(2021, 1, 1), Date::new(2022, 1, 1))]
    fn test_special_range(
        #[case]input: &str,
        #[case]start_opt: Result<Date, DateError>,
        #[case]end_opt: Result<Date, DateError>
    ) {
        let_assert!(Ok(start) = start_opt);
        let_assert!(Ok(end) = end_opt);
        let expected = DateRange::new(start, end);

        let p = test_range_parser();
        let_assert!(Ok(actual) = p.parse_from_str(input), "parsing '{input}'");
        assert!(actual == expected);
    }
}