marathon-core 0.1.1

Marathon's rules: sessions, timers, triggers and time parsing
Documentation
//! Parsing of how long to stay awake: `2h`, `1h30m`, `90` (minutes),
//! `until 17:30`, `5:30pm`, `forever`.

use std::fmt;
use std::time::Duration;

use jiff::civil::Time;
use jiff::{Timestamp, tz::TimeZone};

/// When a session should end, as the user wrote it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Until {
    /// No end time.
    Indefinite,
    /// A fixed length from now.
    For(Duration),
    /// The next time the local clock shows this time.
    At(Time),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError(String);

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for ParseError {}

fn err(input: &str) -> ParseError {
    ParseError(format!(
        "can't read {input:?} as a duration; try 2h, 45m, 1h30m, 90 (minutes), 17:30, 5:30pm or forever"
    ))
}

impl Until {
    /// Parses a duration or clock time. A bare number means minutes.
    pub fn parse(input: &str) -> Result<Self, ParseError> {
        let s = input.trim().to_ascii_lowercase();
        let s = s
            .strip_prefix("until")
            .or_else(|| s.strip_prefix('@'))
            .map(str::trim)
            .unwrap_or(&s);
        match s {
            "" => return Err(err(input)),
            "forever" | "indefinitely" | "indefinite" | "inf" => return Ok(Until::Indefinite),
            _ => {}
        }
        if let Some(t) = parse_clock(s) {
            return Ok(Until::At(t));
        }
        if let Ok(minutes) = s.parse::<u64>() {
            return positive(Duration::from_secs(minutes.saturating_mul(60)), input);
        }
        parse_units(s)
            .ok_or_else(|| err(input))
            .and_then(|d| positive(d, input))
    }

    /// Resolves to a wall-clock deadline, or `None` for no end time.
    /// A clock time already past today means tomorrow.
    pub fn resolve(self, now: Timestamp, tz: &TimeZone) -> Option<Timestamp> {
        match self {
            Until::Indefinite => None,
            Until::For(d) => Some(now.saturating_add(d).unwrap_or(Timestamp::MAX)),
            Until::At(t) => {
                let today = tz.to_datetime(now).date();
                let at = tz.to_timestamp(today.to_datetime(t)).ok()?;
                if at > now {
                    return Some(at);
                }
                tz.to_timestamp(today.tomorrow().ok()?.to_datetime(t)).ok()
            }
        }
    }
}

/// Ten years: longer than anyone means, and keeps deadlines meaningful.
const MAX_SECS: f64 = 315_360_000.0;

fn positive(d: Duration, input: &str) -> Result<Until, ParseError> {
    if d.as_secs_f64() > MAX_SECS {
        Err(ParseError(format!(
            "{input:?} is too long; the most is 10 years"
        )))
    } else if d.is_zero() {
        Err(ParseError(format!(
            "{input:?} is zero; give a length above zero"
        )))
    } else {
        Ok(Until::For(d))
    }
}

/// `1h30m`, `2h`, `45m`, `30s`, `1d`, `1.5h`, with optional spaces.
fn parse_units(s: &str) -> Option<Duration> {
    let mut total = 0f64;
    let mut rest = s;
    while !rest.is_empty() {
        let num_len = rest
            .find(|c: char| !(c.is_ascii_digit() || c == '.'))
            .unwrap_or(rest.len());
        if num_len == 0 {
            return None;
        }
        let n: f64 = rest[..num_len].parse().ok()?;
        rest = rest[num_len..].trim_start();
        let unit_len = rest
            .find(|c: char| !c.is_ascii_alphabetic())
            .unwrap_or(rest.len());
        let secs = match &rest[..unit_len] {
            "s" | "sec" | "secs" | "second" | "seconds" => 1.0,
            "m" | "min" | "mins" | "minute" | "minutes" => 60.0,
            "h" | "hr" | "hrs" | "hour" | "hours" => 3600.0,
            "d" | "day" | "days" => 86400.0,
            _ => return None,
        };
        total += n * secs;
        rest = rest[unit_len..].trim_start();
    }
    (total.is_finite() && total <= MAX_SECS).then(|| Duration::from_secs_f64(total))
}

/// `17:30`, `5:30pm`, `5pm`, `5 pm`, `12am`.
fn parse_clock(s: &str) -> Option<Time> {
    let (body, pm) = match s.strip_suffix("pm").or_else(|| s.strip_suffix("p")) {
        Some(b) => (b.trim(), Some(true)),
        None => match s.strip_suffix("am").or_else(|| s.strip_suffix("a")) {
            Some(b) => (b.trim(), Some(false)),
            None => (s, None),
        },
    };
    let (h, m) = match body.split_once(':') {
        Some((h, m)) if m.len() == 2 => (h.parse::<i8>().ok()?, m.parse::<i8>().ok()?),
        None if pm.is_some() => (body.parse::<i8>().ok()?, 0),
        _ => return None,
    };
    let hour = match pm {
        None => h,
        Some(_) if !(1..=12).contains(&h) => return None,
        Some(true) => h % 12 + 12,
        Some(false) => h % 12,
    };
    Time::new(hour, m, 0, 0).ok()
}

