caldir-core 0.16.0

Core library for caldir calendar storage, sync, and provider protocol
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
use crate::event::EventTime;
use icalendar::{Component, DatePerhapsTime, Property};

#[derive(Debug, Clone, Eq)]
pub struct Recurrence {
    /// RRULE value (after "RRULE:"), e.g. "FREQ=WEEKLY;BYDAY=MO".
    ///
    /// Stored as a string rather than a typed `rrule::RRule` for two reasons:
    /// 1. Robustness — providers (especially CalDAV servers) emit RRULEs that
    ///    the rrule crate can't always parse. Typing the field would turn every
    ///    such case into a load error and break sync for that event.
    /// 2. Round-tripping — `rrule::RRule`'s Display re-serializes from typed
    ///    fields and drops redundant defaults (e.g. INTERVAL=1), causing
    ///    spurious "modified" diffs on subsequent syncs.
    ///
    /// Parse with `rrule::RRule::from_str` at the call site when typed access
    /// is needed (e.g. expanding occurrences).
    pub rrule: String,
    pub exdates: Vec<EventTime>,
    /// RDATE values — explicit dates added to the recurrence set.
    /// Sometimes emited by CalDAV servers like iCloud
    ///
    /// Note: RFC 5545 also allows PERIOD values (`DTSTART/DURATION` pairs)
    /// in RDATE, but those are not modeled here — only date and date-time
    /// values are parsed. PERIOD-valued RDATEs will be silently dropped.
    pub rdates: Vec<EventTime>,
}

// EXDATE/RDATE are sets per RFC 5545, so equality must ignore order.
// Otherwise a provider re-emitting the same dates in a different order
// produces a spurious "modified" diff and a no-op push/pull.
impl PartialEq for Recurrence {
    fn eq(&self, other: &Self) -> bool {
        self.rrule == other.rrule
            && sorted_by_utc(&self.exdates) == sorted_by_utc(&other.exdates)
            && sorted_by_utc(&self.rdates) == sorted_by_utc(&other.rdates)
    }
}

fn sorted_by_utc(times: &[EventTime]) -> Vec<EventTime> {
    let mut v = times.to_vec();
    v.sort_by_key(|t| t.to_utc());
    v
}

impl Recurrence {
    pub fn new(rrule: impl Into<String>) -> Self {
        Recurrence {
            rrule: rrule.into(),
            exdates: Vec::new(),
            rdates: Vec::new(),
        }
    }

    pub(crate) fn from_ical_event(event: &icalendar::Event) -> Option<Self> {
        let rrule = event.property_value("RRULE")?;

        let exdates = parse_event_time_list(event, "EXDATE");
        let rdates = parse_event_time_list(event, "RDATE");

        Some(Recurrence {
            rrule: rrule.to_string(),
            exdates,
            rdates,
        })
    }

    /// Return a copy truncated to end strictly before `before`.
    ///
    /// The returned recurrence:
    /// - Has any existing `UNTIL=` and `COUNT=` fragments stripped from its RRULE
    ///   and replaced with a fresh `UNTIL=<just before `before`>`.
    /// - Has any EXDATEs at or after `before` removed (they are no longer
    ///   meaningful once the series ends earlier).
    ///
    /// `dtstart` is the master event's start time; it determines the format of
    /// the emitted UNTIL value (per RFC 5545 / the rrule crate's matching rule).
    ///
    /// Used to implement "split a recurring series at this instance" — a primitive
    /// that any caldir client can use to translate a "this and future" edit into
    /// two separate events on disk.
    pub fn truncate_before(&self, dtstart: &EventTime, before: &EventTime) -> Recurrence {
        let until_value = format_until_value(dtstart, before);
        let truncated_rrule = with_until(&self.rrule, &until_value);

        let before_utc = before.to_utc();
        let kept_exdates: Vec<EventTime> = self
            .exdates
            .iter()
            .filter(|ex| ex.to_utc() < before_utc)
            .cloned()
            .collect();

        Recurrence {
            rrule: truncated_rrule,
            exdates: kept_exdates,
            rdates: self.rdates.clone(),
        }
    }

    pub(crate) fn apply_to(&self, event: &mut icalendar::Event) {
        event.append_property(Property::new("RRULE", &self.rrule));
        for exdate in &self.exdates {
            event.append_multi_property(DatePerhapsTime::from(exdate).to_property("EXDATE"));
        }
        for rdate in &self.rdates {
            event.append_multi_property(DatePerhapsTime::from(rdate).to_property("RDATE"));
        }
    }
}

