timecore 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,995 @@
1
+ """Recurrence rules: repeating patterns such as daily or weekly.
2
+
3
+ A :class:`Recurrence` describes *how* something repeats (every day,
4
+ every Monday and Wednesday, the second Tuesday of each month) without
5
+ being anchored to a start moment. Anchor it by passing a start to
6
+ :meth:`Recurrence.occurrences`, :meth:`Recurrence.next`,
7
+ :meth:`Recurrence.previous`, or :meth:`Recurrence.between`; the
8
+ result type follows the start type (``Date`` -> ``Date``,
9
+ ``LocalDateTime`` -> ``LocalDateTime``, ``DateTime`` -> ``DateTime``).
10
+
11
+ Backed internally by ``dateutil.rrule``; ``dateutil`` types and
12
+ exceptions never leak into the public API.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import re
18
+ from datetime import UTC
19
+ from datetime import datetime as _StdDateTime
20
+ from datetime import timedelta as _StdTimedelta
21
+ from typing import TYPE_CHECKING
22
+
23
+ from dateutil.relativedelta import relativedelta as _Relativedelta
24
+ from dateutil.rrule import (
25
+ DAILY,
26
+ FR,
27
+ HOURLY,
28
+ MINUTELY,
29
+ MO,
30
+ MONTHLY,
31
+ SA,
32
+ SECONDLY,
33
+ SU,
34
+ TH,
35
+ TU,
36
+ WE,
37
+ WEEKLY,
38
+ YEARLY,
39
+ rrule,
40
+ )
41
+ from dateutil.rrule import (
42
+ weekday as _RruleWeekday,
43
+ )
44
+
45
+ from ..core import Date, DateTime, LocalDateTime, Weekday
46
+ from ..errors import ParseError
47
+ from ._shared import Temporal, _from_stdlib, _require_str, _require_temporal, _to_stdlib
48
+
49
+ if TYPE_CHECKING:
50
+ from collections.abc import Callable, Iterable
51
+
52
+ __all__ = ["Recurrence"]
53
+
54
+ #: dateutil weekday constants, indexed by ``Weekday`` value (Monday=0).
55
+ _WEEKDAY_CONSTANTS: tuple[_RruleWeekday, ...] = (MO, TU, WE, TH, FR, SA, SU)
56
+
57
+ #: iCalendar weekday tokens, indexed by ``Weekday`` value.
58
+ _WEEKDAY_TOKENS: tuple[str, ...] = ("MO", "TU", "WE", "TH", "FR", "SA", "SU")
59
+ _TOKEN_TO_WEEKDAY: dict[str, int] = {
60
+ token: index for index, token in enumerate(_WEEKDAY_TOKENS)
61
+ }
62
+
63
+ #: iCalendar frequency names, keyed by dateutil frequency constant.
64
+ _FREQ_NAMES: dict[int, str] = {
65
+ YEARLY: "YEARLY",
66
+ MONTHLY: "MONTHLY",
67
+ WEEKLY: "WEEKLY",
68
+ DAILY: "DAILY",
69
+ HOURLY: "HOURLY",
70
+ MINUTELY: "MINUTELY",
71
+ SECONDLY: "SECONDLY",
72
+ }
73
+ _NAME_TO_FREQ: dict[str, int] = {name: freq for freq, name in _FREQ_NAMES.items()}
74
+
75
+ #: Sub-daily frequencies, which need a time of day and so cannot
76
+ #: produce ``Date`` occurrences.
77
+ _SUB_DAILY_FREQS: frozenset[int] = frozenset({HOURLY, MINUTELY, SECONDLY})
78
+
79
+ _BYDAY_RE = re.compile(r"^([+-]?\d{1,2})?(MO|TU|WE|TH|FR|SA|SU)$")
80
+ _UNTIL_RE = re.compile(r"^(\d{8})(?:T(\d{6})(Z)?)?$")
81
+
82
+
83
+ def _require_int(value: object, what: str) -> int:
84
+ """Return ``value`` if it is an int (not a bool), else raise ``TypeError``."""
85
+ if isinstance(value, bool) or not isinstance(value, int):
86
+ raise TypeError(f"{what} must be an int, got {type(value).__name__}")
87
+ return value
88
+
89
+
90
+ def _require_positive(value: int, what: str) -> int:
91
+ """Return ``value`` if it is >= 1, else raise ``ValueError``."""
92
+ if value < 1:
93
+ raise ValueError(f"{what} must be >= 1, got {value}")
94
+ return value
95
+
96
+
97
+ def _validate_day_of_month(value: object, what: str) -> int:
98
+ """Validate a day-of-month: 1..31 or -31..-1 (negative counts from the end)."""
99
+ day = _require_int(value, what)
100
+ if day == 0 or day < -31 or day > 31:
101
+ raise ValueError(f"{what} must be in 1..31 or -31..-1, got {day}")
102
+ return day
103
+
104
+
105
+ def _validate_month(value: object, what: str) -> int:
106
+ """Validate a month number, 1..12."""
107
+ month = _require_int(value, what)
108
+ if month < 1 or month > 12:
109
+ raise ValueError(f"{what} must be in 1..12, got {month}")
110
+ return month
111
+
112
+
113
+ def _normalize_weekday(value: object, what: str) -> int:
114
+ """Normalize a weekday given as a ``Weekday`` or an int (Monday=0) to an int."""
115
+ if isinstance(value, Weekday):
116
+ return int(value)
117
+ day = _require_int(value, what)
118
+ if day < 0 or day > 6:
119
+ raise ValueError(f"{what} must be a Weekday or an int in 0..6, got {day}")
120
+ return day
121
+
122
+
123
+ def _normalize_weekdays(
124
+ values: Iterable[Weekday | int] | None, what: str
125
+ ) -> tuple[int, ...] | None:
126
+ """Normalize an iterable of weekdays to a sorted tuple of ints.
127
+
128
+ Returns ``None`` when ``values`` is ``None`` (meaning "same weekday
129
+ as the start"). An empty iterable raises ``ValueError``.
130
+ """
131
+ if values is None:
132
+ return None
133
+ normalized = [_normalize_weekday(value, what) for value in values]
134
+ if not normalized:
135
+ raise ValueError(f"{what} must not be empty")
136
+ return tuple(sorted(set(normalized)))
137
+
138
+
139
+ def _normalize_until(
140
+ until: object,
141
+ ) -> tuple[_StdDateTime | None, bool]:
142
+ """Normalize an ``until`` bound to a stdlib datetime plus an is-date flag.
143
+
144
+ The flag records whether the bound came from a ``Date`` (or a
145
+ date-only iCalendar ``UNTIL``), so :meth:`Recurrence.to_ical` can
146
+ emit a date-only value for it. Takes ``object`` so the runtime
147
+ type checks below are meaningful to pyright.
148
+ """
149
+ if until is None:
150
+ return None, False
151
+ if isinstance(until, Date):
152
+ return _StdDateTime(until.year, until.month, until.day), True
153
+ if isinstance(until, LocalDateTime):
154
+ return until.to_datetime(), False
155
+ if isinstance(until, DateTime):
156
+ return until.to_datetime(), False
157
+ if isinstance(until, _StdDateTime):
158
+ return until, False
159
+ raise TypeError(
160
+ "until must be a Date, LocalDateTime, DateTime, or None, "
161
+ f"got {type(until).__name__}"
162
+ )
163
+
164
+
165
+ def _until_as_wall(until: _StdDateTime | None, start: Temporal) -> _StdDateTime | None:
166
+ """Express a stored ``until`` bound as a naive wall-clock datetime.
167
+
168
+ The bound is read in the start's frame: for a ``DateTime`` start
169
+ an aware bound is converted to that zone's wall time; for a naive
170
+ start an aware bound is read as UTC wall time; for a ``Date``
171
+ start only the date part matters (midnight is already stored).
172
+ """
173
+ if until is None:
174
+ return None
175
+ if isinstance(start, DateTime):
176
+ if until.tzinfo is not None:
177
+ return until.astimezone(start.timezone.to_zoneinfo()).replace(tzinfo=None)
178
+ return until
179
+ if until.tzinfo is not None:
180
+ return until.astimezone(UTC).replace(tzinfo=None)
181
+ return until
182
+
183
+
184
+ class Recurrence:
185
+ """A repeating pattern, anchored to a start only when queried.
186
+
187
+ Build rules with the classmethods (:meth:`daily`, :meth:`weekly`,
188
+ :meth:`monthly`, :meth:`yearly`, :meth:`hourly`, :meth:`minutely`)
189
+ or parse one from iCalendar text with :meth:`from_ical`.
190
+ A rule carries no start moment of its own: every query method
191
+ takes the anchor as its argument, and that anchor also fixes the
192
+ phase of the pattern (for example, an every-2-days rule anchored
193
+ at January 1 yields January 1, 3, 5, ...).
194
+
195
+ DST behaviour for ``DateTime`` recurrences: occurrences keep the
196
+ same wall-clock time in the zone. A wall time that is ambiguous
197
+ (DST fall-back) resolves to the earlier occurrence; a wall time
198
+ that does not exist (DST spring-forward) shifts forward to the
199
+ corresponding valid time after the gap (e.g. 02:30 becomes 03:30).
200
+
201
+ A yearly rule given only a day (``yearly(day=15)``) repeats on
202
+ that day of the start's month each year; a monthly rule given a
203
+ weekday without an occurrence repeats on every such weekday of
204
+ the month. See the individual classmethods for details.
205
+
206
+ Example:
207
+ >>> rule = Recurrence.weekly([Weekday.MONDAY, Weekday.WEDNESDAY])
208
+ >>> rule.occurrences(Date(2026, 1, 5), count=3)
209
+ [Date(2026, 1, 5), Date(2026, 1, 7), Date(2026, 1, 12)]
210
+ """
211
+
212
+ __slots__ = (
213
+ "_bymonth",
214
+ "_bymonthday",
215
+ "_bysetpos",
216
+ "_byweekday",
217
+ "_count",
218
+ "_extra",
219
+ "_freq",
220
+ "_interval",
221
+ "_until",
222
+ "_until_is_date",
223
+ "_wkst",
224
+ )
225
+
226
+ _freq: int
227
+ _interval: int
228
+ _count: int | None
229
+ _until: _StdDateTime | None
230
+ _until_is_date: bool
231
+ _byweekday: tuple[tuple[int, int | None], ...] | None
232
+ _bymonthday: tuple[int, ...] | None
233
+ _bymonth: tuple[int, ...] | None
234
+ _bysetpos: tuple[int, ...] | None
235
+ _extra: tuple[tuple[str, tuple[int, ...] | int], ...]
236
+ _wkst: int | None
237
+
238
+ def __init__(
239
+ self,
240
+ *,
241
+ freq: int,
242
+ interval: int = 1,
243
+ count: int | None = None,
244
+ until: Date | LocalDateTime | DateTime | _StdDateTime | None = None,
245
+ byweekday: tuple[tuple[int, int | None], ...] | None = None,
246
+ bymonthday: tuple[int, ...] | None = None,
247
+ bymonth: tuple[int, ...] | None = None,
248
+ bysetpos: tuple[int, ...] | None = None,
249
+ extra: tuple[tuple[str, tuple[int, ...] | int], ...] = (),
250
+ wkst: int | None = None,
251
+ until_is_date: bool = False,
252
+ ) -> None:
253
+ self._freq = freq
254
+ self._interval = interval
255
+ self._count = count
256
+ normalized_until, is_date = _normalize_until(until)
257
+ self._until = normalized_until
258
+ self._until_is_date = until_is_date or is_date
259
+ self._byweekday = byweekday
260
+ self._bymonthday = bymonthday
261
+ self._bymonth = bymonth
262
+ self._bysetpos = bysetpos
263
+ self._extra = extra
264
+ self._wkst = wkst
265
+
266
+ # -- constructors ---------------------------------------------------
267
+
268
+ @classmethod
269
+ def daily(
270
+ cls,
271
+ interval: int = 1,
272
+ *,
273
+ count: int | None = None,
274
+ until: Date | LocalDateTime | DateTime | None = None,
275
+ ) -> Recurrence:
276
+ """Return a rule repeating every ``interval`` days.
277
+
278
+ Example:
279
+ >>> Recurrence.daily(interval=2).occurrences(Date(2026, 1, 1), count=3)
280
+ [Date(2026, 1, 1), Date(2026, 1, 3), Date(2026, 1, 5)]
281
+ """
282
+ return cls(
283
+ freq=DAILY,
284
+ interval=_require_positive(_require_int(interval, "interval"), "interval"),
285
+ count=_validate_count(count),
286
+ until=until,
287
+ )
288
+
289
+ @classmethod
290
+ def weekly(
291
+ cls,
292
+ weekdays: Iterable[Weekday | int] | None = None,
293
+ interval: int = 1,
294
+ *,
295
+ count: int | None = None,
296
+ until: Date | LocalDateTime | DateTime | None = None,
297
+ ) -> Recurrence:
298
+ """Return a rule repeating every ``interval`` weeks on ``weekdays``.
299
+
300
+ ``weekdays`` is an iterable of :class:`~timecore.core.Weekday`
301
+ (or ints, Monday=0). When omitted, the rule repeats on the
302
+ start's weekday. An empty iterable raises ``ValueError``.
303
+
304
+ Example:
305
+ >>> rule = Recurrence.weekly([Weekday.MONDAY, Weekday.FRIDAY])
306
+ >>> rule.occurrences(Date(2026, 1, 5), count=3)
307
+ [Date(2026, 1, 5), Date(2026, 1, 9), Date(2026, 1, 12)]
308
+ """
309
+ normalized = _normalize_weekdays(weekdays, "weekdays")
310
+ byweekday = (
311
+ None if normalized is None else tuple((day, None) for day in normalized)
312
+ )
313
+ return cls(
314
+ freq=WEEKLY,
315
+ interval=_require_positive(_require_int(interval, "interval"), "interval"),
316
+ count=_validate_count(count),
317
+ until=until,
318
+ byweekday=byweekday,
319
+ )
320
+
321
+ @classmethod
322
+ def monthly(
323
+ cls,
324
+ day: int | None = None,
325
+ *,
326
+ weekday: Weekday | int | None = None,
327
+ occurrence: int | None = None,
328
+ interval: int = 1,
329
+ count: int | None = None,
330
+ until: Date | LocalDateTime | DateTime | None = None,
331
+ ) -> Recurrence:
332
+ """Return a rule repeating every ``interval`` months.
333
+
334
+ Give ``day`` for a fixed day of the month (1..31, or negative
335
+ to count from the end of the month, e.g. ``-1`` for the last
336
+ day); months without that day are skipped. Give ``weekday``
337
+ with ``occurrence`` for an nth weekday (e.g. the second
338
+ Tuesday: ``weekday=Weekday.TUESDAY, occurrence=2``; negative
339
+ occurrences count from the end, e.g. ``-1`` for the last).
340
+ A weekday without an occurrence repeats on every such weekday
341
+ of the month. Give neither ``day`` nor ``weekday`` to repeat
342
+ on the start's day of the month. ``occurrence`` without a
343
+ weekday raises ``ValueError``; ``day`` and ``weekday`` cannot
344
+ be combined.
345
+ """
346
+ if day is not None and weekday is not None:
347
+ raise ValueError("monthly() takes either day or weekday, not both")
348
+ if occurrence is not None and weekday is None:
349
+ raise ValueError("monthly() occurrence requires weekday")
350
+ bymonthday = None if day is None else (_validate_day_of_month(day, "day"),)
351
+ byweekday: tuple[tuple[int, int | None], ...] | None = None
352
+ if weekday is not None:
353
+ if occurrence is not None:
354
+ occurrence = _require_int(occurrence, "occurrence")
355
+ if occurrence == 0 or occurrence < -5 or occurrence > 5:
356
+ raise ValueError(
357
+ f"occurrence must be in 1..5 or -5..-1, got {occurrence}"
358
+ )
359
+ byweekday = ((_normalize_weekday(weekday, "weekday"), occurrence),)
360
+ return cls(
361
+ freq=MONTHLY,
362
+ interval=_require_positive(_require_int(interval, "interval"), "interval"),
363
+ count=_validate_count(count),
364
+ until=until,
365
+ byweekday=byweekday,
366
+ bymonthday=bymonthday,
367
+ )
368
+
369
+ @classmethod
370
+ def yearly(
371
+ cls,
372
+ month: int | None = None,
373
+ day: int | None = None,
374
+ interval: int = 1,
375
+ *,
376
+ count: int | None = None,
377
+ until: Date | LocalDateTime | DateTime | None = None,
378
+ ) -> Recurrence:
379
+ """Return a rule repeating every ``interval`` years.
380
+
381
+ Give ``month`` and/or ``day`` to fix the date within the year.
382
+ With only ``month``, the rule repeats on the start's day of
383
+ that month; with only ``day``, on that day of the start's
384
+ month; with neither, on the start's month and day.
385
+ """
386
+ bymonth = None if month is None else (_validate_month(month, "month"),)
387
+ bymonthday = None if day is None else (_validate_day_of_month(day, "day"),)
388
+ return cls(
389
+ freq=YEARLY,
390
+ interval=_require_positive(_require_int(interval, "interval"), "interval"),
391
+ count=_validate_count(count),
392
+ until=until,
393
+ bymonth=bymonth,
394
+ bymonthday=bymonthday,
395
+ )
396
+
397
+ @classmethod
398
+ def hourly(
399
+ cls,
400
+ interval: int = 1,
401
+ *,
402
+ count: int | None = None,
403
+ until: Date | LocalDateTime | DateTime | None = None,
404
+ ) -> Recurrence:
405
+ """Return a rule repeating every ``interval`` hours.
406
+
407
+ Hourly (and minutely) rules need a datetime start; a ``Date``
408
+ start raises ``ValueError`` when queried.
409
+ """
410
+ return cls(
411
+ freq=HOURLY,
412
+ interval=_require_positive(_require_int(interval, "interval"), "interval"),
413
+ count=_validate_count(count),
414
+ until=until,
415
+ )
416
+
417
+ @classmethod
418
+ def minutely(
419
+ cls,
420
+ interval: int = 1,
421
+ *,
422
+ count: int | None = None,
423
+ until: Date | LocalDateTime | DateTime | None = None,
424
+ ) -> Recurrence:
425
+ """Return a rule repeating every ``interval`` minutes.
426
+
427
+ Minutely (and hourly) rules need a datetime start; a ``Date``
428
+ start raises ``ValueError`` when queried.
429
+ """
430
+ return cls(
431
+ freq=MINUTELY,
432
+ interval=_require_positive(_require_int(interval, "interval"), "interval"),
433
+ count=_validate_count(count),
434
+ until=until,
435
+ )
436
+
437
+ # -- iCalendar ------------------------------------------------------
438
+
439
+ @classmethod
440
+ def from_ical(cls, rrule_text: str) -> Recurrence:
441
+ """Parse an iCalendar recurrence rule.
442
+
443
+ Accepts a bare ``RRULE`` value (``"FREQ=DAILY;COUNT=3"``), a
444
+ full ``"RRULE:..."`` line, or a multi-line block containing a
445
+ ``DTSTART`` line (which is ignored: the rule is anchored by
446
+ the start passed to the query methods, not by the text).
447
+ ``UNTIL`` is read as wall-clock time in the start's frame.
448
+
449
+ Raises:
450
+ ParseError: If the text is not a valid recurrence rule.
451
+ """
452
+ rrule_text = _require_str(rrule_text, "from_ical()")
453
+ text = rrule_text.strip()
454
+ if not text:
455
+ raise ParseError("cannot parse an empty recurrence rule")
456
+ value: str | None = None
457
+ for line in text.splitlines():
458
+ stripped = line.strip()
459
+ if not stripped:
460
+ continue
461
+ upper = stripped.upper()
462
+ if upper.startswith("RRULE:"):
463
+ value = stripped[len("RRULE:") :]
464
+ break
465
+ if upper.startswith("DTSTART"):
466
+ continue
467
+ if "FREQ=" in upper:
468
+ value = stripped
469
+ break
470
+ raise ParseError(f"cannot parse recurrence rule: {rrule_text!r}")
471
+ if value is None:
472
+ raise ParseError(f"cannot parse recurrence rule: {rrule_text!r}")
473
+ return cls._parse_rrule_value(value, rrule_text)
474
+
475
+ @classmethod
476
+ def _parse_rrule_value(cls, value: str, original: str) -> Recurrence:
477
+ """Parse the ``KEY=VALUE;...`` body of an ``RRULE`` line."""
478
+ freq: int | None = None
479
+ interval = 1
480
+ count: int | None = None
481
+ until: _StdDateTime | None = None
482
+ until_is_date = False
483
+ byweekday: tuple[tuple[int, int | None], ...] | None = None
484
+ bymonthday: tuple[int, ...] | None = None
485
+ bymonth: tuple[int, ...] | None = None
486
+ bysetpos: tuple[int, ...] | None = None
487
+ extra: dict[str, tuple[int, ...] | int] = {}
488
+ wkst: int | None = None
489
+
490
+ def fail(message: str) -> ParseError:
491
+ return ParseError(f"cannot parse recurrence rule {original!r}: {message}")
492
+
493
+ for part in value.split(";"):
494
+ if not part:
495
+ continue
496
+ if "=" not in part:
497
+ raise fail(f"expected KEY=VALUE, got {part!r}")
498
+ key, raw = part.split("=", 1)
499
+ key = key.strip().upper()
500
+ raw = raw.strip()
501
+ if key == "FREQ":
502
+ name = raw.upper()
503
+ if name not in _NAME_TO_FREQ:
504
+ raise fail(f"unknown FREQ {raw!r}")
505
+ freq = _NAME_TO_FREQ[name]
506
+ elif key == "INTERVAL":
507
+ interval = _parse_ical_int(raw, "INTERVAL", fail)
508
+ if interval < 1:
509
+ raise fail(f"INTERVAL must be >= 1, got {interval}")
510
+ elif key == "COUNT":
511
+ count = _parse_ical_int(raw, "COUNT", fail)
512
+ if count < 1:
513
+ raise fail(f"COUNT must be >= 1, got {count}")
514
+ elif key == "UNTIL":
515
+ match = _UNTIL_RE.fullmatch(raw)
516
+ if match is None:
517
+ raise fail(f"invalid UNTIL {raw!r}")
518
+ date_part, time_part, zulu = match.groups()
519
+ year, month, day = (
520
+ int(date_part[0:4]),
521
+ int(date_part[4:6]),
522
+ int(date_part[6:8]),
523
+ )
524
+ if time_part is None:
525
+ try:
526
+ until = _StdDateTime(year, month, day)
527
+ except ValueError as exc:
528
+ raise fail(f"invalid UNTIL {raw!r}") from exc
529
+ until_is_date = True
530
+ else:
531
+ hour, minute, second = (
532
+ int(time_part[0:2]),
533
+ int(time_part[2:4]),
534
+ int(time_part[4:6]),
535
+ )
536
+ try:
537
+ until = _StdDateTime(year, month, day, hour, minute, second)
538
+ except ValueError as exc:
539
+ raise fail(f"invalid UNTIL {raw!r}") from exc
540
+ if zulu:
541
+ until = until.replace(tzinfo=UTC)
542
+ elif key == "BYDAY":
543
+ parsed_days: list[tuple[int, int | None]] = []
544
+ for token in raw.split(","):
545
+ token = token.strip()
546
+ day_match = _BYDAY_RE.fullmatch(token.upper())
547
+ if day_match is None:
548
+ raise fail(f"invalid BYDAY token {token!r}")
549
+ occurrence_text, weekday_token = day_match.groups()
550
+ occurrence: int | None = None
551
+ if occurrence_text:
552
+ occurrence = int(occurrence_text)
553
+ if occurrence == 0 or occurrence < -53 or occurrence > 53:
554
+ raise fail(f"invalid BYDAY occurrence in {token!r}")
555
+ parsed_days.append((_TOKEN_TO_WEEKDAY[weekday_token], occurrence))
556
+ if not parsed_days:
557
+ raise fail("BYDAY must not be empty")
558
+ byweekday = tuple(parsed_days)
559
+ elif key in (
560
+ "BYMONTHDAY",
561
+ "BYMONTH",
562
+ "BYSETPOS",
563
+ "BYHOUR",
564
+ "BYMINUTE",
565
+ "BYSECOND",
566
+ "BYYEARDAY",
567
+ "BYWEEKNO",
568
+ ):
569
+ numbers = _parse_ical_int_list(raw, key, fail)
570
+ _validate_ical_numbers(key, numbers, fail)
571
+ if key == "BYMONTHDAY":
572
+ bymonthday = tuple(numbers)
573
+ elif key == "BYMONTH":
574
+ bymonth = tuple(numbers)
575
+ elif key == "BYSETPOS":
576
+ bysetpos = tuple(numbers)
577
+ else:
578
+ extra[key] = tuple(numbers)
579
+ elif key == "BYEASTER":
580
+ offset = _parse_ical_int(raw, "BYEASTER", fail)
581
+ if offset < -366 or offset > 366:
582
+ raise fail(f"BYEASTER must be in -366..366, got {offset}")
583
+ extra[key] = offset
584
+ elif key == "WKST":
585
+ token = raw.upper()
586
+ if token not in _TOKEN_TO_WEEKDAY:
587
+ raise fail(f"invalid WKST {raw!r}")
588
+ wkst = _TOKEN_TO_WEEKDAY[token]
589
+ else:
590
+ raise fail(f"unsupported RRULE part {key!r}")
591
+ if freq is None:
592
+ raise fail("missing FREQ")
593
+ return cls(
594
+ freq=freq,
595
+ interval=interval,
596
+ count=count,
597
+ until=until,
598
+ byweekday=byweekday,
599
+ bymonthday=bymonthday,
600
+ bymonth=bymonth,
601
+ bysetpos=bysetpos,
602
+ extra=tuple(sorted(extra.items())),
603
+ wkst=wkst,
604
+ until_is_date=until_is_date,
605
+ )
606
+
607
+ def to_ical(self) -> str:
608
+ """Return this rule as an iCalendar ``RRULE`` line.
609
+
610
+ The line carries no ``DTSTART``: the rule is anchored by the
611
+ start passed to the query methods. ``UNTIL`` is emitted in
612
+ wall-clock form (no ``Z`` suffix); a date-only bound is
613
+ emitted as a plain date. The result round-trips through
614
+ :meth:`from_ical` to a rule with the same occurrences.
615
+ """
616
+ parts = [f"FREQ={_FREQ_NAMES[self._freq]}"]
617
+ if self._interval != 1:
618
+ parts.append(f"INTERVAL={self._interval}")
619
+ if self._count is not None:
620
+ parts.append(f"COUNT={self._count}")
621
+ if self._until is not None:
622
+ wall = self._until.replace(tzinfo=None)
623
+ if self._until_is_date:
624
+ parts.append(f"UNTIL={wall.strftime('%Y%m%d')}")
625
+ else:
626
+ parts.append(f"UNTIL={wall.strftime('%Y%m%dT%H%M%S')}")
627
+ if self._byweekday is not None:
628
+ tokens: list[str] = []
629
+ for day, occurrence in self._byweekday:
630
+ prefix = "" if occurrence is None else str(occurrence)
631
+ tokens.append(f"{prefix}{_WEEKDAY_TOKENS[day]}")
632
+ parts.append(f"BYDAY={','.join(tokens)}")
633
+ if self._bymonthday is not None:
634
+ parts.append(f"BYMONTHDAY={','.join(str(n) for n in self._bymonthday)}")
635
+ if self._bymonth is not None:
636
+ parts.append(f"BYMONTH={','.join(str(n) for n in self._bymonth)}")
637
+ if self._bysetpos is not None:
638
+ parts.append(f"BYSETPOS={','.join(str(n) for n in self._bysetpos)}")
639
+ for key, numbers in self._extra:
640
+ if isinstance(numbers, int):
641
+ parts.append(f"{key}={numbers}")
642
+ else:
643
+ parts.append(f"{key}={','.join(str(n) for n in numbers)}")
644
+ if self._wkst is not None:
645
+ parts.append(f"WKST={_WEEKDAY_TOKENS[self._wkst]}")
646
+ return "RRULE:" + ";".join(parts)
647
+
648
+ # -- queries ----------------------------------------------------------
649
+
650
+ def occurrences(
651
+ self,
652
+ start: Date | LocalDateTime | DateTime,
653
+ count: int | None = None,
654
+ until: Date | LocalDateTime | DateTime | None = None,
655
+ ) -> list[Date | LocalDateTime | DateTime]:
656
+ """Return occurrences anchored at ``start``.
657
+
658
+ ``start`` itself is the first occurrence (when it matches the
659
+ rule). ``count`` and ``until`` override the bound set when the
660
+ rule was built, if any. At least one bound must apply -- the
661
+ rule's own, or one given here -- otherwise ``ValueError`` is
662
+ raised, since the rule would otherwise produce infinitely
663
+ many occurrences. ``until`` is inclusive.
664
+ """
665
+ start = _require_temporal(start, "occurrences() start")
666
+ effective_count = _validate_count(count) if count is not None else self._count
667
+ effective_until, _ = (
668
+ _normalize_until(until) if until is not None else (self._until, False)
669
+ )
670
+ if effective_count is None and effective_until is None:
671
+ raise ValueError(
672
+ "occurrences() needs a bound: give count or until, "
673
+ "or build the rule with count or until"
674
+ )
675
+ rule, until_wall = self._build_rrule(
676
+ start, count=effective_count, until=effective_until
677
+ )
678
+ try:
679
+ raw = list(rule)
680
+ except (ValueError, OverflowError) as exc:
681
+ raise ParseError(f"could not expand recurrence: {exc}") from exc
682
+ if until_wall is not None:
683
+ raw = [value for value in raw if value <= until_wall]
684
+ return [self._convert(value, start) for value in raw]
685
+
686
+ def next(
687
+ self, after: Date | LocalDateTime | DateTime
688
+ ) -> Date | LocalDateTime | DateTime | None:
689
+ """Return the first occurrence strictly after ``after``.
690
+
691
+ The rule is anchored at ``after``: the phase is fixed by that
692
+ moment (for example, an every-2-days rule queried after
693
+ January 2 yields January 4). Returns ``None`` when the rule
694
+ is exhausted (its ``count`` or ``until`` bound is reached).
695
+ """
696
+ after = _require_temporal(after, "next() after")
697
+ rule, until_wall = self._build_rrule(after)
698
+ try:
699
+ raw = rule.after(_to_stdlib_wall(after), inc=False)
700
+ except (ValueError, OverflowError) as exc:
701
+ raise ParseError(f"could not expand recurrence: {exc}") from exc
702
+ if raw is None:
703
+ return None
704
+ if until_wall is not None and raw > until_wall:
705
+ return None
706
+ return self._convert(raw, after)
707
+
708
+ def previous(
709
+ self, before: Date | LocalDateTime | DateTime
710
+ ) -> Date | LocalDateTime | DateTime | None:
711
+ """Return the last occurrence strictly before ``before``.
712
+
713
+ The rule is anchored at ``before`` (see :meth:`next`): the
714
+ pattern is searched backwards from that moment, so for
715
+ example an every-2-days rule queried before January 10 yields
716
+ January 8. A rule's ``count`` bound limits forward
717
+ occurrences only and does not apply here; its ``until`` bound
718
+ still applies. Returns ``None`` when there is no earlier
719
+ occurrence.
720
+ """
721
+ before = _require_temporal(before, "previous() before")
722
+ rule, until_wall = self._build_rrule(before, shift_back=True)
723
+ try:
724
+ raw = rule.before(_to_stdlib_wall(before), inc=False)
725
+ except (ValueError, OverflowError) as exc:
726
+ raise ParseError(f"could not expand recurrence: {exc}") from exc
727
+ if raw is None:
728
+ return None
729
+ if until_wall is not None and raw > until_wall:
730
+ return None
731
+ return self._convert(raw, before)
732
+
733
+ def between(
734
+ self,
735
+ start: Date | LocalDateTime | DateTime,
736
+ end: Date | LocalDateTime | DateTime,
737
+ ) -> list[Date | LocalDateTime | DateTime]:
738
+ """Return occurrences in the half-open interval ``[start, end)``.
739
+
740
+ The rule is anchored at ``start``. Raises ``ValueError`` when
741
+ ``end`` is before ``start``; a ``start`` equal to ``end`` is
742
+ an empty interval.
743
+ """
744
+ start = _require_temporal(start, "between() start")
745
+ end = _require_temporal(end, "between() end")
746
+ if type(start) is not type(end):
747
+ raise TypeError(
748
+ "between() start and end must be the same type, got "
749
+ f"{type(start).__name__} and {type(end).__name__}"
750
+ )
751
+ if end < start:
752
+ raise ValueError("between() end must not be before start")
753
+ rule, until_wall = self._build_rrule(start)
754
+ try:
755
+ raw = rule.between(_to_stdlib_wall(start), _to_stdlib_wall(end), inc=True)
756
+ except (ValueError, OverflowError) as exc:
757
+ raise ParseError(f"could not expand recurrence: {exc}") from exc
758
+ end_wall = _to_stdlib_wall(end)
759
+ return [
760
+ self._convert(value, start)
761
+ for value in raw
762
+ if value != end_wall and (until_wall is None or value <= until_wall)
763
+ ]
764
+
765
+ # -- internals --------------------------------------------------------
766
+
767
+ def _build_rrule(
768
+ self,
769
+ start: Temporal,
770
+ *,
771
+ count: int | None = None,
772
+ until: _StdDateTime | None = None,
773
+ shift_back: bool = False,
774
+ ) -> tuple[rrule, _StdDateTime | None]:
775
+ """Build the dateutil ``rrule`` anchored at ``start``.
776
+
777
+ Returns the rule plus the effective ``until`` bound as a naive
778
+ wall-clock datetime (or ``None``). ``DateTime`` rules run on
779
+ naive wall-clock datetimes so that occurrences keep the same
780
+ wall time across DST transitions; conversion back (see
781
+ :func:`_from_stdlib`) applies the DST policy. ``count`` /
782
+ ``until`` default to the rule's own bound. With ``shift_back``
783
+ (for :meth:`previous`), the anchor is moved back by twelve
784
+ intervals -- a whole number of periods, so the phase is
785
+ preserved -- and ``count`` is ignored, since a count bound
786
+ limits forward occurrences only.
787
+
788
+ Only one of ``count`` / ``until`` is passed to ``dateutil``:
789
+ passing both is deprecated by dateutil (and inconsistent with
790
+ RFC 5545), so when both apply the rule is built with ``count``
791
+ and callers filter by the returned ``until`` bound.
792
+ """
793
+ if isinstance(start, Date) and self._freq in _SUB_DAILY_FREQS:
794
+ raise ValueError(
795
+ "a sub-daily recurrence (hourly/minutely) needs a "
796
+ "datetime start, not a Date"
797
+ )
798
+ if count is None and not shift_back:
799
+ count = self._count
800
+ if until is None:
801
+ until_wall = _until_as_wall(self._until, start)
802
+ else:
803
+ until_wall = _until_as_wall(until, start)
804
+ dtstart = _to_stdlib_wall(start)
805
+ if shift_back:
806
+ dtstart = _shift_back_wall(dtstart, self._freq, self._interval)
807
+ kwargs: dict[str, object] = {
808
+ "freq": self._freq,
809
+ "dtstart": dtstart,
810
+ "interval": self._interval,
811
+ }
812
+ if count is not None:
813
+ kwargs["count"] = count
814
+ elif until_wall is not None:
815
+ kwargs["until"] = until_wall
816
+ if self._wkst is not None:
817
+ kwargs["wkst"] = _WEEKDAY_CONSTANTS[self._wkst]
818
+ if self._bysetpos is not None:
819
+ kwargs["bysetpos"] = self._bysetpos
820
+ if self._bymonth is not None:
821
+ kwargs["bymonth"] = self._bymonth
822
+ if self._bymonthday is not None:
823
+ kwargs["bymonthday"] = self._bymonthday
824
+ byweekday = self._byweekday
825
+ # Defaults anchored at the start, matching dateutil's
826
+ # dtstart-derived defaults (and, for yearly, the start's month
827
+ # when only a day was given).
828
+ if self._freq == WEEKLY and byweekday is None:
829
+ byweekday = ((start.weekday.value, None),)
830
+ if self._freq == MONTHLY and byweekday is None and self._bymonthday is None:
831
+ kwargs["bymonthday"] = (start.day,)
832
+ if self._freq == YEARLY:
833
+ if self._bymonth is None and self._bymonthday is None:
834
+ kwargs["bymonth"] = (start.month,)
835
+ kwargs["bymonthday"] = (start.day,)
836
+ elif self._bymonth is not None and self._bymonthday is None:
837
+ kwargs["bymonthday"] = (start.day,)
838
+ elif self._bymonthday is not None and self._bymonth is None:
839
+ kwargs["bymonth"] = (start.month,)
840
+ if byweekday is not None:
841
+ kwargs["byweekday"] = tuple(
842
+ _WEEKDAY_CONSTANTS[day]
843
+ if occurrence is None
844
+ else _WEEKDAY_CONSTANTS[day](occurrence)
845
+ for day, occurrence in byweekday
846
+ )
847
+ for key, numbers in self._extra:
848
+ kwargs[key.lower()] = numbers
849
+ try:
850
+ return rrule(**kwargs), until_wall # type: ignore[arg-type]
851
+ except (ValueError, OverflowError, TypeError) as exc:
852
+ raise ParseError(f"could not build recurrence: {exc}") from exc
853
+
854
+ def _convert(
855
+ self, value: _StdDateTime, start: Temporal
856
+ ) -> Date | LocalDateTime | DateTime:
857
+ """Convert a naive wall-clock occurrence back to the start's type."""
858
+ if isinstance(start, Date):
859
+ return _from_stdlib(value, Date)
860
+ if isinstance(start, LocalDateTime):
861
+ return _from_stdlib(value, LocalDateTime)
862
+ return _from_stdlib(value, DateTime, anchor=start)
863
+
864
+ def __eq__(self, other: object) -> bool:
865
+ if isinstance(other, Recurrence):
866
+ return (
867
+ self._freq == other._freq
868
+ and self._interval == other._interval
869
+ and self._count == other._count
870
+ and self._until == other._until
871
+ and self._until_is_date == other._until_is_date
872
+ and self._byweekday == other._byweekday
873
+ and self._bymonthday == other._bymonthday
874
+ and self._bymonth == other._bymonth
875
+ and self._bysetpos == other._bysetpos
876
+ and self._extra == other._extra
877
+ and self._wkst == other._wkst
878
+ )
879
+ return NotImplemented
880
+
881
+ def __hash__(self) -> int:
882
+ return hash(
883
+ (
884
+ self._freq,
885
+ self._interval,
886
+ self._count,
887
+ self._until,
888
+ self._until_is_date,
889
+ self._byweekday,
890
+ self._bymonthday,
891
+ self._bymonth,
892
+ self._bysetpos,
893
+ self._extra,
894
+ self._wkst,
895
+ )
896
+ )
897
+
898
+ def __repr__(self) -> str:
899
+ parts = [f"FREQ={_FREQ_NAMES[self._freq]}"]
900
+ if self._interval != 1:
901
+ parts.append(f"interval={self._interval}")
902
+ if self._count is not None:
903
+ parts.append(f"count={self._count}")
904
+ if self._until is not None:
905
+ parts.append(f"until={self._until!r}")
906
+ if self._byweekday is not None:
907
+ parts.append(f"byweekday={self._byweekday!r}")
908
+ if self._bymonthday is not None:
909
+ parts.append(f"bymonthday={self._bymonthday!r}")
910
+ if self._bymonth is not None:
911
+ parts.append(f"bymonth={self._bymonth!r}")
912
+ if self._bysetpos is not None:
913
+ parts.append(f"bysetpos={self._bysetpos!r}")
914
+ return f"Recurrence({', '.join(parts)})"
915
+
916
+
917
+ def _validate_count(count: int | None) -> int | None:
918
+ """Validate a ``count`` bound: ``None`` or an int >= 1."""
919
+ if count is None:
920
+ return None
921
+ count = _require_int(count, "count")
922
+ return _require_positive(count, "count")
923
+
924
+
925
+ def _to_stdlib_wall(value: Temporal) -> _StdDateTime:
926
+ """Convert a temporal value to a naive wall-clock stdlib datetime."""
927
+ if isinstance(value, DateTime):
928
+ return value.to_local_datetime().to_datetime()
929
+ return _to_stdlib(value)
930
+
931
+
932
+ def _shift_back_wall(wall: _StdDateTime, freq: int, interval: int) -> _StdDateTime:
933
+ """Shift a wall-clock anchor back by twelve intervals.
934
+
935
+ Twelve is a whole number of periods for every frequency, so the
936
+ pattern's phase is preserved, and twelve periods always contain
937
+ at least one occurrence (even for sparse patterns such as the
938
+ 31st of the month or February 29).
939
+ """
940
+ steps = 12 * interval
941
+ if freq == YEARLY:
942
+ return wall + _Relativedelta(years=-steps)
943
+ if freq == MONTHLY:
944
+ return wall + _Relativedelta(months=-steps)
945
+ if freq == WEEKLY:
946
+ return wall - _StdTimedelta(weeks=steps)
947
+ if freq == DAILY:
948
+ return wall - _StdTimedelta(days=steps)
949
+ if freq == HOURLY:
950
+ return wall - _StdTimedelta(hours=steps)
951
+ if freq == MINUTELY:
952
+ return wall - _StdTimedelta(minutes=steps)
953
+ return wall - _StdTimedelta(seconds=steps)
954
+
955
+
956
+ def _parse_ical_int(raw: str, what: str, fail: Callable[[str], ParseError]) -> int:
957
+ """Parse an integer RRULE value, raising ``ParseError`` on failure."""
958
+ try:
959
+ return int(raw)
960
+ except ValueError as exc:
961
+ raise fail(f"invalid {what} {raw!r}") from exc
962
+
963
+
964
+ def _parse_ical_int_list(
965
+ raw: str, what: str, fail: Callable[[str], ParseError]
966
+ ) -> list[int]:
967
+ """Parse a comma-separated list of integer RRULE values."""
968
+ numbers: list[int] = []
969
+ for token in raw.split(","):
970
+ numbers.append(_parse_ical_int(token.strip(), what, fail))
971
+ if not numbers:
972
+ raise fail(f"{what} must not be empty")
973
+ return numbers
974
+
975
+
976
+ def _validate_ical_numbers(
977
+ key: str, numbers: list[int], fail: Callable[[str], ParseError]
978
+ ) -> None:
979
+ """Range-check integer lists for the given RRULE part."""
980
+ ranges: dict[str, tuple[int, int]] = {
981
+ "BYMONTHDAY": (-31, 31),
982
+ "BYMONTH": (1, 12),
983
+ "BYSETPOS": (-366, 366),
984
+ "BYHOUR": (0, 23),
985
+ "BYMINUTE": (0, 59),
986
+ "BYSECOND": (0, 59),
987
+ "BYYEARDAY": (-366, 366),
988
+ "BYWEEKNO": (-53, 53),
989
+ }
990
+ low, high = ranges[key]
991
+ for number in numbers:
992
+ if number == 0 and key in ("BYMONTHDAY", "BYSETPOS", "BYYEARDAY", "BYWEEKNO"):
993
+ raise fail(f"{key} must not contain 0")
994
+ if number < low or number > high:
995
+ raise fail(f"{key} value {number} is out of range {low}..{high}")