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