rrule2 0.15.0

A pure Rust implementation of recurrence rules as defined in the iCalendar RFC. Fork of the `rrule` crate with additional fixes.
Documentation
use std::str::FromStr;

use super::{regex::ParsedDateString, ParseError};
use crate::{core::Tz, NWeekday};
use chrono::{Duration, LocalResult, NaiveDate, NaiveDateTime, Offset, TimeZone, Weekday};

/// Resolves a naive local datetime to a zoned datetime, following the
/// interpretation rules of RFC 5545 ยง3.3.5:
///
/// - A local time that occurs twice (when changing from daylight to standard
///   time) is interpreted using the UTC offset before the transition, i.e.
///   the earlier of the two candidates.
/// - A local time that does not occur (when changing from standard to
///   daylight time) is interpreted using the UTC offset before the gap. For
///   example `TZID=America/New_York:20070311T023000` indicates 07:00 UTC,
///   which is 03:30 EDT.
fn resolve_local_datetime(tz: &Tz, naive: NaiveDateTime) -> chrono::DateTime<Tz> {
    match tz.from_local_datetime(&naive) {
        LocalResult::Single(datetime) => datetime,
        LocalResult::Ambiguous(datetime1, _datetime2) => datetime1,
        LocalResult::None => {
            // The local time falls in a gap created by a DST transition
            // (e.g. 02:30 on the day the clocks jump from 02:00 to 03:00).
            // Find the offset that was in effect just before the transition
            // and interpret the datetime with it. Stepping back an hour is
            // enough for all known real-world transitions, but keep stepping
            // back to stay robust for larger artificial ones.
            let mut offset = None;
            for hours in 1..=48 {
                if let Some(before) = naive.checked_sub_signed(Duration::hours(hours)) {
                    if let LocalResult::Single(before_dt) = tz.from_local_datetime(&before) {
                        offset = Some(*before_dt.offset());
                        break;
                    }
                }
            }
            match offset {
                Some(offset) => tz.from_utc_datetime(&(naive - offset.fix())),
                // No transition found nearby; interpret the datetime as-is.
                None => tz.from_utc_datetime(&naive),
            }
        }
    }
}

/// Attempts to convert a `str` to a `chrono_tz::Tz`.
pub(crate) fn parse_timezone(tz: &str) -> Result<Tz, ParseError> {
    chrono_tz::Tz::from_str(tz)
        .map_err(|_| ParseError::InvalidTimezone(tz.into()))
        .map(Tz::Tz)
}

/// Convert a datetime string and a timezone to a `chrono::DateTime<Tz>`.
/// If the string specifies a zulu timezone with `Z`, then the timezone
/// argument will be ignored.
pub(crate) fn datestring_to_date(
    dt: &str,
    tz: Option<Tz>,
    property: &str,
) -> Result<chrono::DateTime<Tz>, ParseError> {
    let ParsedDateString {
        year,
        month,
        day,
        time,
        flags,
    } = ParsedDateString::from_ical_datetime(dt).map_err(|_| ParseError::InvalidDateTime {
        value: dt.into(),
        property: property.into(),
    })?;

    // Combine parts to create data time.
    let date =
        NaiveDate::from_ymd_opt(year, month, day).ok_or_else(|| ParseError::InvalidDateTime {
            value: dt.into(),
            property: property.into(),
        })?;

    // Spec defines this is a date-time OR date
    // So the time can will be set to 0:0:0 if only a date is given.
    // https://icalendar.org/iCalendar-RFC-5545/3-8-2-4-date-time-start.html
    let (hour, min, sec) = if let Some(time) = time {
        (time.hour, time.min, time.sec)
    } else {
        (0, 0, 0)
    };
    let datetime = date
        .and_hms_opt(hour, min, sec)
        .ok_or_else(|| ParseError::InvalidDateTime {
            value: dt.into(),
            property: property.into(),
        })?;

    // Apply timezone appended to the datetime before converting to UTC.
    // For more info https://icalendar.org/iCalendar-RFC-5545/3-3-5-date-time.html
    let datetime: chrono::DateTime<Tz> = if flags.zulu_timezone_set {
        // If a `Z` is present, UTC should be used.
        chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(datetime, chrono::Utc)
            .with_timezone(&Tz::UTC)
    } else if let Some(tz) = tz {
        // Use the timezone specified in the `TZID`.
        resolve_local_datetime(&tz, datetime)
    } else {
        // Use the current system timezone.
        // TODO Add option to always use UTC when this is executed on a server.
        resolve_local_datetime(&Tz::LOCAL, datetime)
    };

    Ok(datetime)
}

/// Attempts to convert a `str` to a `Weekday`.
pub(crate) fn str_to_weekday(d: &str) -> Result<Weekday, ParseError> {
    let day = match &d.to_uppercase()[..] {
        "MO" => Weekday::Mon,
        "TU" => Weekday::Tue,
        "WE" => Weekday::Wed,
        "TH" => Weekday::Thu,
        "FR" => Weekday::Fri,
        "SA" => Weekday::Sat,
        "SU" => Weekday::Sun,
        _ => return Err(ParseError::InvalidWeekday(d.to_string())),
    };
    Ok(day)
}

