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