docker-tidy/dockertidy/parser.py

55 lines
1.2 KiB
Python
Raw 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):
"""
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(f"'{value}' is not a valid timedelta string")
2020-03-15 13:50:58 +00:00
return value
2020-03-05 22:51:21 +00:00
2020-03-09 00:05:17 +00:00
def timedelta(value, dt_format=None):
"""
Return the :class:`datetime.datetime.DateTime` 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-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-15 13:50:58 +00:00
)
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:
raise environs.EnvError(e) from e