/// Parse the "BYWEEKDAY" and "BYDAY" values
/// Example: `SU,MO,TU,WE,TH,FR` or `4MO` or `-1WE`
/// > For example, within a MONTHLY rule, +1MO (or simply 1MO) represents the first Monday
/// > within the month, whereas -1MO represents the last Monday of the month.
pub(crate) fn parse_weekdays(val: &str) -> Result<Vec<NWeekday>, ParseError> {
    let mut wdays = vec![];
    // Separate all days
    for day in val.split(',') {
        let wday = day.parse::<NWeekday>()?;
        wdays.push(wday);
    }
    Ok(wdays)
}

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

    const US_PACIFIC: Tz = Tz::US__Pacific;

    #[test]
    fn parses_valid_nweekdays() {
        let tests = [
            ("SU", vec![NWeekday::Every(Weekday::Sun)]),
            ("-12TU", vec![NWeekday::Nth(-12, Weekday::Tue)]),
            (
                "MO,WE",
                vec![NWeekday::Every(Weekday::Mon), NWeekday::Every(Weekday::Wed)],
            ),
            (
                "MO,WE,3TU,-4SA",
                vec![
                    NWeekday::Every(Weekday::Mon),
                    NWeekday::Every(Weekday::Wed),
                    NWeekday::Nth(3, Weekday::Tue),
                    NWeekday::Nth(-4, Weekday::Sat),
                ],
            ),
        ];

        for (input, expected_output) in tests {
            let output = parse_weekdays(input);
            assert_eq!(output, Ok(expected_output));
        }
    }

    #[test]
    fn nweekday_display_includes_nth_ordinal() {
        // Regression test for fmeringdal/rust-rrule#148: `Nth(1, ...)` must
        // serialize with the ordinal, since `MO` (= `Every`) and `1MO`
        // (= `Nth(1, ...)`) have different semantics.
        let tests = [
            (NWeekday::Every(Weekday::Mon), "MO"),
            (NWeekday::Nth(1, Weekday::Mon), "1MO"),
            (NWeekday::Nth(2, Weekday::Mon), "2MO"),
            (NWeekday::Nth(-1, Weekday::Thu), "-1TH"),
        ];

        for (nweekday, expected) in tests {
            assert_eq!(nweekday.to_string(), expected);
            // The serialized value parses back to the same value.
            assert_eq!(parse_weekdays(expected), Ok(vec![nweekday]));
        }
    }

    #[test]
    fn rejects_invalid_nweekdays() {
        let tests = ["", "    ", "fjoasfjapsjop", "MONDAY", "MONDAY, TUESDAY"];

        for input in tests {
            let res = parse_weekdays(input);
            assert!(res.is_err());
        }
    }

    #[test]
    fn parses_valid_weekdays() {
        let tests = [
            ("MO", Weekday::Mon),
            ("TU", Weekday::Tue),
            ("WE", Weekday::Wed),
            ("TH", Weekday::Thu),
            ("FR", Weekday::Fri),
            ("SA", Weekday::Sat),
            ("SU", Weekday::Sun),
        ];

        for (input, expected_output) in tests {
            let output = str_to_weekday(input);
            assert_eq!(output, Ok(expected_output));
        }
    }

    #[test]
    fn rejects_invalid_weekdays() {
        let tests = ["", "    ", "fjoasfjapsjop", "MONDAY", "MONDAY, TUESDAY"];

        for input in tests {
            let res = str_to_weekday(input);
            assert!(res.is_err());
        }
    }

    #[test]
    fn parses_valid_datestime_str() {
        let tests = [
            (
                "19970902T090000Z",
                None,
                Tz::UTC.with_ymd_and_hms(1997, 9, 2, 9, 0, 0).unwrap(),
            ),
            (
                "19970902T090000",
                Some(Tz::UTC),
                Tz::UTC.with_ymd_and_hms(1997, 9, 2, 9, 0, 0).unwrap(),
            ),
            (
                "19970902T090000",
                Some(US_PACIFIC),
                US_PACIFIC.with_ymd_and_hms(1997, 9, 2, 9, 0, 0).unwrap(),
            ),
            (
                "19970902T090000Z",
                Some(US_PACIFIC),
                // Timezone is overwritten by the zulu specified in the datetime string
                Tz::UTC.with_ymd_and_hms(1997, 9, 2, 9, 0, 0).unwrap(),
            ),
        ];

        for (datetime_str, timezone, expected_output) in tests {
            let output = datestring_to_date(datetime_str, timezone, "DTSTART");
            assert_eq!(output, Ok(expected_output));
        }
    }

    #[test]
    fn rejects_invalid_datetime_str() {
        let tests = [
            ("", None),
            ("TZID=America/New_York:19970902T090000", None),
            ("19970902T09", None),
            ("19970902T09", Some(US_PACIFIC)),
        ];

        for (datetime_str, timezone) in tests {
            let res = datestring_to_date(datetime_str, timezone, "DTSTART");
            assert!(res.is_err());
        }
    }
}