version: precompile regexes in Version constructor

This commit is contained in:
Todd Gamblin 2021-02-06 00:22:46 -08:00 committed by Massimiliano Culpo
parent e3e913ef8f
commit c81ca37dfc

View file

@ -37,7 +37,10 @@
__all__ = ['Version', 'VersionRange', 'VersionList', 'ver'] __all__ = ['Version', 'VersionRange', 'VersionList', 'ver']
# Valid version characters # Valid version characters
VALID_VERSION = r'[A-Za-z0-9_.-]' VALID_VERSION = re.compile(r'[A-Za-z0-9_.-]')
# regex for version segments
SEGMENT_REGEX = re.compile(r'[a-zA-Z]+|[0-9]+')
# Infinity-like versions. The order in the list implies the comparison rules # Infinity-like versions. The order in the list implies the comparison rules
infinity_versions = ['develop', 'main', 'master', 'head', 'trunk'] infinity_versions = ['develop', 'main', 'master', 'head', 'trunk']
@ -97,9 +100,10 @@ class Version(object):
"""Class to represent versions""" """Class to represent versions"""
def __init__(self, string): def __init__(self, string):
if not isinstance(string, str):
string = str(string) string = str(string)
if not re.match(VALID_VERSION, string): if not VALID_VERSION.match(string):
raise ValueError("Bad characters in version string: %s" % string) raise ValueError("Bad characters in version string: %s" % string)
# preserve the original string, but trimmed. # preserve the original string, but trimmed.
@ -107,12 +111,11 @@ def __init__(self, string):
self.string = string self.string = string
# Split version into alphabetical and numeric segments # Split version into alphabetical and numeric segments
segment_regex = r'[a-zA-Z]+|[0-9]+' segments = SEGMENT_REGEX.findall(string)
segments = re.findall(segment_regex, string)
self.version = tuple(int_if_int(seg) for seg in segments) self.version = tuple(int_if_int(seg) for seg in segments)
# Store the separators from the original version string as well. # Store the separators from the original version string as well.
self.separators = tuple(re.split(segment_regex, string)[1:]) self.separators = tuple(SEGMENT_REGEX.split(string)[1:])
@property @property
def dotted(self): def dotted(self):