1
0
mirror of https://github.com/ARM-software/devlib.git synced 2025-01-31 02:00:45 +00:00

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.
This commit is contained in:
Sergei Trofimov 2018-06-13 17:09:02 +01:00 committed by setrofim
parent 41f460afbe
commit 7e942cdd4a

View File

@ -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