From 7e942cdd4ad1a3d425c503ebd91445d4b0824059 Mon Sep 17 00:00:00 2001 From: Sergei Trofimov <sergei.trofimov@arm.com> Date: Wed, 13 Jun 2018 17:09:02 +0100 Subject: [PATCH] utils/types: add regex types Add types for regex and bytes_regex. In Python 3, regular expression objects differ based on whether they were created with a str or a bytes instance as the pattern, and can only match against instances of the corresponding type. To make sure we always end up using the right version (e.g. pexpect needs bytes regexes), create functions to do the appropriate conversions. --- devlib/utils/types.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/devlib/utils/types.py b/devlib/utils/types.py index abc50b9..d3c09e9 100644 --- a/devlib/utils/types.py +++ b/devlib/utils/types.py @@ -26,6 +26,7 @@ is not the best language to use for configuration. """ import math +import sys from functools import total_ordering from past.builtins import basestring @@ -124,3 +125,38 @@ def bitmask(value): if not isinstance(value, int): raise ValueError(value) return value + + +regex_type = type(re.compile('')) + + +if sys.version_info[0] == 3: + def regex(value): + if isinstance(value, regex_type): + if isinstance(value.pattern, str): + return value + return re.compile(value.pattern.decode()) + else: + if isinstance(value, bytes): + value = value.decode() + return re.compile(value) + + + def bytes_regex(value): + if isinstance(value, regex_type): + if isinstance(value.pattern, bytes): + return value + return re.compile(value.pattern.encode(sys.stdout.encoding)) + else: + if isinstance(value, str): + value = value.encode(sys.stdout.encoding) + return re.compile(value) +else: + def regex(value): + if isinstance(value, regex_type): + return value + else: + return re.compile(value) + + + bytes_regex = regex