Skip to main content

markdoc_pdf/
dates.rs

1//! Date helpers for PDF document metadata.
2//!
3//! krilla's `Metadata::creation_date` takes a `DateTime` built from
4//! year/month/day/hour/minute/second/utc-offset components. This module
5//! converts from the most common sources:
6//!   - ISO date / datetime strings (`"2025-11-04"` or
7//!     `"2025-11-04T08:30:00Z"`) commonly found in Markdoc frontmatter.
8//!   - The current system time, for build-time stamping.
9
10use krilla::metadata::DateTime;
11use time::format_description::well_known::Iso8601;
12use time::{Date, OffsetDateTime, PrimitiveDateTime};
13
14/// Convert a `time::OffsetDateTime` into krilla's `DateTime` builder
15/// chain.
16fn from_offset_dt(dt: OffsetDateTime) -> DateTime {
17    let mut out = DateTime::new(dt.year() as u16)
18        .month(dt.month() as u8)
19        .day(dt.day())
20        .hour(dt.hour())
21        .minute(dt.minute())
22        .second(dt.second());
23    let offset_h = dt.offset().whole_hours();
24    let offset_m = (dt.offset().whole_minutes() % 60).unsigned_abs() as u8;
25    out = out.utc_offset_hour(offset_h);
26    if offset_m != 0 {
27        out = out.utc_offset_minute(offset_m);
28    }
29    out
30}
31
32fn from_primitive_dt(dt: PrimitiveDateTime) -> DateTime {
33    DateTime::new(dt.year() as u16)
34        .month(dt.month() as u8)
35        .day(dt.day())
36        .hour(dt.hour())
37        .minute(dt.minute())
38        .second(dt.second())
39        .utc_offset_hour(0)
40}
41
42fn from_date(d: Date) -> DateTime {
43    DateTime::new(d.year() as u16)
44        .month(d.month() as u8)
45        .day(d.day())
46}
47
48/// Parse a permissive ISO date / datetime string into a krilla
49/// `DateTime`. Accepts:
50///   - `YYYY-MM-DD`
51///   - `YYYY-MM-DDTHH:MM:SS`
52///   - `YYYY-MM-DDTHH:MM:SSZ` / with offset
53pub fn parse_iso(s: &str) -> Option<DateTime> {
54    let trimmed = s.trim();
55    if trimmed.is_empty() {
56        return None;
57    }
58    if let Ok(dt) = OffsetDateTime::parse(trimmed, &Iso8601::DEFAULT) {
59        return Some(from_offset_dt(dt));
60    }
61    if let Ok(dt) = PrimitiveDateTime::parse(trimmed, &Iso8601::DEFAULT) {
62        return Some(from_primitive_dt(dt));
63    }
64    if let Ok(d) = Date::parse(trimmed, &Iso8601::DEFAULT) {
65        return Some(from_date(d));
66    }
67    None
68}
69
70/// Current system time as a krilla `DateTime`. Falls back to UTC if
71/// the local timezone offset can't be determined (e.g. in containerised
72/// environments without `/etc/localtime`).
73pub fn now() -> DateTime {
74    match OffsetDateTime::now_local() {
75        Ok(dt) => from_offset_dt(dt),
76        Err(_) => from_offset_dt(OffsetDateTime::now_utc()),
77    }
78}
79
80/// Today as `YYYY-MM-DD` (UTC fallback). Used by the renderer to
81/// drive the `{date}` header/footer template variable when the caller
82/// hasn't supplied an explicit date string.
83pub fn today_yyyy_mm_dd() -> String {
84    let dt = OffsetDateTime::now_local().unwrap_or_else(|_| OffsetDateTime::now_utc());
85    format!("{:04}-{:02}-{:02}", dt.year(), dt.month() as u8, dt.day())
86}
87
88/// Re-format a `YYYY-MM-DD…` ISO string into a clean `YYYY-MM-DD`
89/// (drops any time/offset component). Returns the input unchanged
90/// when parsing fails, so the templater always has *something* to
91/// substitute.
92pub fn iso_to_date_only(s: &str) -> String {
93    let trimmed = s.trim();
94    if let Ok(dt) = OffsetDateTime::parse(trimmed, &Iso8601::DEFAULT) {
95        return format!("{:04}-{:02}-{:02}", dt.year(), dt.month() as u8, dt.day());
96    }
97    if let Ok(dt) = PrimitiveDateTime::parse(trimmed, &Iso8601::DEFAULT) {
98        return format!("{:04}-{:02}-{:02}", dt.year(), dt.month() as u8, dt.day());
99    }
100    if let Ok(d) = Date::parse(trimmed, &Iso8601::DEFAULT) {
101        return format!("{:04}-{:02}-{:02}", d.year(), d.month() as u8, d.day());
102    }
103    trimmed.to_string()
104}
105
106/// Parse the four-digit year out of an ISO date string (`2024-07-30…`).
107/// Returns `None` when the leading token isn't a plausible year.
108pub fn year_of(s: &str) -> Option<i32> {
109    let digits: String = s
110        .trim()
111        .chars()
112        .take_while(|c| c.is_ascii_digit())
113        .collect();
114    let year: i32 = digits.parse().ok()?;
115    (1000..=9999).contains(&year).then_some(year)
116}
117
118/// The current calendar year (local time, UTC fallback).
119pub fn current_year() -> i32 {
120    let dt = OffsetDateTime::now_local().unwrap_or_else(|_| OffsetDateTime::now_utc());
121    dt.year()
122}
123
124/// Format a copyright year span. A single year when the first-release
125/// year is absent or equals `current`, otherwise `first–current` joined
126/// with an en dash. Examples: `"2026"`, `"2024–2026"`.
127///
128/// Pre-computing this in the caller keeps the renderer free of date
129/// conditionals — the result is dropped into a template variable.
130pub fn copyright_year_span(first: Option<i32>, current: i32) -> String {
131    match first {
132        Some(first) if first < current => format!("{first}\u{2013}{current}"),
133        _ => current.to_string(),
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140
141    #[test]
142    fn parses_date_only() {
143        assert!(parse_iso("2025-11-04").is_some());
144    }
145
146    #[test]
147    fn parses_datetime_with_offset() {
148        assert!(parse_iso("2025-11-04T08:30:00+01:00").is_some());
149    }
150
151    #[test]
152    fn parses_datetime_zulu() {
153        assert!(parse_iso("2025-11-04T08:30:00Z").is_some());
154    }
155
156    #[test]
157    fn returns_none_for_empty() {
158        assert!(parse_iso("").is_none());
159        assert!(parse_iso("   ").is_none());
160    }
161
162    #[test]
163    fn year_of_extracts_leading_year() {
164        assert_eq!(year_of("2024-07-30"), Some(2024));
165        assert_eq!(year_of("  2026 "), Some(2026));
166        assert_eq!(year_of("2025-01-01T08:30:00Z"), Some(2025));
167        assert_eq!(year_of("not-a-date"), None);
168        assert_eq!(year_of("99"), None); // too few digits to be a year
169        assert_eq!(year_of(""), None);
170    }
171
172    #[test]
173    fn copyright_span_collapses_equal_years() {
174        // first == current → single year.
175        assert_eq!(copyright_year_span(Some(2026), 2026), "2026");
176        // missing first → single (current) year.
177        assert_eq!(copyright_year_span(None, 2026), "2026");
178        // first before current → en-dashed range.
179        assert_eq!(copyright_year_span(Some(2024), 2026), "2024\u{2013}2026");
180        // first after current (clock skew / bad data) → just current.
181        assert_eq!(copyright_year_span(Some(2030), 2026), "2026");
182    }
183
184    #[test]
185    fn returns_none_for_garbage() {
186        assert!(parse_iso("not a date").is_none());
187        assert!(parse_iso("2025-13-99").is_none());
188    }
189
190    #[test]
191    fn now_succeeds() {
192        let _ = now();
193    }
194}