Skip to content

Commit

Permalink
Beefed up the SemanticVersion type
Browse files Browse the repository at this point in the history
Co-authored-by: Shyam Dwaraknath <[email protected]>
  • Loading branch information
ml-evs and shyamd committed Jun 25, 2020
1 parent ff19d2a commit 993ea7d
Showing 1 changed file with 42 additions and 5 deletions.
47 changes: 42 additions & 5 deletions optimade/models/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,63 @@ class SemanticVersion(str):
"""

regex = re.compile(
r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$"
)

@classmethod
def __get_validators__(cls):
yield cls.validate

@classmethod
def __modify_schema__(cls, field_schema):
field_schema.update(
pattern=r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$",
pattern=cls.regex.pattern,
examples=["0.10.1", "1.0.0-rc.2", "1.2.3-rc.5+develop"],
)

@classmethod
def validate(cls, v: str):
regexp = re.compile(
r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$"
)
if not regexp.match(v):
if not cls.regex.match(v):
raise ValueError(f"Unable to validate version {v} as a semver.")

return v

@property
def _match(self):
""" The result of the regex match. """
return self.regex.match(self)

@property
def major(self) -> int:
""" The major version number. """
return int(self._match.group(1))

@property
def minor(self) -> int:
""" The minor version number. """
return int(self._match.group(2))

@property
def patch(self) -> int:
""" The patch version number. """
return int(self._match.group(3))

@property
def prerelease(self) -> str:
""" The pre-release tag. """
return self._match.group(4)

@property
def build_metadata(self) -> str:
""" The build metadata. """
return self._match.group(5)

@property
def base_version(self) -> str:
""" The base version string without patch and metadata info. """
return f"{self.major}.{self.minor}.{self.patch}"


EXTRA_SYMBOLS = ["X", "vacancy"]

Expand Down

0 comments on commit 993ea7d

Please sign in to comment.