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