|
| 1 | +""" |
| 2 | +SemanticVersion definition that is based on the Semantiv Versioning Specification [semver](https://semver.org/). |
| 3 | +""" |
| 4 | + |
| 5 | +from typing import Any, Callable |
| 6 | + |
| 7 | +from pydantic import GetJsonSchemaHandler |
| 8 | +from pydantic.json_schema import JsonSchemaValue |
| 9 | +from pydantic_core import core_schema |
| 10 | + |
| 11 | +try: |
| 12 | + import semver |
| 13 | +except ModuleNotFoundError as e: # pragma: no cover |
| 14 | + raise RuntimeError( |
| 15 | + 'The `semantic_version` module requires "semver" to be installed. You can install it with "pip install semver".' |
| 16 | + ) from e |
| 17 | + |
| 18 | + |
| 19 | +class SemanticVersion: |
| 20 | + """ |
| 21 | + Semantic version based on the official [semver thread](https://python-semver.readthedocs.io/en/latest/advanced/combine-pydantic-and-semver.html). |
| 22 | + """ |
| 23 | + |
| 24 | + @classmethod |
| 25 | + def __get_pydantic_core_schema__( |
| 26 | + cls, |
| 27 | + _source_type: Any, |
| 28 | + _handler: Callable[[Any], core_schema.CoreSchema], |
| 29 | + ) -> core_schema.CoreSchema: |
| 30 | + def validate_from_str(value: str) -> semver.Version: |
| 31 | + return semver.Version.parse(value) |
| 32 | + |
| 33 | + from_str_schema = core_schema.chain_schema( |
| 34 | + [ |
| 35 | + core_schema.str_schema(), |
| 36 | + core_schema.no_info_plain_validator_function(validate_from_str), |
| 37 | + ] |
| 38 | + ) |
| 39 | + |
| 40 | + return core_schema.json_or_python_schema( |
| 41 | + json_schema=from_str_schema, |
| 42 | + python_schema=core_schema.union_schema( |
| 43 | + [ |
| 44 | + core_schema.is_instance_schema(semver.Version), |
| 45 | + from_str_schema, |
| 46 | + ] |
| 47 | + ), |
| 48 | + serialization=core_schema.to_string_ser_schema(), |
| 49 | + ) |
| 50 | + |
| 51 | + @classmethod |
| 52 | + def __get_pydantic_json_schema__( |
| 53 | + cls, _core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler |
| 54 | + ) -> JsonSchemaValue: |
| 55 | + return handler(core_schema.str_schema()) |
0 commit comments