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