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