From 992c91fc90de3d71b56f6beff491f0b204b54556 Mon Sep 17 00:00:00 2001 From: Brett Smith Date: Thu, 8 Jun 2017 12:07:21 -0400 Subject: [PATCH] config: Nicer implementation of date parsing. Keeps less local state through the function, to reduce the risk of that state getting inconsistent. --- oxrlib/config.py | 29 ++++++++++------------------- 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/oxrlib/config.py b/oxrlib/config.py index b4974a1..6df9389 100644 --- a/oxrlib/config.py +++ b/oxrlib/config.py @@ -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):