Changeset - 992c91fc90de
[Not reviewed]
0 1 0
Brett Smith - 7 years ago 2017-06-08 16:12:49
brettcsmith@brettcsmith.org
config: Nicer implementation of date parsing.

Keeps less local state through the function, to reduce the risk of that
state getting inconsistent.
1 file changed with 10 insertions and 19 deletions:
0 comments (0 inline, 0 general)
oxrlib/config.py
Show inline comments
...
 
@@ -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):
0 comments (0 inline, 0 general)