docker-tidy/dockertidy/parser.py

56 lines
1.2 KiB
Python
Raw Permalink Normal View History

2020-03-05 22:51:21 +00:00
#!/usr/bin/env python3
"""Custom input type parser."""
2020-03-15 13:50:58 +00:00
from argparse import ArgumentTypeError
2020-03-05 22:51:21 +00:00
2020-03-15 13:50:58 +00:00
import dateparser
2020-03-05 22:51:21 +00:00
import environs
env = environs.Env()
def timedelta_validator(value):
2020-03-15 13:50:58 +00:00
"""Return the dateparser string for a time in the past.
2020-03-05 22:51:21 +00:00
:param value: a string containing a time format supported by
2020-03-15 13:50:58 +00:00
mod:`dateparser`
2020-03-05 22:51:21 +00:00
"""
if value is None:
return None
2020-03-15 13:50:58 +00:00
if not dateparser.parse(value):
raise ArgumentTypeError("'{}' is not a valid timedelta string".format(value))
return value
2020-03-05 22:51:21 +00:00
2020-03-09 00:05:17 +00:00
def timedelta(value, dt_format=None):
2020-03-05 22:51:21 +00:00
"""Return the :class:`datetime.datetime.DateTime` for a time in the past.
:param value: a string containing a time format supported by
2020-03-15 13:50:58 +00:00
mod:`dateparser`
2020-03-05 22:51:21 +00:00
"""
if value is None:
return None
2020-03-09 00:05:17 +00:00
2020-03-15 13:50:58 +00:00
timedelta = dateparser.parse(
value, settings={
"TO_TIMEZONE": "UTC",
"RETURN_AS_TIMEZONE_AWARE": True
}
)
2020-03-09 00:05:17 +00:00
if dt_format:
timedelta = timedelta.strftime(dt_format)
return timedelta
2020-03-05 22:51:21 +00:00
@env.parser_for("timedelta_validator")
def timedelta_parser(value):
try:
timedelta_validator(value)
return value
except ArgumentTypeError as e:
2020-03-05 22:51:21 +00:00
raise environs.EnvError(e)