Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactored DURATION_REGEX #520

Merged
merged 2 commits into from
May 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Changelog

Minor changes:

- ...
- Adjusted duration regex

Breaking changes:

Expand Down
1 change: 1 addition & 0 deletions docs/credits.rst
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ icalendar contributors
- Pronoy <lukex9442@gmail.com>
- Abe Hanoka <abe@habet.dev>
- `Natasha Mattson <https://github.com/natashamm`_
- `NikEasY <https://github.com/NikEasY>`_

Find out who contributed::

Expand Down
39 changes: 19 additions & 20 deletions src/icalendar/prop.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,9 @@
import time as _time


DATE_PART = r'(\d+)D'
TIME_PART = r'T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?'
DATETIME_PART = f'(?:{DATE_PART})?(?:{TIME_PART})?'
WEEKS_PART = r'(\d+)W'
DURATION_REGEX = re.compile(r'([-+]?)P(?:%s|%s)$'
% (WEEKS_PART, DATETIME_PART))
DURATION_REGEX = re.compile(r'([-+]?)P(?:(\d+)W)?(?:(\d+)D)?'
r'(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$')

WEEKDAY_RULE = re.compile(r'(?P<signal>[+-]?)(?P<relative>[\d]?)'
r'(?P<weekday>[\w]{2})$')

Expand Down Expand Up @@ -475,22 +472,24 @@ def to_ical(self):

@staticmethod
def from_ical(ical):
try:
match = DURATION_REGEX.match(ical)
sign, weeks, days, hours, minutes, seconds = match.groups()
if weeks:
value = timedelta(weeks=int(weeks))
else:
value = timedelta(days=int(days or 0),
hours=int(hours or 0),
minutes=int(minutes or 0),
seconds=int(seconds or 0))
if sign == '-':
value = -value
return value
except Exception:
match = DURATION_REGEX.match(ical)
if not match:
raise ValueError(f'Invalid iCalendar duration: {ical}')

sign, weeks, days, hours, minutes, seconds = match.groups()
value = timedelta(
weeks=int(weeks or 0),
days=int(days or 0),
hours=int(hours or 0),
minutes=int(minutes or 0),
seconds=int(seconds or 0)
)

if sign == '-':
value = -value

return value


class vPeriod:
"""A precise period of time.
Expand Down