Source code for ewoksmx.models.edml.common
import pathlib
from typing import Any
import xmltodict
from pydantic import BaseModel
from pydantic import ConfigDict
from pydantic import model_validator
[docs]
class XSData(BaseModel):
model_config = ConfigDict(extra="ignore", populate_by_name=True)
[docs]
def to_xml_file(self, file_path: pathlib.Path) -> None:
with open(file_path, mode="w") as fh:
fh.write(self.to_xml_string())
[docs]
@classmethod
def from_xml_file(cls, file_path: pathlib.Path) -> "XSData":
with open(file_path, mode="r") as fh:
return cls.from_xml_string(fh.read())
[docs]
def to_xml_string(self) -> str:
return self._edml_dict_to_xml_string(self.to_edml_dict())
[docs]
@classmethod
def from_xml_string(cls, xml_string: str) -> "XSData":
return cls.from_edml_dict(cls._xml_string_to_edml_dict(xml_string))
[docs]
def to_edml_dict(self) -> dict:
return self.model_dump(by_alias=False, exclude_none=True)
[docs]
@classmethod
def from_edml_dict(cls, edml_dict: dict) -> "XSData":
return cls(**edml_dict)
@classmethod
def _xml_string_to_edml_dict(cls, xml_string: str) -> dict:
data = xmltodict.parse(xml_string)[cls.__name__]
if data is None:
return {}
return data
@classmethod
def _edml_dict_to_xml_string(cls, edml_dict: dict) -> str:
return xmltodict.unparse({cls.__name__: edml_dict}, pretty=True, indent=2)
class _XSCommonBasicType(XSData):
@model_validator(mode="before")
@classmethod
def parse(cls, value: Any) -> Any:
if not isinstance(value, dict):
return {"value": value}
return value
[docs]
class XSDataBoolean(_XSCommonBasicType):
value: bool
[docs]
class XSDataFloat(_XSCommonBasicType):
value: float
[docs]
class XSDataInteger(_XSCommonBasicType):
value: int
[docs]
class XSDataString(_XSCommonBasicType):
value: str
[docs]
class XSDataRange(XSData):
begin: int
end: int
[docs]
@model_validator(mode="before")
@classmethod
def parse(cls, value: Any) -> Any:
if isinstance(value, (tuple, list)) and len(value) == 2:
return {"begin": value[0], "end": value[1]}
return value
[docs]
class XSDataFile(XSData):
path: XSDataString
[docs]
@model_validator(mode="before")
@classmethod
def parse(cls, value: Any) -> Any:
if isinstance(value, (str, pathlib.Path)):
return {"path": str(value)}
return value