Skip to content

Commit

Permalink
fix return type
Browse files Browse the repository at this point in the history
  • Loading branch information
aquamatthias committed Dec 4, 2023
1 parent e24954a commit 3581bf8
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
18 changes: 14 additions & 4 deletions resotolib/resotolib/durations.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from functools import reduce
import re
from itertools import chain
from typing import Union, List, Optional
from typing import Union, List, Optional, cast

import isodate
import parsy
Expand Down Expand Up @@ -34,14 +34,16 @@
+ "|".join(chain.from_iterable(names for unit, names, _ in time_units))
+ ")\\s*("
+ "|".join(time_unit_combines)
+ ")?\\s*)+")
+ ")?\\s*)+$"
)

# Matches the proprietary format as well as ISO8601 durations
DurationRe = re.compile(f'({DurationRegexp.pattern})|({ISO8601_PERIOD_REGEX.pattern})')
DurationRe = re.compile(f"({DurationRegexp.pattern})|({ISO8601_PERIOD_REGEX.pattern})")

# Simple check to distinguish between ISO8601 and proprietary format
__ISO8601_PERIOD_PREFIX = re.compile("^([+-])?P")


def combine_durations(elems: List[Union[int, float]]) -> Union[int, float]:
result = 0.0
for d in elems:
Expand All @@ -57,9 +59,17 @@ def combine_durations(elems: List[Union[int, float]]) -> Union[int, float]:
single_duration_parser = parsy.seq((float_p | integer_p), time_unit_parser).combine(operator.mul)
duration_parser = single_duration_parser.sep_by(time_unit_combination.optional(), min=1).map(combine_durations)


def parse_duration(ds: str) -> timedelta:
if __ISO8601_PERIOD_PREFIX.match(ds):
return isodate.parse_duration(ds)
dr = isodate.parse_duration(ds)
if isinstance(dr, isodate.Duration):
td = dr.tdelta
return timedelta(
days=float(td.days + 31 * dr.months + 365 * dr.years), seconds=td.seconds, microseconds=td.microseconds
)
else:
return cast(timedelta, dr)
else:
return timedelta(seconds=duration_parser.parse(ds))

Expand Down
1 change: 1 addition & 0 deletions resotolib/test/durations_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ def test_parse_duration() -> None:


def test_parse_is08601_duration() -> None:
assert parse_duration("P1Y") == timedelta(days=365)
assert parse_duration("PT1S") == timedelta(seconds=1)
assert parse_duration("P4D") == timedelta(days=4)
assert parse_duration("PT1H") == timedelta(hours=1)
Expand Down

0 comments on commit 3581bf8

Please sign in to comment.