66 lines
1.8 KiB
Python
Raw Normal View History

2012-02-07 14:57:46 +02:00
# -*- coding: utf-8 -*-
import re
_REGEX = re.compile('^(?P<major>[0-9]+)'
'\.(?P<minor>[0-9]+)'
'\.(?P<patch>[0-9]+)'
'(\-(?P<prerelease>[0-9A-Za-z]+(\.[0-9A-Za-z]+)*))?'
'(\+(?P<build>[0-9A-Za-z]+(\.[0-9A-Za-z]+)*))?$')
2012-02-07 14:57:46 +02:00
def parse(version):
"""
Parse version to major, minor, patch, pre-release, build parts.
"""
match = _REGEX.match(version)
2012-02-07 14:57:46 +02:00
if match is None:
raise ValueError('%s is not valid SemVer string' % version)
2012-02-08 16:07:11 +04:00
verinfo = match.groupdict()
2012-02-08 16:07:11 +04:00
verinfo['major'] = int(verinfo['major'])
verinfo['minor'] = int(verinfo['minor'])
verinfo['patch'] = int(verinfo['patch'])
2012-02-07 14:57:46 +02:00
return verinfo
2012-02-07 14:57:46 +02:00
def compare(ver1, ver2):
def compare_by_keys(d1, d2, keys):
for key in keys:
v = cmp(d1.get(key), d2.get(key))
if v != 0:
return v
return 0
v1, v2 = parse(ver1), parse(ver2)
return compare_by_keys(
v1, v2, ['major', 'minor', 'patch', 'prerelease', 'build'])
def match(version, match_expr):
prefix = match_expr[:2]
if prefix in ('>=', '<=', '=='):
match_version = match_expr[2:]
elif prefix and prefix[0] in ('>', '<', '='):
2012-02-07 14:57:46 +02:00
prefix = prefix[0]
match_version = match_expr[1:]
else:
2012-02-08 16:07:11 +04:00
raise ValueError("match_expr parameter should be in format <op><ver>, "
"where <op> is one of ['<', '>', '==', '<=', '>=']. "
"You provided: %r" % match_expr)
2012-02-07 14:57:46 +02:00
possibilities_dict = {
'>': (1,),
'<': (-1,),
'==': (0,),
'>=': (0, 1),
2012-02-08 16:07:11 +04:00
'<=': (-1, 0)
}
2012-02-07 14:57:46 +02:00
possibilities = possibilities_dict[prefix]
cmp_res = compare(version, match_version)
2012-02-08 16:07:11 +04:00
return cmp_res in possibilities