2020-06-29 23:17:38 -06:00
|
|
|
# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
|
2021-03-03 22:12:11 -09:00
|
|
|
# or more contributor license agreements. Licensed under the Elastic License
|
|
|
|
|
# 2.0; you may not use this file except in compliance with the Elastic License
|
|
|
|
|
# 2.0.
|
2020-06-29 23:17:38 -06:00
|
|
|
|
|
|
|
|
"""Helper functionality for comparing semantic versions."""
|
|
|
|
|
import re
|
2021-03-09 13:30:12 -09:00
|
|
|
from typing import Iterable, Union
|
2020-06-29 23:17:38 -06:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class Version(tuple):
|
|
|
|
|
|
2022-01-25 18:11:59 -09:00
|
|
|
def __new__(cls, version: Union[str, Iterable]) -> 'Version':
|
|
|
|
|
if isinstance(version, (int, list, tuple)):
|
|
|
|
|
version_class = tuple.__new__(cls, version)
|
|
|
|
|
else:
|
|
|
|
|
version_tuple = tuple(int(a) if a.isdigit() else a for a in re.split(r'[.-]', version))
|
|
|
|
|
version_class = tuple.__new__(cls, version_tuple)
|
2020-06-29 23:17:38 -06:00
|
|
|
|
2022-01-25 18:11:59 -09:00
|
|
|
return version_class
|
2020-06-29 23:17:38 -06:00
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
|
"""Convert back to a string."""
|
2022-01-25 18:11:59 -09:00
|
|
|
recovered_str = str(self[0])
|
|
|
|
|
for additional in self[1:]:
|
|
|
|
|
if isinstance(additional, str):
|
|
|
|
|
recovered_str += "-" + additional
|
|
|
|
|
else:
|
|
|
|
|
recovered_str += "." + str(additional)
|
|
|
|
|
|
|
|
|
|
return recovered_str
|
2022-09-19 09:53:30 -06:00
|
|
|
|
2022-12-08 15:49:49 -05:00
|
|
|
def bump(self, major: bool = False, minor: bool = False, patch: bool = False) -> 'Version':
|
|
|
|
|
"""Increment the version."""
|
|
|
|
|
versions = list(self)
|
|
|
|
|
if major:
|
|
|
|
|
versions[0] += 1
|
|
|
|
|
if minor:
|
|
|
|
|
versions[1] += 1
|
|
|
|
|
if patch and len(versions) > 2:
|
|
|
|
|
versions[-1] += 1
|
|
|
|
|
elif patch and len(versions) == 2:
|
|
|
|
|
versions.append(1)
|
|
|
|
|
return Version(versions)
|
|
|
|
|
|
2022-09-19 09:53:30 -06:00
|
|
|
|
|
|
|
|
def max_versions(*versions: str) -> str:
|
|
|
|
|
"""Return the max versioned string."""
|
|
|
|
|
return str(max([Version(v) for v in versions]))
|