Skip to content

Instantly share code, notes, and snippets.

@jehiah
Created April 10, 2017 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jehiah/4c774b0c07786bf4e9bda18d536c20d1 to your computer and use it in GitHub Desktop.
Save jehiah/4c774b0c07786bf4e9bda18d536c20d1 to your computer and use it in GitHub Desktop.
Semver 2.0.0 compatible version comparison w/o regexes
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