paul@33 | 1 | #!/usr/bin/env python |
paul@33 | 2 | |
paul@33 | 3 | """ |
paul@33 | 4 | Recurrence rule calculation. |
paul@33 | 5 | |
paul@1237 | 6 | Copyright (C) 2014, 2015, 2017 Paul Boddie <paul@boddie.org.uk> |
paul@33 | 7 | |
paul@33 | 8 | This program is free software; you can redistribute it and/or modify it under |
paul@33 | 9 | the terms of the GNU General Public License as published by the Free Software |
paul@33 | 10 | Foundation; either version 3 of the License, or (at your option) any later |
paul@33 | 11 | version. |
paul@33 | 12 | |
paul@33 | 13 | This program is distributed in the hope that it will be useful, but WITHOUT |
paul@33 | 14 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
paul@33 | 15 | FOR A PARTICULAR PURPOSE. See the GNU General Public License for more |
paul@33 | 16 | details. |
paul@33 | 17 | |
paul@33 | 18 | You should have received a copy of the GNU General Public License along with |
paul@33 | 19 | this program. If not, see <http://www.gnu.org/licenses/>. |
paul@33 | 20 | |
paul@33 | 21 | ---- |
paul@33 | 22 | |
paul@33 | 23 | References: |
paul@33 | 24 | |
paul@33 | 25 | RFC 5545: Internet Calendaring and Scheduling Core Object Specification |
paul@33 | 26 | (iCalendar) |
paul@33 | 27 | http://tools.ietf.org/html/rfc5545 |
paul@33 | 28 | |
paul@33 | 29 | ---- |
paul@33 | 30 | |
paul@33 | 31 | FREQ defines the selection resolution. |
paul@33 | 32 | DTSTART defines the start of the selection. |
paul@33 | 33 | INTERVAL defines the step of the selection. |
paul@521 | 34 | COUNT defines a number of instances |
paul@521 | 35 | UNTIL defines a limit to the selection. |
paul@33 | 36 | |
paul@33 | 37 | BY... qualifiers select instances within each outer selection instance according |
paul@33 | 38 | to the recurrence of instances of the next highest resolution. For example, |
paul@33 | 39 | BYDAY selects days in weeks. Thus, if no explicit week recurrence is indicated, |
paul@33 | 40 | all weeks are selected within the selection of the next highest explicitly |
paul@33 | 41 | specified resolution, whether this is months or years. |
paul@33 | 42 | |
paul@33 | 43 | BYSETPOS in conjunction with BY... qualifiers permit the selection of specific |
paul@33 | 44 | instances. |
paul@33 | 45 | |
paul@33 | 46 | Within the FREQ resolution, BY... qualifiers refine selected instances. |
paul@33 | 47 | |
paul@33 | 48 | Outside the FREQ resolution, BY... qualifiers select instances at the resolution |
paul@33 | 49 | concerned. |
paul@33 | 50 | |
paul@33 | 51 | Thus, FREQ and BY... qualifiers need to be ordered in terms of increasing |
paul@33 | 52 | resolution (or decreasing scope). |
paul@33 | 53 | """ |
paul@33 | 54 | |
paul@34 | 55 | from calendar import monthrange |
paul@1398 | 56 | from collections import OrderedDict |
paul@33 | 57 | from datetime import date, datetime, timedelta |
paul@33 | 58 | import operator |
paul@33 | 59 | |
paul@33 | 60 | # Frequency levels, specified by FREQ in iCalendar. |
paul@33 | 61 | |
paul@33 | 62 | freq_levels = ( |
paul@42 | 63 | "YEARLY", |
paul@42 | 64 | "MONTHLY", |
paul@42 | 65 | "WEEKLY", |
paul@1391 | 66 | None, # yearday has no equivalent frequency |
paul@1391 | 67 | None, # monthday has no equivalent frequency |
paul@33 | 68 | "DAILY", |
paul@42 | 69 | "HOURLY", |
paul@42 | 70 | "MINUTELY", |
paul@42 | 71 | "SECONDLY" |
paul@33 | 72 | ) |
paul@33 | 73 | |
paul@1359 | 74 | # Symbols corresponding to resolution levels. |
paul@1359 | 75 | |
paul@1359 | 76 | YEARS, MONTHS, WEEKS, DAYS, HOURS, MINUTES, SECONDS = 0, 1, 2, 5, 6, 7, 8 |
paul@1359 | 77 | |
paul@33 | 78 | # Enumeration levels, employed by BY... qualifiers. |
paul@33 | 79 | |
paul@33 | 80 | enum_levels = ( |
paul@42 | 81 | None, |
paul@44 | 82 | "BYMONTH", |
paul@44 | 83 | "BYWEEKNO", |
paul@44 | 84 | "BYYEARDAY", |
paul@44 | 85 | "BYMONTHDAY", |
paul@44 | 86 | "BYDAY", |
paul@44 | 87 | "BYHOUR", |
paul@44 | 88 | "BYMINUTE", |
paul@44 | 89 | "BYSECOND" |
paul@33 | 90 | ) |
paul@33 | 91 | |
paul@1241 | 92 | # Levels defining days. |
paul@1241 | 93 | |
paul@1241 | 94 | daylevels = [2, 3, 4, 5] |
paul@1241 | 95 | |
paul@33 | 96 | # Map from levels to lengths of datetime tuples. |
paul@33 | 97 | |
paul@44 | 98 | lengths = [1, 2, 3, 3, 3, 3, 4, 5, 6] |
paul@33 | 99 | positions = [l-1 for l in lengths] |
paul@33 | 100 | |
paul@1241 | 101 | # Define the lowest values at each resolution (years, months, days... hours, |
paul@1241 | 102 | # minutes, seconds). |
paul@1241 | 103 | |
paul@1241 | 104 | firstvalues = [0, 1, 1, 1, 1, 1, 0, 0, 0] |
paul@1241 | 105 | |
paul@1359 | 106 | # Map from qualifiers to interval multiples. Here, weeks are defined as 7 days. |
paul@33 | 107 | |
paul@1359 | 108 | multiples = {"WEEKLY" : 7} |
paul@33 | 109 | |
paul@33 | 110 | # Make dictionaries mapping qualifiers to levels. |
paul@33 | 111 | |
paul@1359 | 112 | freq = {} |
paul@1359 | 113 | for i, level in enumerate(freq_levels): |
paul@1359 | 114 | if level: |
paul@1359 | 115 | freq[level] = i |
paul@1359 | 116 | |
paul@1359 | 117 | enum = {} |
paul@1359 | 118 | for i, level in enumerate(enum_levels): |
paul@1359 | 119 | if level: |
paul@1359 | 120 | enum[level] = i |
paul@1359 | 121 | |
paul@1359 | 122 | # Weekdays: name -> 1-based value |
paul@1359 | 123 | |
paul@1398 | 124 | weekday_values = ["MO", "TU", "WE", "TH", "FR", "SA", "SU"] |
paul@1398 | 125 | |
paul@1398 | 126 | weekdays = OrderedDict() |
paul@1398 | 127 | for i, weekday in enumerate(weekday_values): |
paul@1359 | 128 | weekdays[weekday] = i + 1 |
paul@33 | 129 | |
paul@33 | 130 | # Functions for structuring the recurrences. |
paul@33 | 131 | |
paul@33 | 132 | def get_next(it): |
paul@1359 | 133 | |
paul@1359 | 134 | "Return the next value from iterator 'it' or None if no more values exist." |
paul@1359 | 135 | |
paul@33 | 136 | try: |
paul@33 | 137 | return it.next() |
paul@33 | 138 | except StopIteration: |
paul@33 | 139 | return None |
paul@33 | 140 | |
paul@46 | 141 | def get_parameters(values): |
paul@46 | 142 | |
paul@46 | 143 | "Return parameters from the given list of 'values'." |
paul@46 | 144 | |
paul@46 | 145 | d = {} |
paul@1398 | 146 | if not values: |
paul@1398 | 147 | return d |
paul@1398 | 148 | |
paul@46 | 149 | for value in values: |
paul@1361 | 150 | try: |
paul@1361 | 151 | key, value = value.split("=", 1) |
paul@1361 | 152 | d[key] = value |
paul@1361 | 153 | except ValueError: |
paul@46 | 154 | continue |
paul@46 | 155 | return d |
paul@46 | 156 | |
paul@46 | 157 | def get_qualifiers(values): |
paul@46 | 158 | |
paul@46 | 159 | """ |
paul@46 | 160 | Process the list of 'values' of the form "key=value", returning a list of |
paul@358 | 161 | qualifiers of the form (qualifier name, args). |
paul@46 | 162 | """ |
paul@46 | 163 | |
paul@46 | 164 | qualifiers = [] |
paul@46 | 165 | frequency = None |
paul@46 | 166 | interval = 1 |
paul@1398 | 167 | keys = set() |
paul@46 | 168 | |
paul@46 | 169 | for value in values: |
paul@1398 | 170 | |
paul@1398 | 171 | # Ignore qualifiers without values. |
paul@1398 | 172 | |
paul@1361 | 173 | try: |
paul@1361 | 174 | key, value = value.split("=", 1) |
paul@1361 | 175 | except ValueError: |
paul@46 | 176 | continue |
paul@1239 | 177 | |
paul@1398 | 178 | # Ignore duplicate qualifiers. |
paul@1398 | 179 | |
paul@1398 | 180 | if key in keys: |
paul@1398 | 181 | continue |
paul@1398 | 182 | |
paul@1398 | 183 | keys.add(key) |
paul@1398 | 184 | |
paul@1239 | 185 | # Accept frequency indicators as qualifiers. |
paul@1239 | 186 | |
paul@46 | 187 | if key == "FREQ" and freq.has_key(value): |
paul@46 | 188 | qualifier = frequency = (value, {}) |
paul@1239 | 189 | |
paul@1239 | 190 | # Accept interval indicators for frequency qualifier parameterisation. |
paul@1239 | 191 | |
paul@46 | 192 | elif key == "INTERVAL": |
paul@46 | 193 | interval = int(value) |
paul@46 | 194 | continue |
paul@1239 | 195 | |
paul@1361 | 196 | # Accept result set selection, truncation and enumerators as qualifiers. |
paul@1239 | 197 | |
paul@1361 | 198 | elif key in ("BYSETPOS", "COUNT") or enum.has_key(key): |
paul@46 | 199 | qualifier = (key, {"values" : get_qualifier_values(key, value)}) |
paul@1239 | 200 | |
paul@1239 | 201 | # Ignore other items. |
paul@1239 | 202 | |
paul@46 | 203 | else: |
paul@46 | 204 | continue |
paul@46 | 205 | |
paul@46 | 206 | qualifiers.append(qualifier) |
paul@46 | 207 | |
paul@1239 | 208 | # Parameterise any frequency qualifier with the interval. |
paul@1239 | 209 | |
paul@46 | 210 | if frequency: |
paul@46 | 211 | frequency[1]["interval"] = interval |
paul@46 | 212 | |
paul@46 | 213 | return qualifiers |
paul@46 | 214 | |
paul@46 | 215 | def get_qualifier_values(qualifier, value): |
paul@46 | 216 | |
paul@46 | 217 | """ |
paul@46 | 218 | For the given 'qualifier', process the 'value' string, returning a list of |
paul@46 | 219 | suitable values. |
paul@46 | 220 | """ |
paul@46 | 221 | |
paul@1398 | 222 | # For non-weekday selection, obtain a list of numbers. |
paul@1359 | 223 | |
paul@46 | 224 | if qualifier != "BYDAY": |
paul@46 | 225 | return map(int, value.split(",")) |
paul@46 | 226 | |
paul@1359 | 227 | # For weekday selection, obtain the weekday number and instance number. |
paul@1359 | 228 | |
paul@46 | 229 | values = [] |
paul@1359 | 230 | |
paul@46 | 231 | for part in value.split(","): |
paul@1398 | 232 | index, weekday = part[:-2], part[-2:] |
paul@1398 | 233 | |
paul@1398 | 234 | weekday_number = weekdays.get(weekday) |
paul@1398 | 235 | if not weekday_number: |
paul@46 | 236 | continue |
paul@1398 | 237 | |
paul@46 | 238 | if index: |
paul@46 | 239 | index = int(index) |
paul@46 | 240 | else: |
paul@46 | 241 | index = None |
paul@1398 | 242 | |
paul@1398 | 243 | values.append((weekday_number, index)) |
paul@46 | 244 | |
paul@46 | 245 | return values |
paul@46 | 246 | |
paul@33 | 247 | def order_qualifiers(qualifiers): |
paul@33 | 248 | |
paul@1398 | 249 | """ |
paul@1398 | 250 | Obtain 'qualifiers' in order of increasing resolution, producing and |
paul@1398 | 251 | returning selector objects corresponding to the qualifiers. |
paul@1398 | 252 | """ |
paul@33 | 253 | |
paul@33 | 254 | l = [] |
paul@1361 | 255 | |
paul@1398 | 256 | # Obtain selectors for the qualifiers. |
paul@33 | 257 | |
paul@33 | 258 | for qualifier, args in qualifiers: |
paul@1398 | 259 | selector = new_selector(qualifier, args) |
paul@1398 | 260 | l.append(selector) |
paul@1237 | 261 | |
paul@1398 | 262 | return sort_selectors(l) |
paul@1237 | 263 | |
paul@1398 | 264 | def new_selector(qualifier, args=None): |
paul@1361 | 265 | |
paul@1398 | 266 | "Return a selector for 'qualifier' and 'args'." |
paul@1398 | 267 | |
paul@1398 | 268 | # Distinguish between enumerators, used to select particular periods, |
paul@1398 | 269 | # and frequencies, used to select repeating periods. |
paul@1361 | 270 | |
paul@1398 | 271 | if enum.has_key(qualifier): |
paul@1398 | 272 | selector = special_enum_levels.get(qualifier, Enum) |
paul@1398 | 273 | return selector(enum[qualifier], args, qualifier) |
paul@1398 | 274 | |
paul@1398 | 275 | # Create a selector that must be updated with the maximum resolution. |
paul@1361 | 276 | |
paul@1398 | 277 | elif qualifier == "BYSETPOS": |
paul@1398 | 278 | return PositionSelector(None, args, "BYSETPOS") |
paul@1398 | 279 | |
paul@1398 | 280 | elif qualifier == "COUNT": |
paul@1398 | 281 | return LimitSelector(0, args, "COUNT") |
paul@1361 | 282 | |
paul@1398 | 283 | else: |
paul@1398 | 284 | return Pattern(freq[qualifier], args, qualifier) |
paul@1398 | 285 | |
paul@1398 | 286 | def sort_selectors(selectors): |
paul@1361 | 287 | |
paul@1398 | 288 | "Sort 'selectors' in order of increasing resolution." |
paul@1398 | 289 | |
paul@1398 | 290 | if not selectors: |
paul@1398 | 291 | return selectors |
paul@1398 | 292 | |
paul@1398 | 293 | max_level = max(map(lambda selector: selector.level or 0, selectors)) |
paul@33 | 294 | |
paul@1398 | 295 | # Update the result set selector at the maximum resolution. |
paul@33 | 296 | |
paul@1398 | 297 | for selector in selectors: |
paul@1398 | 298 | if isinstance(selector, PositionSelector): |
paul@1398 | 299 | selector.level = max_level |
paul@1361 | 300 | |
paul@1398 | 301 | selectors.sort(key=selector_sort_key) |
paul@1398 | 302 | return selectors |
paul@1361 | 303 | |
paul@1398 | 304 | def selector_sort_key(selector): |
paul@1361 | 305 | |
paul@1398 | 306 | "Produce a sort key for 'selector'." |
paul@1361 | 307 | |
paul@1361 | 308 | # Make BYSETPOS sort earlier than the enumeration it modifies. |
paul@1391 | 309 | # Other BY... qualifiers sort earlier than selectors at the same resolution |
paul@1391 | 310 | # even though such things as "FREQ=HOURLY;BYHOUR=10" do not make much sense. |
paul@1361 | 311 | |
paul@1398 | 312 | return (selector.level, not selector.qualifier.startswith("BY") and 2 or |
paul@1398 | 313 | selector.qualifier != "BYSETPOS" and 1 or 0) |
paul@1398 | 314 | |
paul@1398 | 315 | def get_value_ranges(qualifier): |
paul@1398 | 316 | |
paul@1398 | 317 | """ |
paul@1398 | 318 | Return value ranges for 'qualifier'. Each range is either given by a tuple |
paul@1398 | 319 | indicating the inclusive start and end values or by a list enumerating the |
paul@1398 | 320 | values. |
paul@1398 | 321 | """ |
paul@1398 | 322 | |
paul@1398 | 323 | # Provide ranges for the numeric value of each qualifier. |
paul@1398 | 324 | |
paul@1398 | 325 | if qualifier == "BYMONTH": |
paul@1398 | 326 | return [(-12, -1), (1, 12)], |
paul@1398 | 327 | elif qualifier == "BYWEEKNO": |
paul@1398 | 328 | return [(-53, -1), (1, 53)], |
paul@1398 | 329 | elif qualifier == "BYYEARDAY": |
paul@1398 | 330 | return [(-366, -1), (1, 366)], |
paul@1398 | 331 | elif qualifier == "BYMONTHDAY": |
paul@1398 | 332 | return [(-31, -1), (1, 31)], |
paul@1398 | 333 | elif qualifier == "BYHOUR": |
paul@1398 | 334 | return [(0, 23)], |
paul@1398 | 335 | elif qualifier == "BYMINUTE": |
paul@1398 | 336 | return [(0, 59)], |
paul@1398 | 337 | elif qualifier == "BYSECOND": |
paul@1398 | 338 | return [(0, 60)], |
paul@1398 | 339 | |
paul@1398 | 340 | # Provide ranges for the weekday value and index. |
paul@1398 | 341 | |
paul@1398 | 342 | elif qualifier == "BYDAY": |
paul@1398 | 343 | return [weekdays], [(-53, -1), (1, 53), None] |
paul@1398 | 344 | |
paul@1398 | 345 | return None |
paul@1398 | 346 | |
paul@1398 | 347 | def check_values(qualifier, values): |
paul@1398 | 348 | |
paul@1398 | 349 | """ |
paul@1398 | 350 | Check for 'qualifier' the given 'values', returning checked values that may |
paul@1398 | 351 | be converted or updated. |
paul@1398 | 352 | """ |
paul@1398 | 353 | |
paul@1398 | 354 | ranges = get_value_ranges(qualifier) |
paul@1398 | 355 | |
paul@1398 | 356 | if not ranges: |
paul@1398 | 357 | return None |
paul@1398 | 358 | |
paul@1398 | 359 | # Match each value against each range specification. |
paul@1398 | 360 | |
paul@1398 | 361 | checked = [] |
paul@1398 | 362 | |
paul@1398 | 363 | for v, value_ranges in zip(values, ranges): |
paul@1398 | 364 | |
paul@1398 | 365 | # Return None if no match occurred for the value. |
paul@1398 | 366 | |
paul@1398 | 367 | try: |
paul@1398 | 368 | checked.append(check_value_in_ranges(v, value_ranges)) |
paul@1398 | 369 | except ValueError: |
paul@1398 | 370 | return None |
paul@1398 | 371 | |
paul@1398 | 372 | # Return the checked values. |
paul@1398 | 373 | |
paul@1398 | 374 | return checked |
paul@1398 | 375 | |
paul@1398 | 376 | def check_value_in_ranges(value, value_ranges): |
paul@1398 | 377 | |
paul@1398 | 378 | """ |
paul@1398 | 379 | Check the given 'value' against the given 'value_ranges'. Return the |
paul@1398 | 380 | checked value, possibly converted or updated, or raise ValueError if the |
paul@1398 | 381 | value was not suitable. |
paul@1398 | 382 | """ |
paul@1398 | 383 | |
paul@1398 | 384 | for value_range in value_ranges: |
paul@1398 | 385 | |
paul@1398 | 386 | # Test actual ranges. |
paul@1398 | 387 | |
paul@1398 | 388 | if isinstance(value_range, tuple): |
paul@1398 | 389 | start, end = value_range |
paul@1398 | 390 | if start <= value <= end: |
paul@1398 | 391 | return value |
paul@1398 | 392 | |
paul@1398 | 393 | # Test enumerations. |
paul@1398 | 394 | |
paul@1398 | 395 | elif isinstance(value_range, list): |
paul@1398 | 396 | if value in value_range: |
paul@1398 | 397 | return value |
paul@1398 | 398 | |
paul@1398 | 399 | # Test mappings. |
paul@1398 | 400 | |
paul@1398 | 401 | elif isinstance(value_range, dict): |
paul@1398 | 402 | if value_range.has_key(value): |
paul@1398 | 403 | return value_range[value] |
paul@1398 | 404 | |
paul@1398 | 405 | # Test value matches. |
paul@1398 | 406 | |
paul@1398 | 407 | elif value == value_range: |
paul@1398 | 408 | return value |
paul@1398 | 409 | |
paul@1398 | 410 | raise ValueError, value |
paul@33 | 411 | |
paul@33 | 412 | def get_datetime_structure(datetime): |
paul@33 | 413 | |
paul@33 | 414 | "Return the structure of 'datetime' for recurrence production." |
paul@33 | 415 | |
paul@33 | 416 | l = [] |
paul@42 | 417 | offset = 0 |
paul@1237 | 418 | |
paul@1359 | 419 | for pos, value in enumerate(datetime): |
paul@1237 | 420 | |
paul@1237 | 421 | # At the day number, adjust the frequency level offset to reference |
paul@1237 | 422 | # days (and then hours, minutes, seconds). |
paul@1237 | 423 | |
paul@1359 | 424 | if pos == 2: |
paul@44 | 425 | offset = 3 |
paul@1237 | 426 | |
paul@1359 | 427 | l.append(Enum(pos + offset, {"values" : [value]}, "DT")) |
paul@1237 | 428 | |
paul@33 | 429 | return l |
paul@33 | 430 | |
paul@1398 | 431 | def combine_datetime_with_selectors(datetime, selectors): |
paul@33 | 432 | |
paul@33 | 433 | """ |
paul@1398 | 434 | Combine 'datetime' with 'selectors' to produce a structure for recurrence |
paul@33 | 435 | production. |
paul@1241 | 436 | |
paul@1241 | 437 | Initial datetime values appearing at broader resolutions than any qualifiers |
paul@1241 | 438 | are ignored, since their details will be used when materialising the |
paul@1241 | 439 | results. |
paul@1241 | 440 | |
paul@1241 | 441 | Qualifiers are accumulated in order to define a selection. Datetime values |
paul@1241 | 442 | occurring between qualifiers or at the same resolution as qualifiers are |
paul@1241 | 443 | ignored. |
paul@1241 | 444 | |
paul@1241 | 445 | Any remaining datetime values are introduced as enumerators, provided that |
paul@1241 | 446 | they do not conflict with qualifiers. For example, specific day values |
paul@1241 | 447 | conflict with day selectors and weekly qualifiers. |
paul@1241 | 448 | |
paul@1241 | 449 | The purpose of the remaining datetime values is to define a result within |
paul@1241 | 450 | a period selected by the most precise qualifier. For example, the selection |
paul@1241 | 451 | of a day and month in a year recurrence. |
paul@33 | 452 | """ |
paul@33 | 453 | |
paul@33 | 454 | iter_dt = iter(get_datetime_structure(datetime)) |
paul@1398 | 455 | iter_sel = iter(selectors) |
paul@33 | 456 | |
paul@33 | 457 | l = [] |
paul@33 | 458 | |
paul@33 | 459 | from_dt = get_next(iter_dt) |
paul@1398 | 460 | from_sel = get_next(iter_sel) |
paul@1398 | 461 | have_sel = False |
paul@1237 | 462 | |
paul@33 | 463 | # Consume from both lists, merging entries. |
paul@33 | 464 | |
paul@1398 | 465 | while from_dt and from_sel: |
paul@42 | 466 | _level = from_dt.level |
paul@1398 | 467 | level = from_sel.level |
paul@33 | 468 | |
paul@1241 | 469 | # Datetime value at wider resolution. |
paul@33 | 470 | |
paul@42 | 471 | if _level < level: |
paul@39 | 472 | from_dt = get_next(iter_dt) |
paul@33 | 473 | |
paul@33 | 474 | # Qualifier at wider or same resolution as datetime value. |
paul@33 | 475 | |
paul@33 | 476 | else: |
paul@1398 | 477 | if not have_sel: |
paul@1398 | 478 | add_initial_selector(from_sel, level, l) |
paul@1398 | 479 | have_sel = True |
paul@33 | 480 | |
paul@1241 | 481 | # Add the qualifier to the combined list. |
paul@1237 | 482 | |
paul@1398 | 483 | l.append(from_sel) |
paul@1237 | 484 | |
paul@1241 | 485 | # Datetime value at same resolution. |
paul@33 | 486 | |
paul@43 | 487 | if _level == level: |
paul@33 | 488 | from_dt = get_next(iter_dt) |
paul@33 | 489 | |
paul@1237 | 490 | # Get the next qualifier. |
paul@1237 | 491 | |
paul@1398 | 492 | from_sel = get_next(iter_sel) |
paul@1237 | 493 | |
paul@1237 | 494 | # Complete the list by adding remaining datetime enumerators. |
paul@33 | 495 | |
paul@33 | 496 | while from_dt: |
paul@1241 | 497 | |
paul@1241 | 498 | # Ignore datetime values that conflict with day-level qualifiers. |
paul@1241 | 499 | |
paul@1359 | 500 | if not l or from_dt.level != freq["DAILY"] or \ |
paul@1359 | 501 | l[-1].level not in daylevels: |
paul@1359 | 502 | |
paul@1241 | 503 | l.append(from_dt) |
paul@1241 | 504 | |
paul@33 | 505 | from_dt = get_next(iter_dt) |
paul@33 | 506 | |
paul@1237 | 507 | # Complete the list by adding remaining qualifiers. |
paul@1237 | 508 | |
paul@1398 | 509 | while from_sel: |
paul@1398 | 510 | if not have_sel: |
paul@1398 | 511 | add_initial_selector(from_sel, level, l) |
paul@1398 | 512 | have_sel = True |
paul@43 | 513 | |
paul@1241 | 514 | # Add the qualifier to the combined list. |
paul@1237 | 515 | |
paul@1398 | 516 | l.append(from_sel) |
paul@1237 | 517 | |
paul@1237 | 518 | # Get the next qualifier. |
paul@1237 | 519 | |
paul@1398 | 520 | from_sel = get_next(iter_sel) |
paul@33 | 521 | |
paul@33 | 522 | return l |
paul@33 | 523 | |
paul@1398 | 524 | def add_initial_selector(from_sel, level, l): |
paul@1237 | 525 | |
paul@1237 | 526 | """ |
paul@1398 | 527 | Take the first selector 'from_sel' at the given resolution 'level', using it |
paul@1398 | 528 | to create an initial selector, adding it to the combined list 'l' if |
paul@1241 | 529 | required. |
paul@1237 | 530 | """ |
paul@1237 | 531 | |
paul@1398 | 532 | if isinstance(from_sel, Enum) and level > 0: |
paul@1237 | 533 | repeat = Pattern(level - 1, {"interval" : 1}, None) |
paul@1237 | 534 | l.append(repeat) |
paul@1237 | 535 | |
paul@1359 | 536 | def get_multiple(qualifier): |
paul@1359 | 537 | |
paul@1359 | 538 | "Return the time unit multiple for 'qualifier'." |
paul@1359 | 539 | |
paul@1359 | 540 | return multiples.get(qualifier, 1) |
paul@1359 | 541 | |
paul@33 | 542 | # Datetime arithmetic. |
paul@33 | 543 | |
paul@1359 | 544 | def is_year_only(t): |
paul@1359 | 545 | |
paul@1359 | 546 | "Return if 't' describes a year." |
paul@1359 | 547 | |
paul@1359 | 548 | return len(t) == lengths[YEARS] |
paul@1359 | 549 | |
paul@1359 | 550 | def is_month_only(t): |
paul@1359 | 551 | |
paul@1359 | 552 | "Return if 't' describes a month within a year." |
paul@1359 | 553 | |
paul@1359 | 554 | return len(t) == lengths[MONTHS] |
paul@1359 | 555 | |
paul@1359 | 556 | def start_of_year(t): |
paul@1359 | 557 | |
paul@1359 | 558 | "Return the start of the year referenced by 't'." |
paul@1359 | 559 | |
paul@1359 | 560 | return (t[0], 1, 1) |
paul@1359 | 561 | |
paul@1359 | 562 | def end_of_year(t): |
paul@1359 | 563 | |
paul@1359 | 564 | "Return the end of the year referenced by 't'." |
paul@1359 | 565 | |
paul@1359 | 566 | return (t[0], 12, 31) |
paul@1359 | 567 | |
paul@1359 | 568 | def start_of_month(t): |
paul@1359 | 569 | |
paul@1359 | 570 | "Return the start of the month referenced by 't'." |
paul@1359 | 571 | |
paul@1359 | 572 | year, month = t[:2] |
paul@1359 | 573 | return (year, month, 1) |
paul@1359 | 574 | |
paul@1359 | 575 | def end_of_month(t): |
paul@1359 | 576 | |
paul@1359 | 577 | "Return the end of the month referenced by 't'." |
paul@1359 | 578 | |
paul@1359 | 579 | year, month = t[:2] |
paul@1359 | 580 | return update(update((year, month, 1), (0, 1, 0)), (0, 0, -1)) |
paul@1359 | 581 | |
paul@1359 | 582 | def day_in_year(t, number): |
paul@1359 | 583 | |
paul@1359 | 584 | "Return the day in the year referenced by 't' with the given 'number'." |
paul@1359 | 585 | |
paul@1359 | 586 | return to_tuple(date(*start_of_year(t)) + timedelta(number - 1)) |
paul@1359 | 587 | |
paul@1359 | 588 | def get_year_length(t): |
paul@1359 | 589 | |
paul@1359 | 590 | "Return the length of the year referenced by 't'." |
paul@1359 | 591 | |
paul@1359 | 592 | first_day = date(*start_of_year(t)) |
paul@1359 | 593 | last_day = date(*end_of_year(t)) |
paul@1359 | 594 | return (last_day - first_day).days + 1 |
paul@1359 | 595 | |
paul@1359 | 596 | def get_weekday(t): |
paul@1359 | 597 | |
paul@1359 | 598 | "Return the 1-based weekday for the month referenced by 't'." |
paul@1359 | 599 | |
paul@1359 | 600 | year, month = t[:2] |
paul@1359 | 601 | return monthrange(year, month)[0] + 1 |
paul@1359 | 602 | |
paul@1359 | 603 | def get_ordered_weekdays(t): |
paul@322 | 604 | |
paul@322 | 605 | """ |
paul@1359 | 606 | Return the 1-based weekday sequence describing the first week of the month |
paul@1359 | 607 | referenced by 't'. |
paul@322 | 608 | """ |
paul@322 | 609 | |
paul@1359 | 610 | first = get_weekday(t) |
paul@1359 | 611 | return range(first, 8) + range(1, first) |
paul@1359 | 612 | |
paul@1359 | 613 | def get_last_weekday_instance(weekday, first_day, last_day): |
paul@1359 | 614 | |
paul@1359 | 615 | """ |
paul@1359 | 616 | Return the last instance number for 'weekday' within the period from |
paul@1359 | 617 | 'first_day' to 'last_day' inclusive. |
paul@33 | 618 | |
paul@1359 | 619 | Here, 'weekday' is 1-based (starting on Monday), the returned limit is |
paul@1359 | 620 | 1-based. |
paul@1359 | 621 | """ |
paul@1359 | 622 | |
paul@1359 | 623 | weekday0 = get_first_day(first_day, weekday) |
paul@1359 | 624 | days = (date(*last_day) - weekday0).days |
paul@1359 | 625 | return days / 7 + 1 |
paul@1359 | 626 | |
paul@1359 | 627 | def precision(t, level, value=None): |
paul@322 | 628 | |
paul@322 | 629 | """ |
paul@1359 | 630 | Return 't' trimmed in resolution to the indicated resolution 'level', |
paul@1359 | 631 | setting 'value' at the given resolution if indicated. |
paul@322 | 632 | """ |
paul@322 | 633 | |
paul@1359 | 634 | pos = positions[level] |
paul@1359 | 635 | |
paul@1359 | 636 | if value is None: |
paul@1359 | 637 | return t[:pos + 1] |
paul@1359 | 638 | else: |
paul@1359 | 639 | return t[:pos] + (value,) |
paul@1359 | 640 | |
paul@1359 | 641 | def scale(interval, level): |
paul@1359 | 642 | |
paul@1359 | 643 | """ |
paul@1359 | 644 | Scale the given 'interval' value in resolution to the indicated resolution |
paul@1359 | 645 | 'level', returning a tuple with leading zero elements and 'interval' at the |
paul@1359 | 646 | stated position. |
paul@1359 | 647 | """ |
paul@1359 | 648 | |
paul@1359 | 649 | pos = positions[level] |
paul@33 | 650 | return (0,) * pos + (interval,) |
paul@33 | 651 | |
paul@33 | 652 | def get_seconds(t): |
paul@33 | 653 | |
paul@33 | 654 | "Convert the sub-day part of 't' into seconds." |
paul@33 | 655 | |
paul@33 | 656 | t = t + (0,) * (6 - len(t)) |
paul@33 | 657 | return (t[3] * 60 + t[4]) * 60 + t[5] |
paul@33 | 658 | |
paul@33 | 659 | def update(t, step): |
paul@33 | 660 | |
paul@33 | 661 | "Update 't' by 'step' at the resolution of 'step'." |
paul@33 | 662 | |
paul@33 | 663 | i = len(step) |
paul@33 | 664 | |
paul@33 | 665 | # Years only. |
paul@33 | 666 | |
paul@33 | 667 | if i == 1: |
paul@33 | 668 | return (t[0] + step[0],) + tuple(t[1:]) |
paul@33 | 669 | |
paul@33 | 670 | # Years and months. |
paul@33 | 671 | |
paul@33 | 672 | elif i == 2: |
paul@33 | 673 | month = t[1] + step[1] |
paul@33 | 674 | return (t[0] + step[0] + (month - 1) / 12, (month - 1) % 12 + 1) + tuple(t[2:]) |
paul@33 | 675 | |
paul@33 | 676 | # Dates and datetimes. |
paul@33 | 677 | |
paul@33 | 678 | else: |
paul@33 | 679 | updated_for_months = update(t, step[:2]) |
paul@33 | 680 | |
paul@33 | 681 | # Dates only. |
paul@33 | 682 | |
paul@33 | 683 | if i == 3: |
paul@33 | 684 | d = datetime(*updated_for_months) |
paul@33 | 685 | s = timedelta(step[2]) |
paul@33 | 686 | |
paul@33 | 687 | # Datetimes. |
paul@33 | 688 | |
paul@33 | 689 | else: |
paul@33 | 690 | d = datetime(*updated_for_months) |
paul@33 | 691 | s = timedelta(step[2], get_seconds(step)) |
paul@33 | 692 | |
paul@1359 | 693 | return to_tuple(d + s)[:len(t)] |
paul@39 | 694 | |
paul@1359 | 695 | def to_tuple(d): |
paul@322 | 696 | |
paul@1359 | 697 | "Return date or datetime 'd' as a tuple." |
paul@322 | 698 | |
paul@46 | 699 | if not isinstance(d, date): |
paul@46 | 700 | return d |
paul@1359 | 701 | if isinstance(d, datetime): |
paul@1359 | 702 | n = 6 |
paul@1359 | 703 | else: |
paul@1359 | 704 | n = 3 |
paul@39 | 705 | return d.timetuple()[:n] |
paul@39 | 706 | |
paul@39 | 707 | def get_first_day(first_day, weekday): |
paul@322 | 708 | |
paul@1359 | 709 | """ |
paul@1359 | 710 | Return the first occurrence at or after 'first_day' of 'weekday' as a date |
paul@1359 | 711 | instance. |
paul@1359 | 712 | """ |
paul@322 | 713 | |
paul@39 | 714 | first_day = date(*first_day) |
paul@39 | 715 | first_weekday = first_day.isoweekday() |
paul@39 | 716 | if first_weekday > weekday: |
paul@39 | 717 | return first_day + timedelta(7 - first_weekday + weekday) |
paul@39 | 718 | else: |
paul@39 | 719 | return first_day + timedelta(weekday - first_weekday) |
paul@39 | 720 | |
paul@39 | 721 | def get_last_day(last_day, weekday): |
paul@322 | 722 | |
paul@1359 | 723 | """ |
paul@1359 | 724 | Return the last occurrence at or before 'last_day' of 'weekday' as a date |
paul@1359 | 725 | instance. |
paul@1359 | 726 | """ |
paul@322 | 727 | |
paul@39 | 728 | last_day = date(*last_day) |
paul@39 | 729 | last_weekday = last_day.isoweekday() |
paul@39 | 730 | if last_weekday < weekday: |
paul@39 | 731 | return last_day - timedelta(last_weekday + 7 - weekday) |
paul@39 | 732 | else: |
paul@39 | 733 | return last_day - timedelta(last_weekday - weekday) |
paul@33 | 734 | |
paul@1359 | 735 | # Value expansion and sorting. |
paul@1359 | 736 | |
paul@1359 | 737 | def sort_values(values, limit=None): |
paul@1359 | 738 | |
paul@1359 | 739 | """ |
paul@1359 | 740 | Sort the given 'values' using 'limit' to determine the positions of negative |
paul@1359 | 741 | values. |
paul@1359 | 742 | """ |
paul@1359 | 743 | |
paul@1359 | 744 | # Convert negative values to positive values according to the value limit. |
paul@1359 | 745 | |
paul@1359 | 746 | if limit is not None: |
paul@1359 | 747 | l = map(lambda x, limit=limit: x < 0 and x + 1 + limit or x, values) |
paul@1359 | 748 | else: |
paul@1359 | 749 | l = values[:] |
paul@1359 | 750 | |
paul@1359 | 751 | l.sort() |
paul@1359 | 752 | return l |
paul@1359 | 753 | |
paul@1359 | 754 | def compare_weekday_selectors(x, y, weekdays): |
paul@1359 | 755 | |
paul@1359 | 756 | """ |
paul@1359 | 757 | Compare 'x' and 'y' values of the form (weekday number, instance number) |
paul@1359 | 758 | using 'weekdays' to define an ordering of the weekday numbers. |
paul@1359 | 759 | """ |
paul@1359 | 760 | |
paul@1359 | 761 | return cmp((x[1], weekdays.index(x[0])), (y[1], weekdays.index(y[0]))) |
paul@1359 | 762 | |
paul@1359 | 763 | def sort_weekdays(values, first_day, last_day): |
paul@1359 | 764 | |
paul@1359 | 765 | """ |
paul@1359 | 766 | Return a sorted copy of the given 'values', each having the form (weekday |
paul@1398 | 767 | number, instance number), where 'first_day' indicates the start of the |
paul@1398 | 768 | period in which these values apply, and where 'last_day' indicates the end |
paul@1398 | 769 | of the period. |
paul@1359 | 770 | """ |
paul@1359 | 771 | |
paul@1359 | 772 | weekdays = get_ordered_weekdays(first_day) |
paul@1359 | 773 | |
paul@1359 | 774 | # Expand the values to incorporate specific weekday instances. |
paul@1359 | 775 | |
paul@1359 | 776 | l = [] |
paul@1359 | 777 | |
paul@1359 | 778 | for weekday, index in values: |
paul@1359 | 779 | |
paul@1359 | 780 | # Obtain the last instance number of the weekday in the period. |
paul@1359 | 781 | |
paul@1359 | 782 | limit = get_last_weekday_instance(weekday, first_day, last_day) |
paul@1359 | 783 | |
paul@1359 | 784 | # For specific instances, convert negative selections. |
paul@1359 | 785 | |
paul@1359 | 786 | if index is not None: |
paul@1359 | 787 | l.append((weekday, index < 0 and index + 1 + limit or index)) |
paul@1359 | 788 | |
paul@1359 | 789 | # For None, introduce selections for all instances of the weekday. |
paul@1359 | 790 | |
paul@1359 | 791 | else: |
paul@1359 | 792 | index = 1 |
paul@1359 | 793 | while index <= limit: |
paul@1359 | 794 | l.append((weekday, index)) |
paul@1359 | 795 | index += 1 |
paul@1359 | 796 | |
paul@1359 | 797 | # Sort the values so that the resulting dates are ordered. |
paul@1359 | 798 | |
paul@1359 | 799 | fn = lambda x, y, weekdays=weekdays: compare_weekday_selectors(x, y, weekdays) |
paul@1359 | 800 | l.sort(cmp=fn) |
paul@1359 | 801 | return l |
paul@1359 | 802 | |
paul@1360 | 803 | def convert_positions(setpos): |
paul@1360 | 804 | |
paul@1360 | 805 | "Convert 'setpos' to 0-based indexes." |
paul@1360 | 806 | |
paul@1360 | 807 | l = [] |
paul@1361 | 808 | if setpos: |
paul@1361 | 809 | for pos in setpos: |
paul@1361 | 810 | index = pos < 0 and pos or pos - 1 |
paul@1361 | 811 | l.append(index) |
paul@1360 | 812 | return l |
paul@1360 | 813 | |
paul@33 | 814 | # Classes for producing instances from recurrence structures. |
paul@33 | 815 | |
paul@33 | 816 | class Selector: |
paul@358 | 817 | |
paul@358 | 818 | "A generic selector." |
paul@358 | 819 | |
paul@1241 | 820 | def __init__(self, level, args, qualifier, selecting=None, first=False): |
paul@358 | 821 | |
paul@358 | 822 | """ |
paul@358 | 823 | Initialise at the given 'level' a selector employing the given 'args' |
paul@358 | 824 | defined in the interpretation of recurrence rule qualifiers, with the |
paul@358 | 825 | 'qualifier' being the name of the rule qualifier, and 'selecting' being |
paul@358 | 826 | an optional selector used to find more specific instances from those |
paul@358 | 827 | found by this selector. |
paul@358 | 828 | """ |
paul@358 | 829 | |
paul@42 | 830 | self.level = level |
paul@1398 | 831 | self.args = args or {} |
paul@33 | 832 | self.qualifier = qualifier |
paul@1237 | 833 | self.selecting = selecting |
paul@1241 | 834 | self.first = first |
paul@1237 | 835 | |
paul@33 | 836 | def __repr__(self): |
paul@1359 | 837 | return "%s(%r, %r, %r, %r)" % (self.__class__.__name__, self.level, |
paul@1359 | 838 | self.args, self.qualifier, self.first) |
paul@33 | 839 | |
paul@1364 | 840 | def select(self, start, end, inclusive=False): |
paul@358 | 841 | |
paul@358 | 842 | """ |
paul@1364 | 843 | Return an iterator over instances starting at 'start' and continuing up |
paul@1364 | 844 | to but not including any at 'end' or later. |
paul@359 | 845 | |
paul@359 | 846 | If 'inclusive' is specified, the selection of instances will include the |
paul@359 | 847 | end of the search period if present in the results. |
paul@358 | 848 | """ |
paul@358 | 849 | |
paul@46 | 850 | start = to_tuple(start) |
paul@46 | 851 | end = to_tuple(end) |
paul@1364 | 852 | return self.materialise_items(start, start, end, inclusive) |
paul@1364 | 853 | |
paul@1364 | 854 | def materialise(self, start, end, inclusive=False): |
paul@1364 | 855 | |
paul@1364 | 856 | """ |
paul@1364 | 857 | Starting at 'start', materialise instances up to but not including any |
paul@1364 | 858 | at 'end' or later. A list of instances is returned. |
paul@1364 | 859 | |
paul@1364 | 860 | If 'inclusive' is specified, the selection of instances will include the |
paul@1364 | 861 | end of the search period if present in the results. |
paul@1364 | 862 | """ |
paul@1364 | 863 | |
paul@1364 | 864 | return list(self.select(start, end, inclusive)) |
paul@33 | 865 | |
paul@1398 | 866 | def set_values(self, values): |
paul@1398 | 867 | self.args["values"] = values |
paul@1398 | 868 | |
paul@33 | 869 | class Pattern(Selector): |
paul@358 | 870 | |
paul@1237 | 871 | "A selector of time periods according to a repeating pattern." |
paul@358 | 872 | |
paul@1361 | 873 | def __init__(self, level, args, qualifier, selecting=None, first=False): |
paul@1361 | 874 | Selector.__init__(self, level, args, qualifier, selecting, first) |
paul@1361 | 875 | |
paul@1361 | 876 | multiple = get_multiple(self.qualifier) |
paul@1398 | 877 | interval = self.get_interval() |
paul@1361 | 878 | |
paul@1361 | 879 | # Define the step between result periods. |
paul@1361 | 880 | |
paul@1361 | 881 | self.step = scale(interval * multiple, level) |
paul@1361 | 882 | |
paul@1361 | 883 | # Define the scale of a single period. |
paul@1361 | 884 | |
paul@1361 | 885 | self.unit_step = scale(multiple, level) |
paul@1361 | 886 | |
paul@1361 | 887 | def materialise_items(self, context, start, end, inclusive=False): |
paul@1237 | 888 | |
paul@1237 | 889 | """ |
paul@1361 | 890 | Bounded by the given 'context', return periods within 'start' to 'end'. |
paul@1237 | 891 | |
paul@1237 | 892 | If 'inclusive' is specified, the selection of periods will include those |
paul@1237 | 893 | starting at the end of the search period, if present in the results. |
paul@1237 | 894 | """ |
paul@1237 | 895 | |
paul@1241 | 896 | # Employ the context as the current period if this is the first |
paul@1241 | 897 | # qualifier in the selection chain. |
paul@1241 | 898 | |
paul@1241 | 899 | if self.first: |
paul@1359 | 900 | current = precision(context, self.level) |
paul@1237 | 901 | |
paul@1241 | 902 | # Otherwise, obtain the first value at this resolution within the |
paul@1241 | 903 | # context period. |
paul@1241 | 904 | |
paul@1241 | 905 | else: |
paul@1359 | 906 | current = precision(context, self.level, firstvalues[self.level]) |
paul@1241 | 907 | |
paul@1361 | 908 | return PatternIterator(self, current, start, end, inclusive, |
paul@1361 | 909 | self.step, self.unit_step) |
paul@33 | 910 | |
paul@1398 | 911 | def get_interval(self): |
paul@1398 | 912 | return self.args.get("interval", 1) |
paul@1398 | 913 | |
paul@1398 | 914 | def set_interval(self, interval): |
paul@1398 | 915 | self.args["interval"] = interval |
paul@1398 | 916 | |
paul@35 | 917 | class WeekDayFilter(Selector): |
paul@358 | 918 | |
paul@358 | 919 | "A selector of instances specified in terms of day numbers." |
paul@358 | 920 | |
paul@1361 | 921 | def __init__(self, level, args, qualifier, selecting=None, first=False): |
paul@1361 | 922 | Selector.__init__(self, level, args, qualifier, selecting, first) |
paul@1361 | 923 | self.step = scale(1, WEEKS) |
paul@1361 | 924 | |
paul@1361 | 925 | def materialise_items(self, context, start, end, inclusive=False): |
paul@34 | 926 | |
paul@39 | 927 | # Get weekdays in the year. |
paul@39 | 928 | |
paul@1359 | 929 | if is_year_only(context): |
paul@1359 | 930 | first_day = start_of_year(context) |
paul@1359 | 931 | last_day = end_of_year(context) |
paul@39 | 932 | |
paul@39 | 933 | # Get weekdays in the month. |
paul@39 | 934 | |
paul@1359 | 935 | elif is_month_only(context): |
paul@1359 | 936 | first_day = start_of_month(context) |
paul@1359 | 937 | last_day = end_of_month(context) |
paul@39 | 938 | |
paul@39 | 939 | # Get weekdays in the week. |
paul@39 | 940 | |
paul@39 | 941 | else: |
paul@39 | 942 | current = context |
paul@1398 | 943 | return WeekDayIterator(self, current, start, end, inclusive, self.step, |
paul@1398 | 944 | self.get_weekdays()) |
paul@39 | 945 | |
paul@1361 | 946 | current = first_day |
paul@1361 | 947 | values = sort_weekdays(self.args["values"], first_day, last_day) |
paul@1398 | 948 | return WeekDayGeneralIterator(self, current, start, end, inclusive, |
paul@1398 | 949 | self.step, values) |
paul@1398 | 950 | |
paul@1398 | 951 | def get_values(self): |
paul@1398 | 952 | |
paul@1398 | 953 | """ |
paul@1398 | 954 | Return a sequence of (value, index) tuples selecting weekdays in the |
paul@1398 | 955 | applicable period. Each value is a 1-based index representing a weekday. |
paul@1398 | 956 | """ |
paul@1398 | 957 | |
paul@1398 | 958 | return self.args["values"] |
paul@1398 | 959 | |
paul@1398 | 960 | def get_weekdays(self): |
paul@1398 | 961 | |
paul@1398 | 962 | "Return only the 1-based weekday indexes." |
paul@1398 | 963 | |
paul@1398 | 964 | values = [] |
paul@1398 | 965 | for value, index in self.args["values"]: |
paul@1398 | 966 | values.append(value) |
paul@1398 | 967 | return values |
paul@1359 | 968 | |
paul@1359 | 969 | class Enum(Selector): |
paul@1359 | 970 | |
paul@1359 | 971 | "A generic value selector." |
paul@1359 | 972 | |
paul@1361 | 973 | def __init__(self, level, args, qualifier, selecting=None, first=False): |
paul@1361 | 974 | Selector.__init__(self, level, args, qualifier, selecting, first) |
paul@1361 | 975 | self.step = scale(1, level) |
paul@45 | 976 | |
paul@1361 | 977 | def materialise_items(self, context, start, end, inclusive=False): |
paul@1398 | 978 | return EnumIterator(self, context, start, end, inclusive, self.step, |
paul@1398 | 979 | self.get_values()) |
paul@1398 | 980 | |
paul@1398 | 981 | def get_values(self, limit=None): |
paul@1398 | 982 | return sort_values(self.args["values"], limit) |
paul@33 | 983 | |
paul@1359 | 984 | class MonthDayFilter(Enum): |
paul@1359 | 985 | |
paul@1359 | 986 | "A selector of month days." |
paul@1359 | 987 | |
paul@1361 | 988 | def materialise_items(self, context, start, end, inclusive=False): |
paul@1359 | 989 | last_day = end_of_month(context)[2] |
paul@1398 | 990 | return EnumIterator(self, context, start, end, inclusive, self.step, |
paul@1398 | 991 | self.get_values(last_day)) |
paul@35 | 992 | |
paul@1359 | 993 | class YearDayFilter(Enum): |
paul@1359 | 994 | |
paul@1359 | 995 | "A selector of days in years." |
paul@1359 | 996 | |
paul@1361 | 997 | def materialise_items(self, context, start, end, inclusive=False): |
paul@1361 | 998 | first_day = start_of_year(context) |
paul@1359 | 999 | year_length = get_year_length(context) |
paul@1398 | 1000 | return YearDayFilterIterator(self, first_day, start, end, inclusive, self.step, |
paul@1398 | 1001 | self.get_values(year_length)) |
paul@46 | 1002 | |
paul@1361 | 1003 | class LimitSelector(Selector): |
paul@1361 | 1004 | |
paul@1361 | 1005 | "A result set limit selector." |
paul@1361 | 1006 | |
paul@1361 | 1007 | def materialise_items(self, context, start, end, inclusive=False): |
paul@1398 | 1008 | return LimitIterator(self, context, start, end, inclusive, self.get_limit()) |
paul@1398 | 1009 | |
paul@1398 | 1010 | def get_limit(self): |
paul@1398 | 1011 | return self.args["values"][0] |
paul@1398 | 1012 | |
paul@1398 | 1013 | def set_limit(self, limit): |
paul@1398 | 1014 | self.args["values"] = [limit] |
paul@1361 | 1015 | |
paul@1361 | 1016 | class PositionSelector(Selector): |
paul@1359 | 1017 | |
paul@1361 | 1018 | "A result set position selector." |
paul@1361 | 1019 | |
paul@1361 | 1020 | def __init__(self, level, args, qualifier, selecting=None, first=False): |
paul@1361 | 1021 | Selector.__init__(self, level, args, qualifier, selecting, first) |
paul@1361 | 1022 | self.step = scale(1, level) |
paul@1361 | 1023 | |
paul@1361 | 1024 | def materialise_items(self, context, start, end, inclusive=False): |
paul@1398 | 1025 | return PositionIterator(self, context, start, end, inclusive, self.step, |
paul@1398 | 1026 | self.get_positions()) |
paul@1398 | 1027 | |
paul@1398 | 1028 | def get_positions(self): |
paul@1398 | 1029 | return convert_positions(sort_values(self.args["values"])) |
paul@1398 | 1030 | |
paul@1398 | 1031 | def set_positions(self, positions): |
paul@1398 | 1032 | self.args["values"] = positions |
paul@1398 | 1033 | |
paul@1398 | 1034 | special_enum_levels = { |
paul@1398 | 1035 | "BYDAY" : WeekDayFilter, |
paul@1398 | 1036 | "BYMONTHDAY" : MonthDayFilter, |
paul@1398 | 1037 | "BYYEARDAY" : YearDayFilter, |
paul@1398 | 1038 | } |
paul@1361 | 1039 | |
paul@1361 | 1040 | # Iterator classes. |
paul@1359 | 1041 | |
paul@1361 | 1042 | class SelectorIterator: |
paul@1361 | 1043 | |
paul@1361 | 1044 | "An iterator over selected data." |
paul@1361 | 1045 | |
paul@1361 | 1046 | def __init__(self, selector, current, start, end, inclusive): |
paul@1361 | 1047 | |
paul@1361 | 1048 | """ |
paul@1361 | 1049 | Define an iterator having the 'current' point in time, 'start' and 'end' |
paul@1361 | 1050 | limits, and whether the selection is 'inclusive'. |
paul@1361 | 1051 | """ |
paul@1359 | 1052 | |
paul@1361 | 1053 | self.selector = selector |
paul@1361 | 1054 | self.current = current |
paul@1361 | 1055 | self.start = start |
paul@1361 | 1056 | self.end = end |
paul@1361 | 1057 | self.inclusive = inclusive |
paul@1361 | 1058 | |
paul@1361 | 1059 | # Iterator over selections within this selection. |
paul@1361 | 1060 | |
paul@1361 | 1061 | self.iterator = None |
paul@1361 | 1062 | |
paul@1361 | 1063 | def __iter__(self): |
paul@1359 | 1064 | return self |
paul@1359 | 1065 | |
paul@1361 | 1066 | def next_item(self, earliest, next): |
paul@1361 | 1067 | |
paul@1361 | 1068 | """ |
paul@1361 | 1069 | Given the 'earliest' acceptable instance and the 'next' instance, return |
paul@1361 | 1070 | a list of result items. |
paul@1361 | 1071 | |
paul@1361 | 1072 | Where no selection within the current instance occurs, the current |
paul@1361 | 1073 | instance will be returned as a result if the same or later than the |
paul@1361 | 1074 | earliest acceptable instance. |
paul@1361 | 1075 | """ |
paul@1361 | 1076 | |
paul@1361 | 1077 | # Obtain an item from a selector operating within this selection. |
paul@1361 | 1078 | |
paul@1361 | 1079 | selecting = self.selector.selecting |
paul@1361 | 1080 | |
paul@1361 | 1081 | if selecting: |
paul@1361 | 1082 | |
paul@1361 | 1083 | # Obtain an iterator for any selector within the current period. |
paul@1361 | 1084 | |
paul@1361 | 1085 | if not self.iterator: |
paul@1361 | 1086 | self.iterator = selecting.materialise_items(self.current, |
paul@1361 | 1087 | earliest, next, self.inclusive) |
paul@1361 | 1088 | |
paul@1361 | 1089 | # Attempt to obtain and return a value. |
paul@1361 | 1090 | |
paul@1361 | 1091 | return self.iterator.next() |
paul@1361 | 1092 | |
paul@1361 | 1093 | # Return items within this selection. |
paul@1361 | 1094 | |
paul@1361 | 1095 | else: |
paul@1361 | 1096 | return self.current |
paul@1361 | 1097 | |
paul@1361 | 1098 | def filter_by_period(self, result): |
paul@1361 | 1099 | |
paul@1361 | 1100 | "Return whether 'result' occurs within the selection period." |
paul@1361 | 1101 | |
paul@1361 | 1102 | return (self.inclusive and result <= self.end or result < self.end) and \ |
paul@1361 | 1103 | self.start <= result |
paul@1361 | 1104 | |
paul@1359 | 1105 | def at_limit(self): |
paul@1361 | 1106 | |
paul@1361 | 1107 | "Obtain periods before the end (and also at the end if inclusive)." |
paul@1361 | 1108 | |
paul@1361 | 1109 | return not self.inclusive and self.current == self.end or \ |
paul@1361 | 1110 | self.current > self.end |
paul@1361 | 1111 | |
paul@1361 | 1112 | class PatternIterator(SelectorIterator): |
paul@1361 | 1113 | |
paul@1361 | 1114 | "An iterator for a general selection pattern." |
paul@1361 | 1115 | |
paul@1361 | 1116 | def __init__(self, selector, current, start, end, inclusive, step, unit_step): |
paul@1361 | 1117 | SelectorIterator.__init__(self, selector, current, start, end, inclusive) |
paul@1361 | 1118 | self.step = step |
paul@1361 | 1119 | self.unit_step = unit_step |
paul@1361 | 1120 | |
paul@1361 | 1121 | def next(self): |
paul@1361 | 1122 | |
paul@1361 | 1123 | "Return the next value." |
paul@1361 | 1124 | |
paul@1361 | 1125 | while not self.at_limit(): |
paul@1361 | 1126 | |
paul@1361 | 1127 | # Increment the current datetime by the step for the next period. |
paul@1361 | 1128 | |
paul@1361 | 1129 | next = update(self.current, self.step) |
paul@1361 | 1130 | |
paul@1361 | 1131 | # Determine the end point of the current period. |
paul@1361 | 1132 | |
paul@1361 | 1133 | current_end = update(self.current, self.unit_step) |
paul@1361 | 1134 | |
paul@1361 | 1135 | # Obtain any period or periods within the bounds defined by the |
paul@1361 | 1136 | # current period and any contraining start and end points. |
paul@1361 | 1137 | |
paul@1361 | 1138 | try: |
paul@1361 | 1139 | result = self.next_item(max(self.current, self.start), |
paul@1361 | 1140 | min(current_end, self.end)) |
paul@1361 | 1141 | |
paul@1361 | 1142 | # Obtain the next period if not selecting within this period. |
paul@1361 | 1143 | |
paul@1361 | 1144 | if not self.selector.selecting: |
paul@1361 | 1145 | self.current = next |
paul@1361 | 1146 | |
paul@1361 | 1147 | # Filter out periods. |
paul@1361 | 1148 | |
paul@1361 | 1149 | if self.filter_by_period(result): |
paul@1361 | 1150 | return result |
paul@1361 | 1151 | |
paul@1361 | 1152 | # Move on to the next instance. |
paul@1361 | 1153 | |
paul@1361 | 1154 | except StopIteration: |
paul@1361 | 1155 | self.current = next |
paul@1361 | 1156 | self.iterator = None |
paul@1361 | 1157 | |
paul@1361 | 1158 | raise StopIteration |
paul@1361 | 1159 | |
paul@1361 | 1160 | class WeekDayIterator(SelectorIterator): |
paul@1361 | 1161 | |
paul@1361 | 1162 | "An iterator over weekday selections in week periods." |
paul@1361 | 1163 | |
paul@1361 | 1164 | def __init__(self, selector, current, start, end, inclusive, step, values): |
paul@1361 | 1165 | SelectorIterator.__init__(self, selector, current, start, end, inclusive) |
paul@1361 | 1166 | self.step = step |
paul@1361 | 1167 | self.values = values |
paul@1361 | 1168 | |
paul@1361 | 1169 | def next(self): |
paul@1361 | 1170 | |
paul@1361 | 1171 | "Return the next value." |
paul@1361 | 1172 | |
paul@1361 | 1173 | while not self.at_limit(): |
paul@1361 | 1174 | |
paul@1361 | 1175 | # Increment the current datetime by the step for the next period. |
paul@1361 | 1176 | |
paul@1361 | 1177 | next = update(self.current, self.step) |
paul@1361 | 1178 | |
paul@1361 | 1179 | # Determine whether the day is one chosen. |
paul@1361 | 1180 | |
paul@1361 | 1181 | if date(*self.current).isoweekday() in self.values: |
paul@1361 | 1182 | try: |
paul@1361 | 1183 | result = self.next_item(max(self.current, self.start), |
paul@1361 | 1184 | min(next, self.end)) |
paul@1361 | 1185 | |
paul@1361 | 1186 | # Obtain the next period if not selecting within this period. |
paul@1361 | 1187 | |
paul@1361 | 1188 | if not self.selector.selecting: |
paul@1361 | 1189 | self.current = next |
paul@1361 | 1190 | |
paul@1361 | 1191 | return result |
paul@1361 | 1192 | |
paul@1361 | 1193 | # Move on to the next instance. |
paul@1361 | 1194 | |
paul@1361 | 1195 | except StopIteration: |
paul@1361 | 1196 | self.current = next |
paul@1361 | 1197 | self.iterator = None |
paul@1361 | 1198 | |
paul@1361 | 1199 | else: |
paul@1361 | 1200 | self.current = next |
paul@1361 | 1201 | self.iterator = None |
paul@1361 | 1202 | |
paul@1361 | 1203 | raise StopIteration |
paul@1361 | 1204 | |
paul@1361 | 1205 | class EnumIterator(SelectorIterator): |
paul@1361 | 1206 | |
paul@1361 | 1207 | "An iterator over specific value selections." |
paul@1361 | 1208 | |
paul@1361 | 1209 | def __init__(self, selector, current, start, end, inclusive, step, values): |
paul@1361 | 1210 | SelectorIterator.__init__(self, selector, current, start, end, inclusive) |
paul@1361 | 1211 | self.step = step |
paul@1361 | 1212 | |
paul@1361 | 1213 | # Derive selected periods from a base and the indicated values. |
paul@1361 | 1214 | |
paul@1361 | 1215 | self.base = current |
paul@1361 | 1216 | |
paul@1361 | 1217 | # Iterate over the indicated period values. |
paul@1361 | 1218 | |
paul@1361 | 1219 | self.values = iter(values) |
paul@1361 | 1220 | self.value = None |
paul@1361 | 1221 | |
paul@1361 | 1222 | def get_selected_period(self): |
paul@1361 | 1223 | |
paul@1361 | 1224 | "Return the period indicated by the current value." |
paul@1361 | 1225 | |
paul@1361 | 1226 | return precision(self.base, self.selector.level, self.value) |
paul@1361 | 1227 | |
paul@1361 | 1228 | def next(self): |
paul@1361 | 1229 | |
paul@1361 | 1230 | "Return the next value." |
paul@1361 | 1231 | |
paul@1361 | 1232 | while True: |
paul@1361 | 1233 | |
paul@1361 | 1234 | # Find each of the given selected values. |
paul@1361 | 1235 | |
paul@1361 | 1236 | if not self.selector.selecting or self.value is None: |
paul@1361 | 1237 | self.value = self.values.next() |
paul@1361 | 1238 | |
paul@1361 | 1239 | # Select a period for each value at the current resolution. |
paul@1361 | 1240 | |
paul@1361 | 1241 | self.current = self.get_selected_period() |
paul@1361 | 1242 | next = update(self.current, self.step) |
paul@1361 | 1243 | |
paul@1361 | 1244 | # To support setpos, only current and next bound the search, not |
paul@1361 | 1245 | # the period in addition. |
paul@1361 | 1246 | |
paul@1361 | 1247 | try: |
paul@1361 | 1248 | return self.next_item(self.current, next) |
paul@1361 | 1249 | |
paul@1361 | 1250 | # Move on to the next instance. |
paul@1361 | 1251 | |
paul@1361 | 1252 | except StopIteration: |
paul@1361 | 1253 | self.value = None |
paul@1361 | 1254 | self.iterator = None |
paul@1361 | 1255 | |
paul@1361 | 1256 | raise StopIteration |
paul@1361 | 1257 | |
paul@1361 | 1258 | class WeekDayGeneralIterator(EnumIterator): |
paul@1361 | 1259 | |
paul@1361 | 1260 | "An iterator over weekday selections in month and year periods." |
paul@1361 | 1261 | |
paul@1361 | 1262 | def get_selected_period(self): |
paul@1361 | 1263 | |
paul@1361 | 1264 | "Return the day indicated by the current day value." |
paul@1361 | 1265 | |
paul@1361 | 1266 | value, index = self.value |
paul@1361 | 1267 | offset = timedelta(7 * (index - 1)) |
paul@1361 | 1268 | weekday0 = get_first_day(self.base, value) |
paul@1361 | 1269 | return precision(to_tuple(weekday0 + offset), DAYS) |
paul@1361 | 1270 | |
paul@1361 | 1271 | class YearDayFilterIterator(EnumIterator): |
paul@1361 | 1272 | |
paul@1361 | 1273 | "An iterator over day-in-year selections." |
paul@1361 | 1274 | |
paul@1361 | 1275 | def get_selected_period(self): |
paul@1361 | 1276 | |
paul@1361 | 1277 | "Return the day indicated by the current day value." |
paul@1361 | 1278 | |
paul@1361 | 1279 | offset = timedelta(self.value - 1) |
paul@1361 | 1280 | return precision(to_tuple(date(*self.base) + offset), DAYS) |
paul@1361 | 1281 | |
paul@1361 | 1282 | class LimitIterator(SelectorIterator): |
paul@1361 | 1283 | |
paul@1361 | 1284 | "A result set limiting iterator." |
paul@1361 | 1285 | |
paul@1361 | 1286 | def __init__(self, selector, context, start, end, inclusive, limit): |
paul@1361 | 1287 | SelectorIterator.__init__(self, selector, context, start, end, inclusive) |
paul@1361 | 1288 | self.limit = limit |
paul@1361 | 1289 | self.count = 0 |
paul@1361 | 1290 | |
paul@1361 | 1291 | def next(self): |
paul@1361 | 1292 | |
paul@1361 | 1293 | "Return the next value." |
paul@1361 | 1294 | |
paul@1361 | 1295 | if self.count < self.limit: |
paul@1361 | 1296 | self.count += 1 |
paul@1361 | 1297 | result = self.next_item(self.start, self.end) |
paul@1361 | 1298 | return result |
paul@1361 | 1299 | |
paul@1361 | 1300 | raise StopIteration |
paul@1361 | 1301 | |
paul@1361 | 1302 | class PositionIterator(SelectorIterator): |
paul@1361 | 1303 | |
paul@1361 | 1304 | "An iterator over results, selecting positions." |
paul@1361 | 1305 | |
paul@1361 | 1306 | def __init__(self, selector, context, start, end, inclusive, step, positions): |
paul@1361 | 1307 | SelectorIterator.__init__(self, selector, context, start, end, inclusive) |
paul@1361 | 1308 | self.step = step |
paul@1361 | 1309 | |
paul@1361 | 1310 | # Positions to select. |
paul@1361 | 1311 | |
paul@1361 | 1312 | self.positions = positions |
paul@1361 | 1313 | |
paul@1361 | 1314 | # Queue to hold values matching the negative position values. |
paul@1361 | 1315 | |
paul@1361 | 1316 | self.queue_length = positions and positions[0] < 0 and abs(positions[0]) or 0 |
paul@1361 | 1317 | self.queue = [] |
paul@1361 | 1318 | |
paul@1361 | 1319 | # Result position. |
paul@1361 | 1320 | |
paul@1361 | 1321 | self.resultpos = 0 |
paul@1361 | 1322 | |
paul@1361 | 1323 | def next(self): |
paul@1361 | 1324 | |
paul@1361 | 1325 | "Return the next value." |
paul@1361 | 1326 | |
paul@1361 | 1327 | while True: |
paul@1361 | 1328 | try: |
paul@1361 | 1329 | result = self.next_item(self.start, self.end) |
paul@1361 | 1330 | |
paul@1361 | 1331 | # Positive positions can have their values released immediately. |
paul@1361 | 1332 | |
paul@1361 | 1333 | selected = self.resultpos in self.positions |
paul@1361 | 1334 | self.resultpos += 1 |
paul@1361 | 1335 | |
paul@1361 | 1336 | if selected: |
paul@1361 | 1337 | return result |
paul@1361 | 1338 | |
paul@1361 | 1339 | # Negative positions must be held until this iterator completes and |
paul@1361 | 1340 | # then be released. |
paul@1361 | 1341 | |
paul@1361 | 1342 | if self.queue_length: |
paul@1361 | 1343 | self.queue.append(result) |
paul@1361 | 1344 | if len(self.queue) > self.queue_length: |
paul@1361 | 1345 | del self.queue[0] |
paul@1361 | 1346 | |
paul@1361 | 1347 | except StopIteration: |
paul@1361 | 1348 | |
paul@1361 | 1349 | # With a queue and positions, attempt to find the referenced |
paul@1361 | 1350 | # positions. |
paul@1361 | 1351 | |
paul@1361 | 1352 | if self.queue and self.positions: |
paul@1361 | 1353 | index = self.positions[0] |
paul@1361 | 1354 | del self.positions[0] |
paul@1361 | 1355 | |
paul@1361 | 1356 | # Only negative positions are used at this point. |
paul@1361 | 1357 | |
paul@1361 | 1358 | if index < 0: |
paul@1361 | 1359 | try: |
paul@1361 | 1360 | return self.queue[index] |
paul@1361 | 1361 | except IndexError: |
paul@1361 | 1362 | pass |
paul@1361 | 1363 | |
paul@1361 | 1364 | # With only positive positions remaining, signal the end of |
paul@1361 | 1365 | # the collection. |
paul@1361 | 1366 | |
paul@1361 | 1367 | else: |
paul@1361 | 1368 | raise |
paul@1361 | 1369 | |
paul@1361 | 1370 | # With no queue or positions remaining, signal the end of the |
paul@1361 | 1371 | # collection. |
paul@1361 | 1372 | |
paul@1361 | 1373 | else: |
paul@1361 | 1374 | raise |
paul@1359 | 1375 | |
paul@46 | 1376 | def connect_selectors(selectors): |
paul@358 | 1377 | |
paul@358 | 1378 | """ |
paul@358 | 1379 | Make the 'selectors' reference each other in a hierarchy so that |
paul@358 | 1380 | materialising the principal selector causes the more specific ones to be |
paul@358 | 1381 | employed in the operation. |
paul@358 | 1382 | """ |
paul@358 | 1383 | |
paul@33 | 1384 | current = selectors[0] |
paul@1361 | 1385 | current.first = first = True |
paul@1361 | 1386 | |
paul@33 | 1387 | for selector in selectors[1:]: |
paul@33 | 1388 | current.selecting = selector |
paul@1361 | 1389 | |
paul@1361 | 1390 | # Allow selectors within the limit selector to act as if they are first |
paul@1361 | 1391 | # in the chain and will operate using the supplied datetime context. |
paul@1361 | 1392 | |
paul@1361 | 1393 | first = isinstance(current, LimitSelector) |
paul@1361 | 1394 | |
paul@33 | 1395 | current = selector |
paul@1361 | 1396 | current.first = first |
paul@1361 | 1397 | |
paul@33 | 1398 | return selectors[0] |
paul@33 | 1399 | |
paul@1398 | 1400 | # Public functions. |
paul@46 | 1401 | |
paul@46 | 1402 | def get_rule(dt, rule): |
paul@317 | 1403 | |
paul@317 | 1404 | """ |
paul@317 | 1405 | Using the given initial datetime 'dt', interpret the 'rule' (a semicolon- |
paul@317 | 1406 | separated collection of "key=value" strings), and return the resulting |
paul@317 | 1407 | selector object. |
paul@317 | 1408 | """ |
paul@317 | 1409 | |
paul@1398 | 1410 | selectors = get_selectors_for_rule(rule) |
paul@1398 | 1411 | return get_selector(dt, selectors) |
paul@1398 | 1412 | |
paul@1398 | 1413 | def get_selector(dt, selectors): |
paul@1398 | 1414 | |
paul@1398 | 1415 | """ |
paul@1398 | 1416 | Combine the initial datetime 'dt' with the given 'selectors', returning an |
paul@1398 | 1417 | object that can be used to select recurrences described by the 'selectors'. |
paul@1398 | 1418 | """ |
paul@1398 | 1419 | |
paul@1398 | 1420 | dt = to_tuple(dt) |
paul@1398 | 1421 | return connect_selectors(combine_datetime_with_selectors(dt, selectors)) |
paul@1398 | 1422 | |
paul@1398 | 1423 | def get_selectors_for_rule(rule): |
paul@1398 | 1424 | |
paul@1398 | 1425 | """ |
paul@1398 | 1426 | Return a list of selectors implementing 'rule', useful for "explaining" how |
paul@1398 | 1427 | a rule works. |
paul@1398 | 1428 | """ |
paul@1398 | 1429 | |
paul@351 | 1430 | if not isinstance(rule, tuple): |
paul@1398 | 1431 | rule = (rule or "").split(";") |
paul@1398 | 1432 | return order_qualifiers(get_qualifiers(rule)) |
paul@35 | 1433 | |
paul@33 | 1434 | # vim: tabstop=4 expandtab shiftwidth=4 |