/// Format an RRULE UNTIL value for a series with `dtstart`, set "just before"
/// `before`. Format matches the rrule crate's expectations for the dtstart
/// variant (see RFC 5545).
fn format_until_value(dtstart: &EventTime, before: &EventTime) -> String {
    use chrono::Duration;

    match dtstart {
        EventTime::Date(_) => {
            let before_date = match before {
                EventTime::Date(d) => *d,
                _ => before.to_utc().date_naive(),
            };
            (before_date - Duration::days(1))
                .format("%Y%m%d")
                .to_string()
        }
        EventTime::DateTimeUtc(_) | EventTime::DateTimeZoned { .. } => {
            let before_utc = before.to_utc();
            (before_utc - Duration::seconds(1))
                .format("%Y%m%dT%H%M%SZ")
                .to_string()
        }
        EventTime::DateTimeFloating(_) => {
            let before_naive = before.to_utc().naive_utc();
            (before_naive - Duration::seconds(1))
                .format("%Y%m%dT%H%M%S")
                .to_string()
        }
    }
}

/// Return a copy of `rrule` with any existing `UNTIL=` and `COUNT=` fragments
/// removed and a new `UNTIL=<until_value>` appended. Order of other fragments
/// is preserved.
fn with_until(rrule: &str, until_value: &str) -> String {
    let mut parts: Vec<String> = rrule
        .split(';')
        .filter(|p| !p.is_empty())
        .filter(|p| !p.starts_with("UNTIL=") && !p.starts_with("COUNT="))
        .map(|p| p.to_string())
        .collect();
    parts.push(format!("UNTIL={}", until_value));
    parts.join(";")
}

fn parse_event_time_list(event: &icalendar::Event, name: &str) -> Vec<EventTime> {
    event
        .multi_properties()
        .get(name)
        .map(|props| {
            props
                .iter()
                .flat_map(split_property_values)
                .filter_map(|p| DatePerhapsTime::from_property(&p))
                .map(EventTime::from)
                .collect()
        })
        .unwrap_or_default()
}

