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