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