/// A deadline as a local 24-hour clock time, e.g. `17:30`.
pub fn format_clock(at: Timestamp, tz: &TimeZone) -> String {
    format_time(tz.to_datetime(at).time())
}

/// A time of day on the 24-hour clock, e.g. `09:00`.
pub fn format_time(t: jiff::civil::Time) -> String {
    t.strftime("%H:%M").to_string()
}

/// Short human form of what is left: `2h 05m`, `14m`, `45s`.
/// Minutes round up, like the menu bar countdown, so `on 2m` reads "2m".
pub fn format_remaining(d: Duration) -> String {
    let secs = d.as_secs();
    if secs < 60 {
        return format!("{secs}s");
    }
    let minutes = secs.div_ceil(60);
    let (h, m) = (minutes / 60, minutes % 60);
    if h > 0 {
        format!("{h}h {m:02}m")
    } else {
        format!("{m}m")
    }
}

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

    fn min(m: u64) -> Until {
        Until::For(Duration::from_secs(m * 60))
    }

    #[test]
    fn parses_lengths() {
        assert_eq!(Until::parse("2h").unwrap(), min(120));
        assert_eq!(Until::parse("1h30m").unwrap(), min(90));
        assert_eq!(Until::parse("1h 30m").unwrap(), min(90));
        assert_eq!(Until::parse("90").unwrap(), min(90));
        assert_eq!(Until::parse("1.5h").unwrap(), min(90));
        assert_eq!(Until::parse("45 minutes").unwrap(), min(45));
        assert_eq!(Until::parse("1d").unwrap(), min(1440));
        assert_eq!(
            Until::parse("30s").unwrap(),
            Until::For(Duration::from_secs(30))
        );
        assert_eq!(Until::parse("Forever").unwrap(), Until::Indefinite);
    }

    #[test]
    fn parses_clock_times() {
        let t = |h, m| Until::At(Time::new(h, m, 0, 0).unwrap());
        assert_eq!(Until::parse("17:30").unwrap(), t(17, 30));
        assert_eq!(Until::parse("until 17:30").unwrap(), t(17, 30));
        assert_eq!(Until::parse("@9:05").unwrap(), t(9, 5));
        assert_eq!(Until::parse("5:30pm").unwrap(), t(17, 30));
        assert_eq!(Until::parse("5 PM").unwrap(), t(17, 0));
        assert_eq!(Until::parse("12am").unwrap(), t(0, 0));
        assert_eq!(Until::parse("12pm").unwrap(), t(12, 0));
    }

    #[test]
    fn rejects_nonsense() {
        for bad in [
            "",
            "0",
            "0m",
            "h",
            "2x",
            "25:00",
            "13pm",
            "1:5",
            "-5m",
            "1e400h",
            "99999999999d",
        ] {
            assert!(Until::parse(bad).is_err(), "{bad:?} should fail");
        }
    }

    #[test]
    fn clock_time_rolls_to_tomorrow() {
        let tz = TimeZone::UTC;
        let now: Timestamp = "2026-12-03T18:00:00Z".parse().unwrap();
        let later = Until::parse("19:00").unwrap().resolve(now, &tz).unwrap();
        assert_eq!(later, "2026-12-03T19:00:00Z".parse().unwrap());
        let earlier = Until::parse("17:00").unwrap().resolve(now, &tz).unwrap();
        assert_eq!(earlier, "2026-12-04T17:00:00Z".parse().unwrap());
        let same = Until::parse("18:00").unwrap().resolve(now, &tz).unwrap();
        assert_eq!(same, "2026-12-04T18:00:00Z".parse().unwrap());
    }

    #[test]
    fn clock_time_respects_zone() {
        let tz = TimeZone::get("America/Los_Angeles").unwrap();
        let now: Timestamp = "2026-12-03T21:00:00Z".parse().unwrap(); // 13:00 PST
        let at = Until::parse("5pm").unwrap().resolve(now, &tz).unwrap();
        assert_eq!(at, "2026-12-04T01:00:00Z".parse().unwrap());
    }

    #[test]
    fn formats_remaining() {
        assert_eq!(format_remaining(Duration::from_secs(7500)), "2h 05m");
        assert_eq!(format_remaining(Duration::from_secs(840)), "14m");
        assert_eq!(format_remaining(Duration::from_secs(45)), "45s");
        assert_eq!(format_remaining(Duration::from_secs(119)), "2m");
        assert_eq!(format_remaining(Duration::from_secs(3599)), "1h 00m");
    }
}