config: Nicer implementation of date parsing.

Keeps less local state through the function, to reduce the risk of that
state getting inconsistent.
This commit is contained in:
Brett Smith 2017-06-08 12:07:21 -04:00
parent 385a492ae7
commit 992c91fc90

View file

@ -48,27 +48,18 @@ class Configuration:
post_hook()
def _date_from_s(self, s):
number_digits = [[]]
clean_s = s.strip()
numbers = []
seen_seps = set()
bad_c = False
for c in s.strip():
if c.isdigit():
number_digits[-1].append(c)
elif c in self.DATE_SEPS:
seen_seps.add(c)
number_digits.append([])
else:
bad_c = True
numbers = [int(''.join(digit_list), 10) for digit_list in number_digits]
if bad_c or (len(numbers) > 3) or (len(seen_seps) > 1):
start_index = 0
for index, c in (pair for pair in enumerate(clean_s) if pair[1] in self.DATE_SEPS):
seen_seps.add(c)
numbers.append(int(clean_s[start_index:index], 10))
start_index = index + 1
numbers.append(int(clean_s[start_index:], 10))
if (len(numbers) > 3) or (len(seen_seps) > 1):
raise ValueError("can't parse date from {!r}".format(s))
replacements = {}
try:
replacements['day'] = numbers[-1]
replacements['month'] = numbers[-2]
replacements['year'] = numbers[-3]
except IndexError:
pass
replacements = dict(zip(['day', 'month', 'year'], reversed(numbers)))
return self.TODAY.replace(**replacements)
def _build_argparser(self):