1use std::sync::OnceLock;
7
8use chrono::{Datelike, Local, NaiveDate, NaiveDateTime, NaiveTime, Timelike};
9use regex::Regex;
10
11fn patterns() -> &'static [Regex] {
12 static PATTERNS: OnceLock<Vec<Regex>> = OnceLock::new();
13 PATTERNS.get_or_init(|| {
14 [
17 r"\[(\d{4}-\d{1,2}-\d{1,2} \d{2}:\d{2})\]\s*$",
18 r"\[(\d{4}-\d{1,2}-\d{1,2})\]\s*$",
19 r"\[(\d{1,2}-\d{1,2} \d{2}:\d{2})\]\s*$",
20 r"\[(\d{1,2}-\d{1,2})\]\s*$",
21 r"\[(\d{2}:\d{2})\]\s*$",
22 ]
23 .iter()
24 .map(|p| Regex::new(p).expect("valid due-date pattern"))
25 .collect()
26 })
27}
28
29pub fn parse(description: &str) -> (String, String) {
31 for re in patterns() {
32 if let Some(m) = re.find(description) {
33 let due = re
34 .captures(description)
35 .and_then(|c| c.get(1))
36 .map(|g| g.as_str().to_string())
37 .unwrap_or_default();
38 let mut rest = String::with_capacity(description.len());
39 rest.push_str(&description[..m.start()]);
40 rest.push_str(&description[m.end()..]);
41 return (due, rest.trim().to_string());
42 }
43 }
44 (String::new(), description.trim().to_string())
45}
46
47pub fn is_valid(text: &str) -> bool {
50 normalize_for_write(text).is_ok()
51}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct InvalidDue {
55 value: String,
56}
57
58impl std::fmt::Display for InvalidDue {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 write!(
61 f,
62 "invalid due {:?}; use YYYY-MM-DD, MM-DD, or HH:MM, optionally with a time",
63 self.value
64 )
65 }
66}
67
68impl std::error::Error for InvalidDue {}
69
70pub fn normalize_for_write(text: &str) -> Result<String, InvalidDue> {
77 normalize_for_write_at(text, Local::now().naive_local())
78}
79
80pub fn normalize_for_write_at(text: &str, now: NaiveDateTime) -> Result<String, InvalidDue> {
81 normalize_at(text, now, true)
82}
83
84pub fn normalize_legacy_at(text: &str, now: NaiveDateTime) -> Result<String, InvalidDue> {
88 normalize_at(text, now, false)
89}
90
91fn normalize_at(
92 text: &str,
93 now: NaiveDateTime,
94 roll_shorthand_forward: bool,
95) -> Result<String, InvalidDue> {
96 let original = text.trim();
97 if original.is_empty() {
98 return Ok(String::new());
99 }
100 let input = original.replace('T', " ");
101 let (matched, rest) = parse(&format!("[{input}]"));
102 if matched != input || !rest.is_empty() {
103 return Err(InvalidDue {
104 value: original.to_string(),
105 });
106 }
107
108 let (date_part, time_part) = match input.split_once(' ') {
109 Some((date, time)) if !date.is_empty() && !time.is_empty() => (date, Some(time)),
110 None if input.contains(':') => ("", Some(input.as_str())),
111 None => (input.as_str(), None),
112 _ => {
113 return Err(InvalidDue {
114 value: original.to_string(),
115 });
116 }
117 };
118 let time = match time_part {
119 Some(value) => Some(parse_time(value).ok_or_else(|| InvalidDue {
120 value: original.to_string(),
121 })?),
122 None => None,
123 };
124
125 let pieces: Vec<&str> = date_part.split('-').collect();
126 let date = match pieces.as_slice() {
127 [year, month, day] => {
128 let year = year.parse::<i32>().ok();
129 let month = month.parse::<u32>().ok();
130 let day = day.parse::<u32>().ok();
131 match (year, month, day) {
132 (Some(year), Some(month), Some(day)) => NaiveDate::from_ymd_opt(year, month, day),
133 _ => None,
134 }
135 .ok_or_else(|| InvalidDue {
136 value: original.to_string(),
137 })?
138 }
139 [month, day] => {
140 let month = month.parse::<u32>().ok();
141 let day = day.parse::<u32>().ok();
142 let (Some(month), Some(day)) = (month, day) else {
143 return Err(InvalidDue {
144 value: original.to_string(),
145 });
146 };
147 if roll_shorthand_forward {
148 next_month_day(month, day, time, now)
149 } else {
150 month_day_in_migration_year(month, day, now)
151 }
152 .ok_or_else(|| InvalidDue {
153 value: original.to_string(),
154 })?
155 }
156 [""] => {
157 let Some(clock) = time else {
158 return Err(InvalidDue {
159 value: original.to_string(),
160 });
161 };
162 let today = now.date();
163 let candidate = today.and_time(clock);
164 if !roll_shorthand_forward || candidate >= now {
165 today
166 } else {
167 today.succ_opt().ok_or_else(|| InvalidDue {
168 value: original.to_string(),
169 })?
170 }
171 }
172 _ => {
173 return Err(InvalidDue {
174 value: original.to_string(),
175 });
176 }
177 };
178
179 Ok(match time {
180 Some(time) => format!("{} {}", date.format("%Y-%m-%d"), time.format("%H:%M")),
181 None => date.format("%Y-%m-%d").to_string(),
182 })
183}
184
185fn month_day_in_migration_year(month: u32, day: u32, now: NaiveDateTime) -> Option<NaiveDate> {
186 NaiveDate::from_ymd_opt(now.year(), month, day)
187}
188
189fn parse_time(value: &str) -> Option<NaiveTime> {
190 if value.len() != 5 || value.as_bytes().get(2) != Some(&b':') {
191 return None;
192 }
193 let hour = value.get(..2)?.parse().ok()?;
194 let minute = value.get(3..)?.parse().ok()?;
195 NaiveTime::from_hms_opt(hour, minute, 0)
196}
197
198fn next_month_day(
199 month: u32,
200 day: u32,
201 time: Option<NaiveTime>,
202 now: NaiveDateTime,
203) -> Option<NaiveDate> {
204 for offset in 0..=8 {
207 let year = now.year().checked_add(offset)?;
208 let Some(candidate) = NaiveDate::from_ymd_opt(year, month, day) else {
209 continue;
210 };
211 let is_future = match time {
212 Some(clock) => candidate.and_time(clock) >= now,
213 None => candidate >= now.date(),
214 };
215 if is_future {
216 return Some(candidate);
217 }
218 }
219 None
220}
221
222pub fn is_today(due: &str) -> bool {
223 relative_day(due) == Some(0)
224}
225
226fn relative_day(due: &str) -> Option<i64> {
228 if due.is_empty() {
229 return None;
230 }
231 if due.len() == 5 && due.contains(':') {
233 return Some(0);
234 }
235 let (y, mo, d, _, _) = sort_key(due)?;
236 relative_date(y, mo, d)
237}
238
239fn relative_date(year: i32, month: u32, day: u32) -> Option<i64> {
240 let date = NaiveDate::from_ymd_opt(year, month, day)?;
241 Some((date - Local::now().date_naive()).num_days())
242}
243
244pub fn display(due: &str, date_format: &str) -> String {
248 if due.is_empty() {
249 return String::new();
250 }
251 let Some((y, mo, d, h, mi)) = sort_key(due) else {
252 return format!("[{due}]");
253 };
254 let relative = if due.len() == 5 && due.contains(':') {
255 Some(0)
256 } else {
257 relative_date(y, mo, d)
258 };
259 let label = match relative {
260 Some(0) => "Today".to_string(),
261 Some(1) => "Tomorrow".to_string(),
262 Some(-1) => "Yesterday".to_string(),
263 _ => format_date(y, mo, d, date_format),
264 };
265 let text = if due.contains(':') {
266 format!("{label} {h:02}:{mi:02}")
267 } else {
268 label
269 };
270 format!("[{text}]")
271}
272
273fn format_date(year: i32, month: u32, day: u32, date_format: &str) -> String {
274 match date_format {
275 "D-M-Y" => format!("{day:02}-{month:02}-{year}"),
276 "M-D-Y" => format!("{month:02}-{day:02}-{year}"),
277 _ => format!("{year}-{month:02}-{day:02}"),
278 }
279}
280
281pub fn sort_key(due: &str) -> Option<(i32, u32, u32, u32, u32)> {
286 if due.is_empty() {
287 return None;
288 }
289 let today = Local::now().date_naive();
290 let (date_part, time_part) = match due.split_once(' ') {
291 Some((date, time)) => (date, Some(time)),
292 None if due.contains(':') => ("", Some(due)),
293 None => (due, None),
294 };
295
296 let date = match date_part.split('-').collect::<Vec<_>>().as_slice() {
297 [y, m, d] => NaiveDate::from_ymd_opt(y.parse().ok()?, m.parse().ok()?, d.parse().ok()?)?,
298 [m, d] => NaiveDate::from_ymd_opt(today.year(), m.parse().ok()?, d.parse().ok()?)?,
299 [""] if time_part.is_some() => today,
300 _ => return None,
301 };
302 let time = match time_part {
303 Some(value) => parse_time(value)?,
304 None => NaiveTime::from_hms_opt(0, 0, 0)?,
305 };
306 Some((
307 date.year(),
308 date.month(),
309 date.day(),
310 time.hour(),
311 time.minute(),
312 ))
313}
314
315pub fn now_string(date_format: &str) -> String {
317 let now = Local::now();
318 let date = match date_format {
319 "D-M-Y" => now.format("%d-%m-%Y"),
320 "M-D-Y" => now.format("%m-%d-%Y"),
321 _ => now.format("%Y-%m-%d"),
322 };
323 format!("{} {}", date, now.format("%H:%M"))
324}
325
326#[cfg(test)]
327mod tests {
328 use super::*;
329 use chrono::Local;
330
331 #[test]
332 fn parses_every_supported_shape() {
333 let cases = [
334 (
335 "buy milk [2026-08-06 09:00]",
336 "2026-08-06 09:00",
337 "buy milk",
338 ),
339 ("buy milk [2026-8-6]", "2026-8-6", "buy milk"),
340 ("buy milk [08-06 09:00]", "08-06 09:00", "buy milk"),
341 ("buy milk [8-6]", "8-6", "buy milk"),
342 ("buy milk [09:00]", "09:00", "buy milk"),
343 ];
344 for (input, due, rest) in cases {
345 assert_eq!(parse(input), (due.to_string(), rest.to_string()), "{input}");
346 }
347 }
348
349 #[test]
350 fn leaves_plain_descriptions_alone() {
351 assert_eq!(
352 parse("read [the] book"),
353 (String::new(), "read [the] book".to_string())
354 );
355 assert_eq!(
356 parse("plan [2030-01-02] launch"),
357 (String::new(), "plan [2030-01-02] launch".to_string()),
358 "only a trailing date token is due syntax"
359 );
360 }
361
362 #[test]
363 fn sorts_across_the_different_shapes() {
364 let year = Local::now().year();
365 assert_eq!(sort_key(""), None);
366 assert_eq!(sort_key("2030-01-02 09:30"), Some((2030, 1, 2, 9, 30)));
367 assert_eq!(sort_key("2030-01-02"), Some((2030, 1, 2, 0, 0)));
368 assert_eq!(sort_key("12-25"), Some((year, 12, 25, 0, 0)));
369 assert!(
370 sort_key("12-25") > sort_key("01-02"),
371 "December comes after January of the same year"
372 );
373 assert!(
374 sort_key(&format!("{}-01-01", year + 1)) > sort_key("12-25"),
375 "next year comes after this December"
376 );
377 }
378
379 #[test]
380 fn invalid_due_values_do_not_masquerade_as_today() {
381 for value in ["garbage", "2030-99-99", "25:99"] {
382 assert_eq!(sort_key(value), None, "{value}");
383 assert_eq!(display(value, "Y-M-D"), format!("[{value}]"));
384 }
385 }
386
387 #[test]
388 fn validates_bare_dates() {
389 assert!(is_valid(""));
390 assert!(is_valid("09:00"));
391 assert!(is_valid("2030-01-02"));
392 assert!(is_valid("01-02 09:00"));
393 assert!(is_valid("8-6"));
395 assert!(is_valid("8-6 14:30"));
396 assert!(is_valid("2026-8-6 14:30"));
397 assert!(!is_valid("next tuesday"));
398 assert!(!is_valid("2030/01/02"));
399 assert!(!is_valid("09:00 and more"));
400 }
401
402 #[test]
403 fn rejects_digits_that_are_not_a_real_date_or_time() {
404 assert!(!is_valid("2026-99-99"), "month 99");
405 assert!(!is_valid("2026-00-00"), "month and day zero");
406 assert!(!is_valid("2026-02-30"), "February has no 30th");
407 assert!(!is_valid("25:99"), "hour and minute out of range");
408 assert!(!is_valid("2026-08-10 30:70"));
409 assert!(is_valid("2028-02-29"), "a real leap day still passes");
410 }
411
412 #[test]
413 fn normalizes_shorthand_to_the_next_absolute_moment() {
414 let now = chrono::NaiveDate::from_ymd_opt(2026, 8, 8)
415 .unwrap()
416 .and_hms_opt(12, 0, 0)
417 .unwrap();
418
419 assert_eq!(normalize_for_write_at("8-8", now).unwrap(), "2026-08-08");
420 assert_eq!(normalize_for_write_at("8-7", now).unwrap(), "2027-08-07");
421 assert_eq!(
422 normalize_for_write_at("8-8 13:00", now).unwrap(),
423 "2026-08-08 13:00"
424 );
425 assert_eq!(
426 normalize_for_write_at("8-8 11:00", now).unwrap(),
427 "2027-08-08 11:00"
428 );
429 assert_eq!(
430 normalize_for_write_at("13:00", now).unwrap(),
431 "2026-08-08 13:00"
432 );
433 assert_eq!(
434 normalize_for_write_at("11:00", now).unwrap(),
435 "2026-08-09 11:00"
436 );
437 }
438
439 #[test]
440 fn absolute_due_values_are_canonicalized_without_rolling_forward() {
441 let now = chrono::NaiveDate::from_ymd_opt(2026, 8, 8)
442 .unwrap()
443 .and_hms_opt(12, 0, 0)
444 .unwrap();
445
446 assert_eq!(
447 normalize_for_write_at("2020-1-2", now).unwrap(),
448 "2020-01-02"
449 );
450 assert_eq!(
451 normalize_for_write_at("2020-1-2 03:04", now).unwrap(),
452 "2020-01-02 03:04"
453 );
454 assert!(normalize_for_write_at("2026-02-30", now).is_err());
455 }
456
457 #[test]
458 fn legacy_shorthand_is_frozen_to_the_migration_day_and_year() {
459 let now = chrono::NaiveDate::from_ymd_opt(2026, 8, 8)
460 .unwrap()
461 .and_hms_opt(12, 0, 0)
462 .unwrap();
463
464 assert_eq!(normalize_legacy_at("8-7", now).unwrap(), "2026-08-07");
465 assert_eq!(
466 normalize_legacy_at("11:00", now).unwrap(),
467 "2026-08-08 11:00"
468 );
469 }
470
471 #[test]
472 fn today_is_labelled() {
473 let today = Local::now().date_naive();
474 let today_s = today.format("%Y-%m-%d").to_string();
475 assert!(is_today(&today_s));
476 assert_eq!(display(&today_s, "Y-M-D"), "[Today]");
477 assert_eq!(
478 display(&format!("{today_s} 07:30"), "Y-M-D"),
479 "[Today 07:30]"
480 );
481 assert_eq!(display("09:00", "D-M-Y"), "[Today 09:00]");
482 assert_eq!(display("2000-01-01", "Y-M-D"), "[2000-01-01]");
483 assert_eq!(display("2000-01-01", "D-M-Y"), "[01-01-2000]");
484 assert_eq!(display("2000-01-01 09:30", "M-D-Y"), "[01-01-2000 09:30]");
485 assert_eq!(display("", "Y-M-D"), "");
486
487 let tom = (today + chrono::Duration::days(1))
488 .format("%Y-%m-%d")
489 .to_string();
490 let yest = (today - chrono::Duration::days(1))
491 .format("%Y-%m-%d")
492 .to_string();
493 assert_eq!(display(&tom, "Y-M-D"), "[Tomorrow]");
494 assert_eq!(
495 display(&format!("{tom} 09:00"), "Y-M-D"),
496 "[Tomorrow 09:00]"
497 );
498 assert_eq!(display(&yest, "Y-M-D"), "[Yesterday]");
499 assert_eq!(
500 display(&format!("{yest} 18:00"), "D-M-Y"),
501 "[Yesterday 18:00]"
502 );
503 }
504}