// RFC 5545 allows EXDATE/RDATE to carry multiple comma-separated values on a
// single line. `DatePerhapsTime::from_property` parses the whole value as one
// date(-time), so it returns None for comma-packed properties and every entry
// is silently dropped. Split the value here and rebuild a property per entry,
// preserving parameters (TZID, VALUE) so downstream parsing still sees them.
fn split_property_values(prop: &Property) -> Vec<Property> {
    let key = prop.key();
    prop.value()
        .split(',')
        .map(str::trim)
        .filter(|v| !v.is_empty())
        .map(|v| {
            let mut split = Property::new(key, v);
            for (param_key, param) in prop.params() {
                split.add_parameter(param_key, param.value());
            }
            split
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils::test_icalendar_event;
    use chrono::{NaiveDate, TimeZone};
    use pretty_assertions::assert_eq;

    #[test]
    fn from_ical_event_returns_none_when_no_rrule() {
        let event = test_icalendar_event().done();

        let recurrence = Recurrence::from_ical_event(&event);

        assert_eq!(recurrence, None);
    }

    #[test]
    fn from_ical_event_parses_rrule_value() {
        let event = test_icalendar_event()
            .append_property(Property::new("RRULE", "FREQ=WEEKLY;BYDAY=MO"))
            .done();

        let recurrence = Recurrence::from_ical_event(&event).unwrap();

        assert_eq!(recurrence.rrule, "FREQ=WEEKLY;BYDAY=MO");
        assert!(recurrence.exdates.is_empty());
        assert!(recurrence.rdates.is_empty());
    }

    #[test]
    fn from_ical_event_parses_multiple_exdates() {
        let event = test_icalendar_event()
            .append_property(Property::new("RRULE", "FREQ=DAILY"))
            .append_multi_property(Property::new("EXDATE", "20260105").done())
            .append_multi_property(Property::new("EXDATE", "20260108").done())
            .done();

        let recurrence = Recurrence::from_ical_event(&event).unwrap();

        assert_eq!(
            recurrence.exdates,
            vec![
                EventTime::Date(NaiveDate::from_ymd_opt(2026, 1, 5).unwrap()),
                EventTime::Date(NaiveDate::from_ymd_opt(2026, 1, 8).unwrap()),
            ]
        );
    }

    #[test]
    fn from_ical_event_parses_comma_separated_exdates() {
        let event = test_icalendar_event()
            .append_property(Property::new("RRULE", "FREQ=DAILY"))
            .append_multi_property(Property::new("EXDATE", "20260105,20260108").done())
            .done();

        let recurrence = Recurrence::from_ical_event(&event).unwrap();

        assert_eq!(
            recurrence.exdates,
            vec![
                EventTime::Date(NaiveDate::from_ymd_opt(2026, 1, 5).unwrap()),
                EventTime::Date(NaiveDate::from_ymd_opt(2026, 1, 8).unwrap()),
            ]
        );
    }

    #[test]
    fn from_ical_event_parses_zoned_exdate() {
        let mut exdate = Property::new("EXDATE", "20260105T100000");
        exdate.add_parameter("TZID", "Europe/Stockholm");

        let event = test_icalendar_event()
            .append_property(Property::new("RRULE", "FREQ=WEEKLY"))
            .append_multi_property(exdate.done())
            .done();

        let recurrence = Recurrence::from_ical_event(&event).unwrap();

        assert_eq!(
            recurrence.exdates,
            vec![EventTime::DateTimeZoned {
                datetime: NaiveDate::from_ymd_opt(2026, 1, 5)
                    .unwrap()
                    .and_hms_opt(10, 0, 0)
                    .unwrap(),
                tzid: "Europe/Stockholm".to_string(),
            }]
        );
    }

    #[test]
    fn from_ical_event_normalizes_windows_exdate_timezone_to_iana() {
        let mut exdate = Property::new("EXDATE", "20260105T100000");
        exdate.add_parameter("TZID", "Pacific Standard Time");

        let event = test_icalendar_event()
            .append_property(Property::new("RRULE", "FREQ=WEEKLY"))
            .append_multi_property(exdate.done())
            .done();

        let recurrence = Recurrence::from_ical_event(&event).unwrap();

        assert_eq!(
            recurrence.exdates,
            vec![EventTime::DateTimeZoned {
                datetime: NaiveDate::from_ymd_opt(2026, 1, 5)
                    .unwrap()
                    .and_hms_opt(10, 0, 0)
                    .unwrap(),
                tzid: "America/Los_Angeles".to_string(),
            }]
        );
    }

    #[test]
    fn from_ical_event_parses_multiple_rdates() {
        let event = test_icalendar_event()
            .append_property(Property::new("RRULE", "FREQ=DAILY"))
            .append_multi_property(Property::new("RDATE", "20260201").done())
            .append_multi_property(Property::new("RDATE", "20260215").done())
            .done();

        let recurrence = Recurrence::from_ical_event(&event).unwrap();

        assert_eq!(
            recurrence.rdates,
            vec![
                EventTime::Date(NaiveDate::from_ymd_opt(2026, 2, 1).unwrap()),
                EventTime::Date(NaiveDate::from_ymd_opt(2026, 2, 15).unwrap()),
            ]
        );
    }

    #[test]
    fn from_ical_event_parses_zoned_rdate() {
        let mut rdate = Property::new("RDATE", "20260201T100000");
        rdate.add_parameter("TZID", "Europe/Stockholm");

        let event = test_icalendar_event()
            .append_property(Property::new("RRULE", "FREQ=WEEKLY"))
            .append_multi_property(rdate.done())
            .done();

        let recurrence = Recurrence::from_ical_event(&event).unwrap();

        assert_eq!(
            recurrence.rdates,
            vec![EventTime::DateTimeZoned {
                datetime: NaiveDate::from_ymd_opt(2026, 2, 1)
                    .unwrap()
                    .and_hms_opt(10, 0, 0)
                    .unwrap(),
                tzid: "Europe/Stockholm".to_string(),
            }]
        );
    }

    #[test]
    fn from_ical_event_normalizes_windows_rdate_timezone_to_iana() {
        let mut rdate = Property::new("RDATE", "20260201T100000");
        rdate.add_parameter("TZID", "Pacific Standard Time");

        let event = test_icalendar_event()
            .append_property(Property::new("RRULE", "FREQ=WEEKLY"))
            .append_multi_property(rdate.done())
            .done();

        let recurrence = Recurrence::from_ical_event(&event).unwrap();

        assert_eq!(
            recurrence.rdates,
            vec![EventTime::DateTimeZoned {
                datetime: NaiveDate::from_ymd_opt(2026, 2, 1)
                    .unwrap()
                    .and_hms_opt(10, 0, 0)
                    .unwrap(),
                tzid: "America/Los_Angeles".to_string(),
            }]
        );
    }

    #[test]
    fn from_ical_event_parses_exdates_and_rdates_together() {
        let event = test_icalendar_event()
            .append_property(Property::new("RRULE", "FREQ=WEEKLY"))
            .append_multi_property(Property::new("EXDATE", "20260105").done())
            .append_multi_property(Property::new("RDATE", "20260201").done())
            .done();

        let recurrence = Recurrence::from_ical_event(&event).unwrap();

        assert_eq!(
            recurrence.exdates,
            vec![EventTime::Date(
                NaiveDate::from_ymd_opt(2026, 1, 5).unwrap()
            )]
        );
        assert_eq!(
            recurrence.rdates,
            vec![EventTime::Date(
                NaiveDate::from_ymd_opt(2026, 2, 1).unwrap()
            )]
        );
    }

    #[test]
    fn apply_to_writes_rrule_exdates_and_rdates() {
        let recurrence = Recurrence {
            rrule: "FREQ=WEEKLY;BYDAY=MO".to_string(),
            exdates: vec![
                EventTime::Date(NaiveDate::from_ymd_opt(2026, 1, 5).unwrap()),
                EventTime::Date(NaiveDate::from_ymd_opt(2026, 1, 12).unwrap()),
            ],
            rdates: vec![
                EventTime::Date(NaiveDate::from_ymd_opt(2026, 2, 1).unwrap()),
                EventTime::Date(NaiveDate::from_ymd_opt(2026, 2, 15).unwrap()),
            ],
        };

        let mut event = icalendar::Event::new();
        recurrence.apply_to(&mut event);

        assert_eq!(event.property_value("RRULE"), Some("FREQ=WEEKLY;BYDAY=MO"));
        let exdates = event.multi_properties().get("EXDATE").unwrap();
        assert_eq!(exdates.len(), 2);
        assert_eq!(exdates[0].value(), "20260105");
        assert_eq!(exdates[1].value(), "20260112");
        let rdates = event.multi_properties().get("RDATE").unwrap();
        assert_eq!(rdates.len(), 2);
        assert_eq!(rdates[0].value(), "20260201");
        assert_eq!(rdates[1].value(), "20260215");
    }

    #[test]
    fn equality_ignores_exdate_and_rdate_order() {
        let d1 = EventTime::Date(NaiveDate::from_ymd_opt(2026, 1, 5).unwrap());
        let d2 = EventTime::Date(NaiveDate::from_ymd_opt(2026, 1, 12).unwrap());
        let d3 = EventTime::Date(NaiveDate::from_ymd_opt(2026, 2, 1).unwrap());
        let d4 = EventTime::Date(NaiveDate::from_ymd_opt(2026, 2, 15).unwrap());

        let a = Recurrence {
            rrule: "FREQ=WEEKLY".to_string(),
            exdates: vec![d1.clone(), d2.clone()],
            rdates: vec![d3.clone(), d4.clone()],
        };
        let b = Recurrence {
            rrule: "FREQ=WEEKLY".to_string(),
            exdates: vec![d2, d1],
            rdates: vec![d4, d3],
        };

        assert_eq!(a, b);
    }

    #[test]
    fn equality_detects_different_exdates() {
        let a = Recurrence {
            rrule: "FREQ=WEEKLY".to_string(),
            exdates: vec![EventTime::Date(
                NaiveDate::from_ymd_opt(2026, 1, 5).unwrap(),
            )],
            rdates: vec![],
        };
        let b = Recurrence {
            rrule: "FREQ=WEEKLY".to_string(),
            exdates: vec![EventTime::Date(
                NaiveDate::from_ymd_opt(2026, 1, 6).unwrap(),
            )],
            rdates: vec![],
        };

        assert_ne!(a, b);
    }

    #[test]
    fn truncate_before_adds_until_for_utc_dtstart() {
        let rec = Recurrence::new("FREQ=DAILY");
        let dtstart =
            EventTime::DateTimeUtc(chrono::Utc.with_ymd_and_hms(2026, 4, 1, 10, 0, 0).unwrap());
        let before =
            EventTime::DateTimeUtc(chrono::Utc.with_ymd_and_hms(2026, 4, 5, 10, 0, 0).unwrap());

        let truncated = rec.truncate_before(&dtstart, &before);

        assert_eq!(truncated.rrule, "FREQ=DAILY;UNTIL=20260405T095959Z");
    }

    #[test]
    fn truncate_before_adds_until_for_date_dtstart() {
        let rec = Recurrence::new("FREQ=DAILY");
        let dtstart = EventTime::Date(NaiveDate::from_ymd_opt(2026, 4, 1).unwrap());
        let before = EventTime::Date(NaiveDate::from_ymd_opt(2026, 4, 5).unwrap());

        let truncated = rec.truncate_before(&dtstart, &before);

        assert_eq!(truncated.rrule, "FREQ=DAILY;UNTIL=20260404");
    }

    #[test]
    fn truncate_before_replaces_existing_until() {
        let rec = Recurrence::new("FREQ=DAILY;UNTIL=20271231T235959Z");
        let dtstart =
            EventTime::DateTimeUtc(chrono::Utc.with_ymd_and_hms(2026, 4, 1, 10, 0, 0).unwrap());
        let before =
            EventTime::DateTimeUtc(chrono::Utc.with_ymd_and_hms(2026, 4, 5, 10, 0, 0).unwrap());

        let truncated = rec.truncate_before(&dtstart, &before);

        assert_eq!(truncated.rrule, "FREQ=DAILY;UNTIL=20260405T095959Z");
    }

    #[test]
    fn truncate_before_replaces_existing_count() {
        let rec = Recurrence::new("FREQ=DAILY;COUNT=100");
        let dtstart =
            EventTime::DateTimeUtc(chrono::Utc.with_ymd_and_hms(2026, 4, 1, 10, 0, 0).unwrap());
        let before =
            EventTime::DateTimeUtc(chrono::Utc.with_ymd_and_hms(2026, 4, 5, 10, 0, 0).unwrap());

        let truncated = rec.truncate_before(&dtstart, &before);

        assert_eq!(truncated.rrule, "FREQ=DAILY;UNTIL=20260405T095959Z");
        assert!(!truncated.rrule.contains("COUNT="));
    }

    #[test]
    fn truncate_before_drops_exdates_at_or_after_before() {
        let kept =
            EventTime::DateTimeUtc(chrono::Utc.with_ymd_and_hms(2026, 4, 3, 10, 0, 0).unwrap());
        let dropped_at =
            EventTime::DateTimeUtc(chrono::Utc.with_ymd_and_hms(2026, 4, 5, 10, 0, 0).unwrap());
        let dropped_after =
            EventTime::DateTimeUtc(chrono::Utc.with_ymd_and_hms(2026, 4, 6, 10, 0, 0).unwrap());

        let rec = Recurrence {
            rrule: "FREQ=DAILY".to_string(),
            exdates: vec![kept.clone(), dropped_at, dropped_after],
            rdates: vec![],
        };

        let truncated = rec.truncate_before(
            &EventTime::DateTimeUtc(chrono::Utc.with_ymd_and_hms(2026, 4, 1, 10, 0, 0).unwrap()),
            &EventTime::DateTimeUtc(chrono::Utc.with_ymd_and_hms(2026, 4, 5, 10, 0, 0).unwrap()),
        );

        assert_eq!(truncated.exdates, vec![kept]);
    }

    #[test]
    fn truncate_before_keeps_rdates() {
        // RDATEs aren't pruned by truncation — they're explicit additions.
        let rdate =
            EventTime::DateTimeUtc(chrono::Utc.with_ymd_and_hms(2026, 4, 10, 10, 0, 0).unwrap());
        let rec = Recurrence {
            rrule: "FREQ=DAILY".to_string(),
            exdates: vec![],
            rdates: vec![rdate.clone()],
        };

        let truncated = rec.truncate_before(
            &EventTime::DateTimeUtc(chrono::Utc.with_ymd_and_hms(2026, 4, 1, 10, 0, 0).unwrap()),
            &EventTime::DateTimeUtc(chrono::Utc.with_ymd_and_hms(2026, 4, 5, 10, 0, 0).unwrap()),
        );

        assert_eq!(truncated.rdates, vec![rdate]);
    }

    #[test]
    fn apply_to_omits_exdate_and_rdate_when_empty() {
        let recurrence = Recurrence::new("FREQ=DAILY");

        let mut event = icalendar::Event::new();
        recurrence.apply_to(&mut event);

        assert!(event.multi_properties().get("EXDATE").is_none());
        assert!(event.multi_properties().get("RDATE").is_none());
    }
}