python-dateutil 2.4.1__zip

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1375 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ The rrule module offers a small, complete, and very fast, implementation of
4
+ the recurrence rules documented in the
5
+ `iCalendar RFC <http://www.ietf.org/rfc/rfc2445.txt>`_,
6
+ including support for caching of results.
7
+ """
8
+ import itertools
9
+ import datetime
10
+ import calendar
11
+ import sys
12
+
13
+ from fractions import gcd
14
+
15
+ from six import advance_iterator, integer_types
16
+ from six.moves import _thread
17
+
18
+ __all__ = ["rrule", "rruleset", "rrulestr",
19
+ "YEARLY", "MONTHLY", "WEEKLY", "DAILY",
20
+ "HOURLY", "MINUTELY", "SECONDLY",
21
+ "MO", "TU", "WE", "TH", "FR", "SA", "SU"]
22
+
23
+ # Every mask is 7 days longer to handle cross-year weekly periods.
24
+ M366MASK = tuple([1]*31+[2]*29+[3]*31+[4]*30+[5]*31+[6]*30 +
25
+ [7]*31+[8]*31+[9]*30+[10]*31+[11]*30+[12]*31+[1]*7)
26
+ M365MASK = list(M366MASK)
27
+ M29, M30, M31 = list(range(1, 30)), list(range(1, 31)), list(range(1, 32))
28
+ MDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7])
29
+ MDAY365MASK = list(MDAY366MASK)
30
+ M29, M30, M31 = list(range(-29, 0)), list(range(-30, 0)), list(range(-31, 0))
31
+ NMDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7])
32
+ NMDAY365MASK = list(NMDAY366MASK)
33
+ M366RANGE = (0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366)
34
+ M365RANGE = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365)
35
+ WDAYMASK = [0, 1, 2, 3, 4, 5, 6]*55
36
+ del M29, M30, M31, M365MASK[59], MDAY365MASK[59], NMDAY365MASK[31]
37
+ MDAY365MASK = tuple(MDAY365MASK)
38
+ M365MASK = tuple(M365MASK)
39
+
40
+ (YEARLY,
41
+ MONTHLY,
42
+ WEEKLY,
43
+ DAILY,
44
+ HOURLY,
45
+ MINUTELY,
46
+ SECONDLY) = list(range(7))
47
+
48
+ # Imported on demand.
49
+ easter = None
50
+ parser = None
51
+
52
+
53
+ class weekday(object):
54
+ __slots__ = ["weekday", "n"]
55
+
56
+ def __init__(self, weekday, n=None):
57
+ if n == 0:
58
+ raise ValueError("Can't create weekday with n == 0")
59
+ self.weekday = weekday
60
+ self.n = n
61
+
62
+ def __call__(self, n):
63
+ if n == self.n:
64
+ return self
65
+ else:
66
+ return self.__class__(self.weekday, n)
67
+
68
+ def __eq__(self, other):
69
+ try:
70
+ if self.weekday != other.weekday or self.n != other.n:
71
+ return False
72
+ except AttributeError:
73
+ return False
74
+ return True
75
+
76
+ def __repr__(self):
77
+ s = ("MO", "TU", "WE", "TH", "FR", "SA", "SU")[self.weekday]
78
+ if not self.n:
79
+ return s
80
+ else:
81
+ return "%s(%+d)" % (s, self.n)
82
+
83
+ MO, TU, WE, TH, FR, SA, SU = weekdays = tuple([weekday(x) for x in range(7)])
84
+
85
+
86
+ class rrulebase(object):
87
+ def __init__(self, cache=False):
88
+ if cache:
89
+ self._cache = []
90
+ self._cache_lock = _thread.allocate_lock()
91
+ self._cache_gen = self._iter()
92
+ self._cache_complete = False
93
+ else:
94
+ self._cache = None
95
+ self._cache_complete = False
96
+ self._len = None
97
+
98
+ def __iter__(self):
99
+ if self._cache_complete:
100
+ return iter(self._cache)
101
+ elif self._cache is None:
102
+ return self._iter()
103
+ else:
104
+ return self._iter_cached()
105
+
106
+ def _iter_cached(self):
107
+ i = 0
108
+ gen = self._cache_gen
109
+ cache = self._cache
110
+ acquire = self._cache_lock.acquire
111
+ release = self._cache_lock.release
112
+ while gen:
113
+ if i == len(cache):
114
+ acquire()
115
+ if self._cache_complete:
116
+ break
117
+ try:
118
+ for j in range(10):
119
+ cache.append(advance_iterator(gen))
120
+ except StopIteration:
121
+ self._cache_gen = gen = None
122
+ self._cache_complete = True
123
+ break
124
+ release()
125
+ yield cache[i]
126
+ i += 1
127
+ while i < self._len:
128
+ yield cache[i]
129
+ i += 1
130
+
131
+ def __getitem__(self, item):
132
+ if self._cache_complete:
133
+ return self._cache[item]
134
+ elif isinstance(item, slice):
135
+ if item.step and item.step < 0:
136
+ return list(iter(self))[item]
137
+ else:
138
+ return list(itertools.islice(self,
139
+ item.start or 0,
140
+ item.stop or sys.maxsize,
141
+ item.step or 1))
142
+ elif item >= 0:
143
+ gen = iter(self)
144
+ try:
145
+ for i in range(item+1):
146
+ res = advance_iterator(gen)
147
+ except StopIteration:
148
+ raise IndexError
149
+ return res
150
+ else:
151
+ return list(iter(self))[item]
152
+
153
+ def __contains__(self, item):
154
+ if self._cache_complete:
155
+ return item in self._cache
156
+ else:
157
+ for i in self:
158
+ if i == item:
159
+ return True
160
+ elif i > item:
161
+ return False
162
+ return False
163
+
164
+ # __len__() introduces a large performance penality.
165
+ def count(self):
166
+ """ Returns the number of recurrences in this set. It will have go
167
+ trough the whole recurrence, if this hasn't been done before. """
168
+ if self._len is None:
169
+ for x in self:
170
+ pass
171
+ return self._len
172
+
173
+ def before(self, dt, inc=False):
174
+ """ Returns the last recurrence before the given datetime instance. The
175
+ inc keyword defines what happens if dt is an occurrence. With
176
+ inc=True, if dt itself is an occurrence, it will be returned. """
177
+ if self._cache_complete:
178
+ gen = self._cache
179
+ else:
180
+ gen = self
181
+ last = None
182
+ if inc:
183
+ for i in gen:
184
+ if i > dt:
185
+ break
186
+ last = i
187
+ else:
188
+ for i in gen:
189
+ if i >= dt:
190
+ break
191
+ last = i
192
+ return last
193
+
194
+ def after(self, dt, inc=False):
195
+ """ Returns the first recurrence after the given datetime instance. The
196
+ inc keyword defines what happens if dt is an occurrence. With
197
+ inc=True, if dt itself is an occurrence, it will be returned. """
198
+ if self._cache_complete:
199
+ gen = self._cache
200
+ else:
201
+ gen = self
202
+ if inc:
203
+ for i in gen:
204
+ if i >= dt:
205
+ return i
206
+ else:
207
+ for i in gen:
208
+ if i > dt:
209
+ return i
210
+ return None
211
+
212
+ def between(self, after, before, inc=False):
213
+ """ Returns all the occurrences of the rrule between after and before.
214
+ The inc keyword defines what happens if after and/or before are
215
+ themselves occurrences. With inc=True, they will be included in the
216
+ list, if they are found in the recurrence set. """
217
+ if self._cache_complete:
218
+ gen = self._cache
219
+ else:
220
+ gen = self
221
+ started = False
222
+ l = []
223
+ if inc:
224
+ for i in gen:
225
+ if i > before:
226
+ break
227
+ elif not started:
228
+ if i >= after:
229
+ started = True
230
+ l.append(i)
231
+ else:
232
+ l.append(i)
233
+ else:
234
+ for i in gen:
235
+ if i >= before:
236
+ break
237
+ elif not started:
238
+ if i > after:
239
+ started = True
240
+ l.append(i)
241
+ else:
242
+ l.append(i)
243
+ return l
244
+
245
+
246
+ class rrule(rrulebase):
247
+ """
248
+ That's the base of the rrule operation. It accepts all the keywords
249
+ defined in the RFC as its constructor parameters (except byday,
250
+ which was renamed to byweekday) and more. The constructor prototype is::
251
+
252
+ rrule(freq)
253
+
254
+ Where freq must be one of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY,
255
+ or SECONDLY.
256
+
257
+ Additionally, it supports the following keyword arguments:
258
+
259
+ :param cache:
260
+ If given, it must be a boolean value specifying to enable or disable
261
+ caching of results. If you will use the same rrule instance multiple
262
+ times, enabling caching will improve the performance considerably.
263
+ :param dtstart:
264
+ The recurrence start. Besides being the base for the recurrence,
265
+ missing parameters in the final recurrence instances will also be
266
+ extracted from this date. If not given, datetime.now() will be used
267
+ instead.
268
+ :param interval:
269
+ The interval between each freq iteration. For example, when using
270
+ YEARLY, an interval of 2 means once every two years, but with HOURLY,
271
+ it means once every two hours. The default interval is 1.
272
+ :param wkst:
273
+ The week start day. Must be one of the MO, TU, WE constants, or an
274
+ integer, specifying the first day of the week. This will affect
275
+ recurrences based on weekly periods. The default week start is got
276
+ from calendar.firstweekday(), and may be modified by
277
+ calendar.setfirstweekday().
278
+ :param count:
279
+ How many occurrences will be generated.
280
+ :param until:
281
+ If given, this must be a datetime instance, that will specify the
282
+ limit of the recurrence. If a recurrence instance happens to be the
283
+ same as the datetime instance given in the until keyword, this will
284
+ be the last occurrence.
285
+ :param bysetpos:
286
+ If given, it must be either an integer, or a sequence of integers,
287
+ positive or negative. Each given integer will specify an occurrence
288
+ number, corresponding to the nth occurrence of the rule inside the
289
+ frequency period. For example, a bysetpos of -1 if combined with a
290
+ MONTHLY frequency, and a byweekday of (MO, TU, WE, TH, FR), will
291
+ result in the last work day of every month.
292
+ :param bymonth:
293
+ If given, it must be either an integer, or a sequence of integers,
294
+ meaning the months to apply the recurrence to.
295
+ :param bymonthday:
296
+ If given, it must be either an integer, or a sequence of integers,
297
+ meaning the month days to apply the recurrence to.
298
+ :param byyearday:
299
+ If given, it must be either an integer, or a sequence of integers,
300
+ meaning the year days to apply the recurrence to.
301
+ :param byweekno:
302
+ If given, it must be either an integer, or a sequence of integers,
303
+ meaning the week numbers to apply the recurrence to. Week numbers
304
+ have the meaning described in ISO8601, that is, the first week of
305
+ the year is that containing at least four days of the new year.
306
+ :param byweekday:
307
+ If given, it must be either an integer (0 == MO), a sequence of
308
+ integers, one of the weekday constants (MO, TU, etc), or a sequence
309
+ of these constants. When given, these variables will define the
310
+ weekdays where the recurrence will be applied. It's also possible to
311
+ use an argument n for the weekday instances, which will mean the nth
312
+ occurrence of this weekday in the period. For example, with MONTHLY,
313
+ or with YEARLY and BYMONTH, using FR(+1) in byweekday will specify the
314
+ first friday of the month where the recurrence happens. Notice that in
315
+ the RFC documentation, this is specified as BYDAY, but was renamed to
316
+ avoid the ambiguity of that keyword.
317
+ :param byhour:
318
+ If given, it must be either an integer, or a sequence of integers,
319
+ meaning the hours to apply the recurrence to.
320
+ :param byminute:
321
+ If given, it must be either an integer, or a sequence of integers,
322
+ meaning the minutes to apply the recurrence to.
323
+ :param bysecond:
324
+ If given, it must be either an integer, or a sequence of integers,
325
+ meaning the seconds to apply the recurrence to.
326
+ :param byeaster:
327
+ If given, it must be either an integer, or a sequence of integers,
328
+ positive or negative. Each integer will define an offset from the
329
+ Easter Sunday. Passing the offset 0 to byeaster will yield the Easter
330
+ Sunday itself. This is an extension to the RFC specification.
331
+ """
332
+ def __init__(self, freq, dtstart=None,
333
+ interval=1, wkst=None, count=None, until=None, bysetpos=None,
334
+ bymonth=None, bymonthday=None, byyearday=None, byeaster=None,
335
+ byweekno=None, byweekday=None,
336
+ byhour=None, byminute=None, bysecond=None,
337
+ cache=False):
338
+ super(rrule, self).__init__(cache)
339
+ global easter
340
+ if not dtstart:
341
+ dtstart = datetime.datetime.now().replace(microsecond=0)
342
+ elif not isinstance(dtstart, datetime.datetime):
343
+ dtstart = datetime.datetime.fromordinal(dtstart.toordinal())
344
+ else:
345
+ dtstart = dtstart.replace(microsecond=0)
346
+ self._dtstart = dtstart
347
+ self._tzinfo = dtstart.tzinfo
348
+ self._freq = freq
349
+ self._interval = interval
350
+ self._count = count
351
+
352
+ if until and not isinstance(until, datetime.datetime):
353
+ until = datetime.datetime.fromordinal(until.toordinal())
354
+ self._until = until
355
+
356
+ if wkst is None:
357
+ self._wkst = calendar.firstweekday()
358
+ elif isinstance(wkst, integer_types):
359
+ self._wkst = wkst
360
+ else:
361
+ self._wkst = wkst.weekday
362
+
363
+ if bysetpos is None:
364
+ self._bysetpos = None
365
+ elif isinstance(bysetpos, integer_types):
366
+ if bysetpos == 0 or not (-366 <= bysetpos <= 366):
367
+ raise ValueError("bysetpos must be between 1 and 366, "
368
+ "or between -366 and -1")
369
+ self._bysetpos = (bysetpos,)
370
+ else:
371
+ self._bysetpos = tuple(bysetpos)
372
+ for pos in self._bysetpos:
373
+ if pos == 0 or not (-366 <= pos <= 366):
374
+ raise ValueError("bysetpos must be between 1 and 366, "
375
+ "or between -366 and -1")
376
+
377
+ if (byweekno is None and byyearday is None and bymonthday is None and
378
+ byweekday is None and byeaster is None):
379
+ if freq == YEARLY:
380
+ if bymonth is None:
381
+ bymonth = dtstart.month
382
+ bymonthday = dtstart.day
383
+ elif freq == MONTHLY:
384
+ bymonthday = dtstart.day
385
+ elif freq == WEEKLY:
386
+ byweekday = dtstart.weekday()
387
+
388
+ # bymonth
389
+ if bymonth is None:
390
+ self._bymonth = None
391
+ else:
392
+ if isinstance(bymonth, integer_types):
393
+ bymonth = (bymonth,)
394
+
395
+ self._bymonth = tuple(sorted(set(bymonth)))
396
+
397
+ # byyearday
398
+ if byyearday is None:
399
+ self._byyearday = None
400
+ else:
401
+ if isinstance(byyearday, integer_types):
402
+ byyearday = (byyearday,)
403
+
404
+ self._byyearday = tuple(sorted(set(byyearday)))
405
+
406
+ # byeaster
407
+ if byeaster is not None:
408
+ if not easter:
409
+ from dateutil import easter
410
+ if isinstance(byeaster, integer_types):
411
+ self._byeaster = (byeaster,)
412
+ else:
413
+ self._byeaster = tuple(sorted(byeaster))
414
+ else:
415
+ self._byeaster = None
416
+
417
+ # bymonthay
418
+ if bymonthday is None:
419
+ self._bymonthday = ()
420
+ self._bynmonthday = ()
421
+ else:
422
+ if isinstance(bymonthday, integer_types):
423
+ bymonthday = (bymonthday,)
424
+
425
+ self._bymonthday = tuple(sorted(set([x for x in bymonthday if x > 0])))
426
+ self._bynmonthday = tuple(sorted(set([x for x in bymonthday if x < 0])))
427
+
428
+ # byweekno
429
+ if byweekno is None:
430
+ self._byweekno = None
431
+ else:
432
+ if isinstance(byweekno, integer_types):
433
+ byweekno = (byweekno,)
434
+
435
+ self._byweekno = tuple(sorted(set(byweekno)))
436
+
437
+ # byweekday / bynweekday
438
+ if byweekday is None:
439
+ self._byweekday = None
440
+ self._bynweekday = None
441
+ else:
442
+ # If it's one of the valid non-sequence types, convert to a
443
+ # single-element sequence before the iterator that builds the
444
+ # byweekday set.
445
+ if isinstance(byweekday, integer_types) or hasattr(byweekday, "n"):
446
+ byweekday = (byweekday,)
447
+
448
+ self._byweekday = set()
449
+ self._bynweekday = set()
450
+ for wday in byweekday:
451
+ if isinstance(wday, integer_types):
452
+ self._byweekday.add(wday)
453
+ elif not wday.n or freq > MONTHLY:
454
+ self._byweekday.add(wday.weekday)
455
+ else:
456
+ self._bynweekday.add((wday.weekday, wday.n))
457
+
458
+ if not self._byweekday:
459
+ self._byweekday = None
460
+ elif not self._bynweekday:
461
+ self._bynweekday = None
462
+
463
+ if self._byweekday is not None:
464
+ self._byweekday = tuple(sorted(self._byweekday))
465
+
466
+ if self._bynweekday is not None:
467
+ self._bynweekday = tuple(sorted(self._bynweekday))
468
+
469
+ # byhour
470
+ if byhour is None:
471
+ if freq < HOURLY:
472
+ self._byhour = set((dtstart.hour,))
473
+ else:
474
+ self._byhour = None
475
+ else:
476
+ if isinstance(byhour, integer_types):
477
+ byhour = (byhour,)
478
+
479
+ if freq == HOURLY:
480
+ self._byhour = self.__construct_byset(start=dtstart.hour,
481
+ byxxx=byhour,
482
+ base=24)
483
+ else:
484
+ self._byhour = set(byhour)
485
+
486
+ self._byhour = tuple(sorted(self._byhour))
487
+
488
+ # byminute
489
+ if byminute is None:
490
+ if freq < MINUTELY:
491
+ self._byminute = set((dtstart.minute,))
492
+ else:
493
+ self._byminute = None
494
+ else:
495
+ if isinstance(byminute, integer_types):
496
+ byminute = (byminute,)
497
+
498
+ if freq == MINUTELY:
499
+ self._byminute = self.__construct_byset(start=dtstart.minute,
500
+ byxxx=byminute,
501
+ base=60)
502
+ else:
503
+ self._byminute = set(byminute)
504
+
505
+ self._byminute = tuple(sorted(self._byminute))
506
+
507
+ # bysecond
508
+ if bysecond is None:
509
+ if freq < SECONDLY:
510
+ self._bysecond = ((dtstart.second,))
511
+ else:
512
+ self._bysecond = None
513
+ else:
514
+ if isinstance(bysecond, integer_types):
515
+ bysecond = (bysecond,)
516
+
517
+ self._bysecond = set(bysecond)
518
+
519
+ if freq == SECONDLY:
520
+ self._bysecond = self.__construct_byset(start=dtstart.second,
521
+ byxxx=bysecond,
522
+ base=60)
523
+ else:
524
+ self._bysecond = set(bysecond)
525
+
526
+ self._bysecond = tuple(sorted(self._bysecond))
527
+
528
+ if self._freq >= HOURLY:
529
+ self._timeset = None
530
+ else:
531
+ self._timeset = []
532
+ for hour in self._byhour:
533
+ for minute in self._byminute:
534
+ for second in self._bysecond:
535
+ self._timeset.append(
536
+ datetime.time(hour, minute, second,
537
+ tzinfo=self._tzinfo))
538
+ self._timeset.sort()
539
+ self._timeset = tuple(self._timeset)
540
+
541
+ def _iter(self):
542
+ year, month, day, hour, minute, second, weekday, yearday, _ = \
543
+ self._dtstart.timetuple()
544
+
545
+ # Some local variables to speed things up a bit
546
+ freq = self._freq
547
+ interval = self._interval
548
+ wkst = self._wkst
549
+ until = self._until
550
+ bymonth = self._bymonth
551
+ byweekno = self._byweekno
552
+ byyearday = self._byyearday
553
+ byweekday = self._byweekday
554
+ byeaster = self._byeaster
555
+ bymonthday = self._bymonthday
556
+ bynmonthday = self._bynmonthday
557
+ bysetpos = self._bysetpos
558
+ byhour = self._byhour
559
+ byminute = self._byminute
560
+ bysecond = self._bysecond
561
+
562
+ ii = _iterinfo(self)
563
+ ii.rebuild(year, month)
564
+
565
+ getdayset = {YEARLY: ii.ydayset,
566
+ MONTHLY: ii.mdayset,
567
+ WEEKLY: ii.wdayset,
568
+ DAILY: ii.ddayset,
569
+ HOURLY: ii.ddayset,
570
+ MINUTELY: ii.ddayset,
571
+ SECONDLY: ii.ddayset}[freq]
572
+
573
+ if freq < HOURLY:
574
+ timeset = self._timeset
575
+ else:
576
+ gettimeset = {HOURLY: ii.htimeset,
577
+ MINUTELY: ii.mtimeset,
578
+ SECONDLY: ii.stimeset}[freq]
579
+ if ((freq >= HOURLY and
580
+ self._byhour and hour not in self._byhour) or
581
+ (freq >= MINUTELY and
582
+ self._byminute and minute not in self._byminute) or
583
+ (freq >= SECONDLY and
584
+ self._bysecond and second not in self._bysecond)):
585
+ timeset = ()
586
+ else:
587
+ timeset = gettimeset(hour, minute, second)
588
+
589
+ total = 0
590
+ count = self._count
591
+ while True:
592
+ # Get dayset with the right frequency
593
+ dayset, start, end = getdayset(year, month, day)
594
+
595
+ # Do the "hard" work ;-)
596
+ filtered = False
597
+ for i in dayset[start:end]:
598
+ if ((bymonth and ii.mmask[i] not in bymonth) or
599
+ (byweekno and not ii.wnomask[i]) or
600
+ (byweekday and ii.wdaymask[i] not in byweekday) or
601
+ (ii.nwdaymask and not ii.nwdaymask[i]) or
602
+ (byeaster and not ii.eastermask[i]) or
603
+ ((bymonthday or bynmonthday) and
604
+ ii.mdaymask[i] not in bymonthday and
605
+ ii.nmdaymask[i] not in bynmonthday) or
606
+ (byyearday and
607
+ ((i < ii.yearlen and i+1 not in byyearday and
608
+ -ii.yearlen+i not in byyearday) or
609
+ (i >= ii.yearlen and i+1-ii.yearlen not in byyearday and
610
+ -ii.nextyearlen+i-ii.yearlen not in byyearday)))):
611
+ dayset[i] = None
612
+ filtered = True
613
+
614
+ # Output results
615
+ if bysetpos and timeset:
616
+ poslist = []
617
+ for pos in bysetpos:
618
+ if pos < 0:
619
+ daypos, timepos = divmod(pos, len(timeset))
620
+ else:
621
+ daypos, timepos = divmod(pos-1, len(timeset))
622
+ try:
623
+ i = [x for x in dayset[start:end]
624
+ if x is not None][daypos]
625
+ time = timeset[timepos]
626
+ except IndexError:
627
+ pass
628
+ else:
629
+ date = datetime.date.fromordinal(ii.yearordinal+i)
630
+ res = datetime.datetime.combine(date, time)
631
+ if res not in poslist:
632
+ poslist.append(res)
633
+ poslist.sort()
634
+ for res in poslist:
635
+ if until and res > until:
636
+ self._len = total
637
+ return
638
+ elif res >= self._dtstart:
639
+ total += 1
640
+ yield res
641
+ if count:
642
+ count -= 1
643
+ if not count:
644
+ self._len = total
645
+ return
646
+ else:
647
+ for i in dayset[start:end]:
648
+ if i is not None:
649
+ date = datetime.date.fromordinal(ii.yearordinal+i)
650
+ for time in timeset:
651
+ res = datetime.datetime.combine(date, time)
652
+ if until and res > until:
653
+ self._len = total
654
+ return
655
+ elif res >= self._dtstart:
656
+ total += 1
657
+ yield res
658
+ if count:
659
+ count -= 1
660
+ if not count:
661
+ self._len = total
662
+ return
663
+
664
+ # Handle frequency and interval
665
+ fixday = False
666
+ if freq == YEARLY:
667
+ year += interval
668
+ if year > datetime.MAXYEAR:
669
+ self._len = total
670
+ return
671
+ ii.rebuild(year, month)
672
+ elif freq == MONTHLY:
673
+ month += interval
674
+ if month > 12:
675
+ div, mod = divmod(month, 12)
676
+ month = mod
677
+ year += div
678
+ if month == 0:
679
+ month = 12
680
+ year -= 1
681
+ if year > datetime.MAXYEAR:
682
+ self._len = total
683
+ return
684
+ ii.rebuild(year, month)
685
+ elif freq == WEEKLY:
686
+ if wkst > weekday:
687
+ day += -(weekday+1+(6-wkst))+self._interval*7
688
+ else:
689
+ day += -(weekday-wkst)+self._interval*7
690
+ weekday = wkst
691
+ fixday = True
692
+ elif freq == DAILY:
693
+ day += interval
694
+ fixday = True
695
+ elif freq == HOURLY:
696
+ if filtered:
697
+ # Jump to one iteration before next day
698
+ hour += ((23-hour)//interval)*interval
699
+
700
+ if byhour:
701
+ ndays, hour = self.__mod_distance(value=hour,
702
+ byxxx=self._byhour,
703
+ base=24)
704
+ else:
705
+ ndays, hour = divmod(hour+interval, 24)
706
+
707
+ if ndays:
708
+ day += ndays
709
+ fixday = True
710
+
711
+ timeset = gettimeset(hour, minute, second)
712
+ elif freq == MINUTELY:
713
+ if filtered:
714
+ # Jump to one iteration before next day
715
+ minute += ((1439-(hour*60+minute))//interval)*interval
716
+
717
+ valid = False
718
+ rep_rate = (24*60)
719
+ for j in range(rep_rate // gcd(interval, rep_rate)):
720
+ if byminute:
721
+ nhours, minute = \
722
+ self.__mod_distance(value=minute,
723
+ byxxx=self._byminute,
724
+ base=60)
725
+ else:
726
+ nhours, minute = divmod(minute+interval, 60)
727
+
728
+ div, hour = divmod(hour+nhours, 24)
729
+ if div:
730
+ day += div
731
+ fixday = True
732
+ filtered = False
733
+
734
+ if not byhour or hour in byhour:
735
+ valid = True
736
+ break
737
+
738
+ if not valid:
739
+ raise ValueError('Invalid combination of interval and ' +
740
+ 'byhour resulting in empty rule.')
741
+
742
+ timeset = gettimeset(hour, minute, second)
743
+ elif freq == SECONDLY:
744
+ if filtered:
745
+ # Jump to one iteration before next day
746
+ second += (((86399-(hour*3600+minute*60+second))
747
+ // interval)*interval)
748
+
749
+ rep_rate = (24*3600)
750
+ valid = False
751
+ for j in range(0, rep_rate // gcd(interval, rep_rate)):
752
+ if bysecond:
753
+ nminutes, second = \
754
+ self.__mod_distance(value=second,
755
+ byxxx=self._bysecond,
756
+ base=60)
757
+ else:
758
+ nminutes, second = divmod(second+interval, 60)
759
+
760
+ div, minute = divmod(minute+nminutes, 60)
761
+ if div:
762
+ hour += div
763
+ div, hour = divmod(hour, 24)
764
+ if div:
765
+ day += div
766
+ fixday = True
767
+
768
+ if ((not byhour or hour in byhour) and
769
+ (not byminute or minute in byminute) and
770
+ (not bysecond or second in bysecond)):
771
+ valid = True
772
+ break
773
+
774
+ if not valid:
775
+ raise ValueError('Invalid combination of interval, ' +
776
+ 'byhour and byminute resulting in empty' +
777
+ ' rule.')
778
+
779
+ timeset = gettimeset(hour, minute, second)
780
+
781
+ if fixday and day > 28:
782
+ daysinmonth = calendar.monthrange(year, month)[1]
783
+ if day > daysinmonth:
784
+ while day > daysinmonth:
785
+ day -= daysinmonth
786
+ month += 1
787
+ if month == 13:
788
+ month = 1
789
+ year += 1
790
+ if year > datetime.MAXYEAR:
791
+ self._len = total
792
+ return
793
+ daysinmonth = calendar.monthrange(year, month)[1]
794
+ ii.rebuild(year, month)
795
+
796
+ def __construct_byset(self, start, byxxx, base):
797
+ """
798
+ If a `BYXXX` sequence is passed to the constructor at the same level as
799
+ `FREQ` (e.g. `FREQ=HOURLY,BYHOUR={2,4,7},INTERVAL=3`), there are some
800
+ specifications which cannot be reached given some starting conditions.
801
+
802
+ This occurs whenever the interval is not coprime with the base of a
803
+ given unit and the difference between the starting position and the
804
+ ending position is not coprime with the greatest common denominator
805
+ between the interval and the base. For example, with a FREQ of hourly
806
+ starting at 17:00 and an interval of 4, the only valid values for
807
+ BYHOUR would be {21, 1, 5, 9, 13, 17}, because 4 and 24 are not
808
+ coprime.
809
+
810
+ :param start:
811
+ Specifies the starting position.
812
+ :param byxxx:
813
+ An iterable containing the list of allowed values.
814
+ :param base:
815
+ The largest allowable value for the specified frequency (e.g.
816
+ 24 hours, 60 minutes).
817
+
818
+ This does not preserve the type of the iterable, returning a set, since
819
+ the values should be unique and the order is irrelevant, this will
820
+ speed up later lookups.
821
+
822
+ In the event of an empty set, raises a :exception:`ValueError`, as this
823
+ results in an empty rrule.
824
+ """
825
+
826
+ cset = set()
827
+
828
+ # Support a single byxxx value.
829
+ if isinstance(byxxx, integer_types):
830
+ byxxx = (byxxx, )
831
+
832
+ for num in byxxx:
833
+ i_gcd = gcd(self._interval, base)
834
+ # Use divmod rather than % because we need to wrap negative nums.
835
+ if i_gcd == 1 or divmod(num - start, i_gcd)[1] == 0:
836
+ cset.add(num)
837
+
838
+ if len(cset) == 0:
839
+ raise ValueError("Invalid rrule byxxx generates an empty set.")
840
+
841
+ return cset
842
+
843
+ def __mod_distance(self, value, byxxx, base):
844
+ """
845
+ Calculates the next value in a sequence where the `FREQ` parameter is
846
+ specified along with a `BYXXX` parameter at the same "level"
847
+ (e.g. `HOURLY` specified with `BYHOUR`).
848
+
849
+ :param value:
850
+ The old value of the component.
851
+ :param byxxx:
852
+ The `BYXXX` set, which should have been generated by
853
+ `rrule._construct_byset`, or something else which checks that a
854
+ valid rule is present.
855
+ :param base:
856
+ The largest allowable value for the specified frequency (e.g.
857
+ 24 hours, 60 minutes).
858
+
859
+ If a valid value is not found after `base` iterations (the maximum
860
+ number before the sequence would start to repeat), this raises a
861
+ :exception:`ValueError`, as no valid values were found.
862
+
863
+ This returns a tuple of `divmod(n*interval, base)`, where `n` is the
864
+ smallest number of `interval` repetitions until the next specified
865
+ value in `byxxx` is found.
866
+ """
867
+ accumulator = 0
868
+ for ii in range(1, base + 1):
869
+ # Using divmod() over % to account for negative intervals
870
+ div, value = divmod(value + self._interval, base)
871
+ accumulator += div
872
+ if value in byxxx:
873
+ return (accumulator, value)
874
+
875
+
876
+ class _iterinfo(object):
877
+ __slots__ = ["rrule", "lastyear", "lastmonth",
878
+ "yearlen", "nextyearlen", "yearordinal", "yearweekday",
879
+ "mmask", "mrange", "mdaymask", "nmdaymask",
880
+ "wdaymask", "wnomask", "nwdaymask", "eastermask"]
881
+
882
+ def __init__(self, rrule):
883
+ for attr in self.__slots__:
884
+ setattr(self, attr, None)
885
+ self.rrule = rrule
886
+
887
+ def rebuild(self, year, month):
888
+ # Every mask is 7 days longer to handle cross-year weekly periods.
889
+ rr = self.rrule
890
+ if year != self.lastyear:
891
+ self.yearlen = 365+calendar.isleap(year)
892
+ self.nextyearlen = 365+calendar.isleap(year+1)
893
+ firstyday = datetime.date(year, 1, 1)
894
+ self.yearordinal = firstyday.toordinal()
895
+ self.yearweekday = firstyday.weekday()
896
+
897
+ wday = datetime.date(year, 1, 1).weekday()
898
+ if self.yearlen == 365:
899
+ self.mmask = M365MASK
900
+ self.mdaymask = MDAY365MASK
901
+ self.nmdaymask = NMDAY365MASK
902
+ self.wdaymask = WDAYMASK[wday:]
903
+ self.mrange = M365RANGE
904
+ else:
905
+ self.mmask = M366MASK
906
+ self.mdaymask = MDAY366MASK
907
+ self.nmdaymask = NMDAY366MASK
908
+ self.wdaymask = WDAYMASK[wday:]
909
+ self.mrange = M366RANGE
910
+
911
+ if not rr._byweekno:
912
+ self.wnomask = None
913
+ else:
914
+ self.wnomask = [0]*(self.yearlen+7)
915
+ # no1wkst = firstwkst = self.wdaymask.index(rr._wkst)
916
+ no1wkst = firstwkst = (7-self.yearweekday+rr._wkst) % 7
917
+ if no1wkst >= 4:
918
+ no1wkst = 0
919
+ # Number of days in the year, plus the days we got
920
+ # from last year.
921
+ wyearlen = self.yearlen+(self.yearweekday-rr._wkst) % 7
922
+ else:
923
+ # Number of days in the year, minus the days we
924
+ # left in last year.
925
+ wyearlen = self.yearlen-no1wkst
926
+ div, mod = divmod(wyearlen, 7)
927
+ numweeks = div+mod//4
928
+ for n in rr._byweekno:
929
+ if n < 0:
930
+ n += numweeks+1
931
+ if not (0 < n <= numweeks):
932
+ continue
933
+ if n > 1:
934
+ i = no1wkst+(n-1)*7
935
+ if no1wkst != firstwkst:
936
+ i -= 7-firstwkst
937
+ else:
938
+ i = no1wkst
939
+ for j in range(7):
940
+ self.wnomask[i] = 1
941
+ i += 1
942
+ if self.wdaymask[i] == rr._wkst:
943
+ break
944
+ if 1 in rr._byweekno:
945
+ # Check week number 1 of next year as well
946
+ # TODO: Check -numweeks for next year.
947
+ i = no1wkst+numweeks*7
948
+ if no1wkst != firstwkst:
949
+ i -= 7-firstwkst
950
+ if i < self.yearlen:
951
+ # If week starts in next year, we
952
+ # don't care about it.
953
+ for j in range(7):
954
+ self.wnomask[i] = 1
955
+ i += 1
956
+ if self.wdaymask[i] == rr._wkst:
957
+ break
958
+ if no1wkst:
959
+ # Check last week number of last year as
960
+ # well. If no1wkst is 0, either the year
961
+ # started on week start, or week number 1
962
+ # got days from last year, so there are no
963
+ # days from last year's last week number in
964
+ # this year.
965
+ if -1 not in rr._byweekno:
966
+ lyearweekday = datetime.date(year-1, 1, 1).weekday()
967
+ lno1wkst = (7-lyearweekday+rr._wkst) % 7
968
+ lyearlen = 365+calendar.isleap(year-1)
969
+ if lno1wkst >= 4:
970
+ lno1wkst = 0
971
+ lnumweeks = 52+(lyearlen +
972
+ (lyearweekday-rr._wkst) % 7) % 7//4
973
+ else:
974
+ lnumweeks = 52+(self.yearlen-no1wkst) % 7//4
975
+ else:
976
+ lnumweeks = -1
977
+ if lnumweeks in rr._byweekno:
978
+ for i in range(no1wkst):
979
+ self.wnomask[i] = 1
980
+
981
+ if (rr._bynweekday and (month != self.lastmonth or
982
+ year != self.lastyear)):
983
+ ranges = []
984
+ if rr._freq == YEARLY:
985
+ if rr._bymonth:
986
+ for month in rr._bymonth:
987
+ ranges.append(self.mrange[month-1:month+1])
988
+ else:
989
+ ranges = [(0, self.yearlen)]
990
+ elif rr._freq == MONTHLY:
991
+ ranges = [self.mrange[month-1:month+1]]
992
+ if ranges:
993
+ # Weekly frequency won't get here, so we may not
994
+ # care about cross-year weekly periods.
995
+ self.nwdaymask = [0]*self.yearlen
996
+ for first, last in ranges:
997
+ last -= 1
998
+ for wday, n in rr._bynweekday:
999
+ if n < 0:
1000
+ i = last+(n+1)*7
1001
+ i -= (self.wdaymask[i]-wday) % 7
1002
+ else:
1003
+ i = first+(n-1)*7
1004
+ i += (7-self.wdaymask[i]+wday) % 7
1005
+ if first <= i <= last:
1006
+ self.nwdaymask[i] = 1
1007
+
1008
+ if rr._byeaster:
1009
+ self.eastermask = [0]*(self.yearlen+7)
1010
+ eyday = easter.easter(year).toordinal()-self.yearordinal
1011
+ for offset in rr._byeaster:
1012
+ self.eastermask[eyday+offset] = 1
1013
+
1014
+ self.lastyear = year
1015
+ self.lastmonth = month
1016
+
1017
+ def ydayset(self, year, month, day):
1018
+ return list(range(self.yearlen)), 0, self.yearlen
1019
+
1020
+ def mdayset(self, year, month, day):
1021
+ dset = [None]*self.yearlen
1022
+ start, end = self.mrange[month-1:month+1]
1023
+ for i in range(start, end):
1024
+ dset[i] = i
1025
+ return dset, start, end
1026
+
1027
+ def wdayset(self, year, month, day):
1028
+ # We need to handle cross-year weeks here.
1029
+ dset = [None]*(self.yearlen+7)
1030
+ i = datetime.date(year, month, day).toordinal()-self.yearordinal
1031
+ start = i
1032
+ for j in range(7):
1033
+ dset[i] = i
1034
+ i += 1
1035
+ # if (not (0 <= i < self.yearlen) or
1036
+ # self.wdaymask[i] == self.rrule._wkst):
1037
+ # This will cross the year boundary, if necessary.
1038
+ if self.wdaymask[i] == self.rrule._wkst:
1039
+ break
1040
+ return dset, start, i
1041
+
1042
+ def ddayset(self, year, month, day):
1043
+ dset = [None]*self.yearlen
1044
+ i = datetime.date(year, month, day).toordinal()-self.yearordinal
1045
+ dset[i] = i
1046
+ return dset, i, i+1
1047
+
1048
+ def htimeset(self, hour, minute, second):
1049
+ tset = []
1050
+ rr = self.rrule
1051
+ for minute in rr._byminute:
1052
+ for second in rr._bysecond:
1053
+ tset.append(datetime.time(hour, minute, second,
1054
+ tzinfo=rr._tzinfo))
1055
+ tset.sort()
1056
+ return tset
1057
+
1058
+ def mtimeset(self, hour, minute, second):
1059
+ tset = []
1060
+ rr = self.rrule
1061
+ for second in rr._bysecond:
1062
+ tset.append(datetime.time(hour, minute, second, tzinfo=rr._tzinfo))
1063
+ tset.sort()
1064
+ return tset
1065
+
1066
+ def stimeset(self, hour, minute, second):
1067
+ return (datetime.time(hour, minute, second,
1068
+ tzinfo=self.rrule._tzinfo),)
1069
+
1070
+
1071
+ class rruleset(rrulebase):
1072
+ """ The rruleset type allows more complex recurrence setups, mixing
1073
+ multiple rules, dates, exclusion rules, and exclusion dates. The type
1074
+ constructor takes the following keyword arguments:
1075
+
1076
+ :param cache: If True, caching of results will be enabled, improving
1077
+ performance of multiple queries considerably. """
1078
+
1079
+ class _genitem(object):
1080
+ def __init__(self, genlist, gen):
1081
+ try:
1082
+ self.dt = advance_iterator(gen)
1083
+ genlist.append(self)
1084
+ except StopIteration:
1085
+ pass
1086
+ self.genlist = genlist
1087
+ self.gen = gen
1088
+
1089
+ def __next__(self):
1090
+ try:
1091
+ self.dt = advance_iterator(self.gen)
1092
+ except StopIteration:
1093
+ self.genlist.remove(self)
1094
+
1095
+ next = __next__
1096
+
1097
+ def __lt__(self, other):
1098
+ return self.dt < other.dt
1099
+
1100
+ def __gt__(self, other):
1101
+ return self.dt > other.dt
1102
+
1103
+ def __eq__(self, other):
1104
+ return self.dt == other.dt
1105
+
1106
+ def __ne__(self, other):
1107
+ return self.dt != other.dt
1108
+
1109
+ def __init__(self, cache=False):
1110
+ super(rruleset, self).__init__(cache)
1111
+ self._rrule = []
1112
+ self._rdate = []
1113
+ self._exrule = []
1114
+ self._exdate = []
1115
+
1116
+ def rrule(self, rrule):
1117
+ """ Include the given :py:class:`rrule` instance in the recurrence set
1118
+ generation. """
1119
+ self._rrule.append(rrule)
1120
+
1121
+ def rdate(self, rdate):
1122
+ """ Include the given :py:class:`datetime` instance in the recurrence
1123
+ set generation. """
1124
+ self._rdate.append(rdate)
1125
+
1126
+ def exrule(self, exrule):
1127
+ """ Include the given rrule instance in the recurrence set exclusion
1128
+ list. Dates which are part of the given recurrence rules will not
1129
+ be generated, even if some inclusive rrule or rdate matches them.
1130
+ """
1131
+ self._exrule.append(exrule)
1132
+
1133
+ def exdate(self, exdate):
1134
+ """ Include the given datetime instance in the recurrence set
1135
+ exclusion list. Dates included that way will not be generated,
1136
+ even if some inclusive rrule or rdate matches them. """
1137
+ self._exdate.append(exdate)
1138
+
1139
+ def _iter(self):
1140
+ rlist = []
1141
+ self._rdate.sort()
1142
+ self._genitem(rlist, iter(self._rdate))
1143
+ for gen in [iter(x) for x in self._rrule]:
1144
+ self._genitem(rlist, gen)
1145
+ rlist.sort()
1146
+ exlist = []
1147
+ self._exdate.sort()
1148
+ self._genitem(exlist, iter(self._exdate))
1149
+ for gen in [iter(x) for x in self._exrule]:
1150
+ self._genitem(exlist, gen)
1151
+ exlist.sort()
1152
+ lastdt = None
1153
+ total = 0
1154
+ while rlist:
1155
+ ritem = rlist[0]
1156
+ if not lastdt or lastdt != ritem.dt:
1157
+ while exlist and exlist[0] < ritem:
1158
+ advance_iterator(exlist[0])
1159
+ exlist.sort()
1160
+ if not exlist or ritem != exlist[0]:
1161
+ total += 1
1162
+ yield ritem.dt
1163
+ lastdt = ritem.dt
1164
+ advance_iterator(ritem)
1165
+ rlist.sort()
1166
+ self._len = total
1167
+
1168
+
1169
+ class _rrulestr(object):
1170
+
1171
+ _freq_map = {"YEARLY": YEARLY,
1172
+ "MONTHLY": MONTHLY,
1173
+ "WEEKLY": WEEKLY,
1174
+ "DAILY": DAILY,
1175
+ "HOURLY": HOURLY,
1176
+ "MINUTELY": MINUTELY,
1177
+ "SECONDLY": SECONDLY}
1178
+
1179
+ _weekday_map = {"MO": 0, "TU": 1, "WE": 2, "TH": 3,
1180
+ "FR": 4, "SA": 5, "SU": 6}
1181
+
1182
+ def _handle_int(self, rrkwargs, name, value, **kwargs):
1183
+ rrkwargs[name.lower()] = int(value)
1184
+
1185
+ def _handle_int_list(self, rrkwargs, name, value, **kwargs):
1186
+ rrkwargs[name.lower()] = [int(x) for x in value.split(',')]
1187
+
1188
+ _handle_INTERVAL = _handle_int
1189
+ _handle_COUNT = _handle_int
1190
+ _handle_BYSETPOS = _handle_int_list
1191
+ _handle_BYMONTH = _handle_int_list
1192
+ _handle_BYMONTHDAY = _handle_int_list
1193
+ _handle_BYYEARDAY = _handle_int_list
1194
+ _handle_BYEASTER = _handle_int_list
1195
+ _handle_BYWEEKNO = _handle_int_list
1196
+ _handle_BYHOUR = _handle_int_list
1197
+ _handle_BYMINUTE = _handle_int_list
1198
+ _handle_BYSECOND = _handle_int_list
1199
+
1200
+ def _handle_FREQ(self, rrkwargs, name, value, **kwargs):
1201
+ rrkwargs["freq"] = self._freq_map[value]
1202
+
1203
+ def _handle_UNTIL(self, rrkwargs, name, value, **kwargs):
1204
+ global parser
1205
+ if not parser:
1206
+ from dateutil import parser
1207
+ try:
1208
+ rrkwargs["until"] = parser.parse(value,
1209
+ ignoretz=kwargs.get("ignoretz"),
1210
+ tzinfos=kwargs.get("tzinfos"))
1211
+ except ValueError:
1212
+ raise ValueError("invalid until date")
1213
+
1214
+ def _handle_WKST(self, rrkwargs, name, value, **kwargs):
1215
+ rrkwargs["wkst"] = self._weekday_map[value]
1216
+
1217
+ def _handle_BYWEEKDAY(self, rrkwargs, name, value, **kwarsg):
1218
+ l = []
1219
+ for wday in value.split(','):
1220
+ for i in range(len(wday)):
1221
+ if wday[i] not in '+-0123456789':
1222
+ break
1223
+ n = wday[:i] or None
1224
+ w = wday[i:]
1225
+ if n:
1226
+ n = int(n)
1227
+ l.append(weekdays[self._weekday_map[w]](n))
1228
+ rrkwargs["byweekday"] = l
1229
+
1230
+ _handle_BYDAY = _handle_BYWEEKDAY
1231
+
1232
+ def _parse_rfc_rrule(self, line,
1233
+ dtstart=None,
1234
+ cache=False,
1235
+ ignoretz=False,
1236
+ tzinfos=None):
1237
+ if line.find(':') != -1:
1238
+ name, value = line.split(':')
1239
+ if name != "RRULE":
1240
+ raise ValueError("unknown parameter name")
1241
+ else:
1242
+ value = line
1243
+ rrkwargs = {}
1244
+ for pair in value.split(';'):
1245
+ name, value = pair.split('=')
1246
+ name = name.upper()
1247
+ value = value.upper()
1248
+ try:
1249
+ getattr(self, "_handle_"+name)(rrkwargs, name, value,
1250
+ ignoretz=ignoretz,
1251
+ tzinfos=tzinfos)
1252
+ except AttributeError:
1253
+ raise ValueError("unknown parameter '%s'" % name)
1254
+ except (KeyError, ValueError):
1255
+ raise ValueError("invalid '%s': %s" % (name, value))
1256
+ return rrule(dtstart=dtstart, cache=cache, **rrkwargs)
1257
+
1258
+ def _parse_rfc(self, s,
1259
+ dtstart=None,
1260
+ cache=False,
1261
+ unfold=False,
1262
+ forceset=False,
1263
+ compatible=False,
1264
+ ignoretz=False,
1265
+ tzinfos=None):
1266
+ global parser
1267
+ if compatible:
1268
+ forceset = True
1269
+ unfold = True
1270
+ s = s.upper()
1271
+ if not s.strip():
1272
+ raise ValueError("empty string")
1273
+ if unfold:
1274
+ lines = s.splitlines()
1275
+ i = 0
1276
+ while i < len(lines):
1277
+ line = lines[i].rstrip()
1278
+ if not line:
1279
+ del lines[i]
1280
+ elif i > 0 and line[0] == " ":
1281
+ lines[i-1] += line[1:]
1282
+ del lines[i]
1283
+ else:
1284
+ i += 1
1285
+ else:
1286
+ lines = s.split()
1287
+ if (not forceset and len(lines) == 1 and (s.find(':') == -1 or
1288
+ s.startswith('RRULE:'))):
1289
+ return self._parse_rfc_rrule(lines[0], cache=cache,
1290
+ dtstart=dtstart, ignoretz=ignoretz,
1291
+ tzinfos=tzinfos)
1292
+ else:
1293
+ rrulevals = []
1294
+ rdatevals = []
1295
+ exrulevals = []
1296
+ exdatevals = []
1297
+ for line in lines:
1298
+ if not line:
1299
+ continue
1300
+ if line.find(':') == -1:
1301
+ name = "RRULE"
1302
+ value = line
1303
+ else:
1304
+ name, value = line.split(':', 1)
1305
+ parms = name.split(';')
1306
+ if not parms:
1307
+ raise ValueError("empty property name")
1308
+ name = parms[0]
1309
+ parms = parms[1:]
1310
+ if name == "RRULE":
1311
+ for parm in parms:
1312
+ raise ValueError("unsupported RRULE parm: "+parm)
1313
+ rrulevals.append(value)
1314
+ elif name == "RDATE":
1315
+ for parm in parms:
1316
+ if parm != "VALUE=DATE-TIME":
1317
+ raise ValueError("unsupported RDATE parm: "+parm)
1318
+ rdatevals.append(value)
1319
+ elif name == "EXRULE":
1320
+ for parm in parms:
1321
+ raise ValueError("unsupported EXRULE parm: "+parm)
1322
+ exrulevals.append(value)
1323
+ elif name == "EXDATE":
1324
+ for parm in parms:
1325
+ if parm != "VALUE=DATE-TIME":
1326
+ raise ValueError("unsupported RDATE parm: "+parm)
1327
+ exdatevals.append(value)
1328
+ elif name == "DTSTART":
1329
+ for parm in parms:
1330
+ raise ValueError("unsupported DTSTART parm: "+parm)
1331
+ if not parser:
1332
+ from dateutil import parser
1333
+ dtstart = parser.parse(value, ignoretz=ignoretz,
1334
+ tzinfos=tzinfos)
1335
+ else:
1336
+ raise ValueError("unsupported property: "+name)
1337
+ if (forceset or len(rrulevals) > 1 or rdatevals
1338
+ or exrulevals or exdatevals):
1339
+ if not parser and (rdatevals or exdatevals):
1340
+ from dateutil import parser
1341
+ rset = rruleset(cache=cache)
1342
+ for value in rrulevals:
1343
+ rset.rrule(self._parse_rfc_rrule(value, dtstart=dtstart,
1344
+ ignoretz=ignoretz,
1345
+ tzinfos=tzinfos))
1346
+ for value in rdatevals:
1347
+ for datestr in value.split(','):
1348
+ rset.rdate(parser.parse(datestr,
1349
+ ignoretz=ignoretz,
1350
+ tzinfos=tzinfos))
1351
+ for value in exrulevals:
1352
+ rset.exrule(self._parse_rfc_rrule(value, dtstart=dtstart,
1353
+ ignoretz=ignoretz,
1354
+ tzinfos=tzinfos))
1355
+ for value in exdatevals:
1356
+ for datestr in value.split(','):
1357
+ rset.exdate(parser.parse(datestr,
1358
+ ignoretz=ignoretz,
1359
+ tzinfos=tzinfos))
1360
+ if compatible and dtstart:
1361
+ rset.rdate(dtstart)
1362
+ return rset
1363
+ else:
1364
+ return self._parse_rfc_rrule(rrulevals[0],
1365
+ dtstart=dtstart,
1366
+ cache=cache,
1367
+ ignoretz=ignoretz,
1368
+ tzinfos=tzinfos)
1369
+
1370
+ def __call__(self, s, **kwargs):
1371
+ return self._parse_rfc(s, **kwargs)
1372
+
1373
+ rrulestr = _rrulestr()
1374
+
1375
+ # vim:ts=4:sw=4:et