Created
April 10, 2017 14:18
-
-
Save jehiah/4c774b0c07786bf4e9bda18d536c20d1 to your computer and use it in GitHub Desktop.
Semver 2.0.0 compatible version comparison w/o regexes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def compare(a, b): | |
""" | |
Compare two version strings. | |
:return -1, 0, 1 | |
:rtype: int | |
""" | |
a = map(_cast_int, a.split('+', 2)[0].split('.')) | |
b = map(_cast_int, b.split('+', 2)[0].split('.')) | |
c = _cmp_range(a[:3], b[:3]) | |
if c != 0: | |
return c | |
c = _cmp_range(a[3:], b[3:], flip=True) | |
if c != 0: | |
return c | |
if not a[3:]: | |
return 1 | |
if not b[3:]: | |
return -1 | |
return c | |
def _cmp_range(a, b, flip=False): | |
for i in range(min(len(a), len(b))): | |
aa = a[i] | |
bb = b[i] | |
c = _compare_item(aa, bb, flip) | |
if c == 0: | |
continue | |
return c | |
return cmp(len(a), len(b)) | |
def _cast_int(a): | |
try: | |
return int(a) | |
except: | |
return a | |
def _compare_item(a, b, flip=False): | |
if isinstance(a, int) and isinstance(b, int): | |
return cmp(a, b) | |
elif isinstance(a, int): | |
return -1 if flip else 1 | |
elif isinstance(b, int): | |
return 1 if flip else -1 | |
else: | |
return cmp(a, b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment