|
| 1 | +import pathlib |
| 2 | +import subprocess |
| 3 | +import tempfile |
| 4 | + |
| 5 | +from typing import Optional, Union |
| 6 | + |
| 7 | +from rdflib import Graph |
| 8 | + |
| 9 | +from esmf_aspect_meta_model_python.samm_cli import SammCli |
| 10 | + |
| 11 | + |
| 12 | +class AdaptiveGraph(Graph): # TODO: avoid double parse when upgrading |
| 13 | + """An RDF graph that can adaptively upgrade SAMM files using the SAMM CLI.""" |
| 14 | + |
| 15 | + _samm_namespace_prefix = "samm" # TODO: take out to a common place |
| 16 | + _samm_org_identifier = "org.eclipse.esmf.samm" |
| 17 | + |
| 18 | + def __init__(self, samm_version: str | None = None, *args, **kwargs) -> None: |
| 19 | + super().__init__(*args, **kwargs) |
| 20 | + |
| 21 | + self._samm_version = samm_version |
| 22 | + self._samm_cli = SammCli() |
| 23 | + |
| 24 | + def _upgrade_ttl_file(self, file_path: pathlib.Path) -> str: |
| 25 | + """Run SAMM CLI prettyprint to upgrade a TTL file to the latest version.""" |
| 26 | + try: |
| 27 | + return self._samm_cli.prettyprint(str(file_path), capture=True) |
| 28 | + except subprocess.CalledProcessError as e: |
| 29 | + raise RuntimeError(f"SAMM CLI failed for {file_path}:\n{e.stdout}\n{e.stderr}") from e |
| 30 | + |
| 31 | + def _has_version_mismatch_in_graph(self, input_source: str | bytes | pathlib.PurePath) -> bool: |
| 32 | + """Parse into a temporary graph to detect mismatch BEFORE loading into self.""" |
| 33 | + temp_graph = Graph() |
| 34 | + |
| 35 | + if isinstance(input_source, pathlib.Path): |
| 36 | + temp_graph.parse(input_source) |
| 37 | + else: |
| 38 | + temp_graph.parse(data=input_source, format="ttl") # type: ignore[arg-type] |
| 39 | + |
| 40 | + for prefix, namespace in temp_graph.namespace_manager.namespaces(): |
| 41 | + if prefix.startswith(self._samm_namespace_prefix): |
| 42 | + parts = namespace.strip("#").split(":") |
| 43 | + if len(parts) >= 5 and parts[2] == self._samm_org_identifier: |
| 44 | + version = parts[-1] |
| 45 | + if version != self._samm_version: |
| 46 | + return True |
| 47 | + return False |
| 48 | + |
| 49 | + def _upgrade_source(self, source: str | pathlib.PurePath) -> str: |
| 50 | + source_path = pathlib.Path(source) |
| 51 | + |
| 52 | + print(f"[INFO] SAMM version mismatch detected in {source_path}. Upgrading...") |
| 53 | + |
| 54 | + return self._upgrade_ttl_file(source_path) |
| 55 | + |
| 56 | + def _upgrade_data(self, data: str | bytes) -> str: |
| 57 | + print( # TODO: improve logging |
| 58 | + f"[INFO] SAMM version mismatch detected in provided data (target v{self._samm_version}) Upgrading..." |
| 59 | + ) |
| 60 | + |
| 61 | + with tempfile.NamedTemporaryFile("wb", suffix=".ttl", delete=False) as tmp: |
| 62 | + tmp.write(data.encode("utf-8") if isinstance(data, str) else data) |
| 63 | + tmp_path = pathlib.Path(tmp.name) |
| 64 | + |
| 65 | + try: |
| 66 | + return self._upgrade_ttl_file(tmp_path) |
| 67 | + finally: |
| 68 | + tmp_path.unlink(missing_ok=True) |
| 69 | + |
| 70 | + def set_samm_version(self, samm_version: str | None) -> None: |
| 71 | + """Set the SAMM version for this graph.""" |
| 72 | + self._samm_version = samm_version |
| 73 | + |
| 74 | + def parse( # type: ignore[override] |
| 75 | + self, |
| 76 | + *, |
| 77 | + source: Optional[pathlib.PurePath] = None, |
| 78 | + data: Optional[str | bytes] = None, |
| 79 | + **kwargs, |
| 80 | + ) -> "AdaptiveGraph": |
| 81 | + """ |
| 82 | + Parse a TTL file into this graph, upgrading via SAMM CLI if version mismatch detected. |
| 83 | +
|
| 84 | + If a SAMM version mismatch is detected, the TTL file will be upgraded using the SAMM CLI prettyprint |
| 85 | + before parsing into this graph. |
| 86 | +
|
| 87 | + Args: |
| 88 | + source: Path to the TTL file as pathlib.Path. |
| 89 | + data: RDF content as string or bytes. |
| 90 | + *args, **kwargs: Additional arguments passed to rdflib.Graph.parse(). |
| 91 | +
|
| 92 | + Returns: |
| 93 | + self (AdaptiveGraph): The current graph instance with parsed data. |
| 94 | +
|
| 95 | + Raises: |
| 96 | + RuntimeError: If the SAMM CLI fails during the upgrade process. |
| 97 | + ValueError: If neither 'source' nor 'data' is provided, or if SAMM version is not set. |
| 98 | + """ |
| 99 | + if (source is None) == (data is None): |
| 100 | + raise ValueError("Either 'source' or 'data' must be provided.") |
| 101 | + if not self._samm_version: |
| 102 | + raise ValueError("SAMM version is not set.") |
| 103 | + |
| 104 | + if self._has_version_mismatch_in_graph(input_source=data or pathlib.Path(source)): # type: ignore[arg-type] |
| 105 | + data = self._upgrade_data(data) if data else self._upgrade_source(source) # type: ignore[arg-type] |
| 106 | + source = None |
| 107 | + |
| 108 | + super().parse(source=source, data=data, **kwargs) |
| 109 | + |
| 110 | + return self |
| 111 | + |
| 112 | + def __add__(self, other: Union["Graph", "AdaptiveGraph"]) -> "AdaptiveGraph": |
| 113 | + """Override addition to propagate SAMM version to the resulting graph.""" |
| 114 | + retval = super().__add__(other) |
| 115 | + |
| 116 | + if isinstance(retval, AdaptiveGraph): |
| 117 | + if isinstance(other, AdaptiveGraph) and other._samm_version != self._samm_version: |
| 118 | + raise ValueError("SAMM version mismatch during addition.") |
| 119 | + |
| 120 | + retval.set_samm_version(self._samm_version) |
| 121 | + |
| 122 | + return retval # type: ignore[return-value] |
| 123 | + |
| 124 | + def __sub__(self, other: Union["Graph", "AdaptiveGraph"]) -> "AdaptiveGraph": |
| 125 | + """Override subtraction to propagate SAMM version to the resulting graph.""" |
| 126 | + retval = super().__sub__(other) |
| 127 | + |
| 128 | + if isinstance(retval, AdaptiveGraph): |
| 129 | + if isinstance(other, AdaptiveGraph) and other._samm_version != self._samm_version: |
| 130 | + raise ValueError("SAMM version mismatch during subtraction.") |
| 131 | + |
| 132 | + retval.set_samm_version(self._samm_version) |
| 133 | + |
| 134 | + return retval # type: ignore[return-value] |
| 135 | + |
| 136 | + def __mul__(self, other: Union["Graph", "AdaptiveGraph"]) -> "AdaptiveGraph": |
| 137 | + """Override multiplication to propagate SAMM version to the resulting graph.""" |
| 138 | + retval = super().__mul__(other) |
| 139 | + |
| 140 | + if isinstance(retval, AdaptiveGraph): |
| 141 | + if isinstance(other, AdaptiveGraph) and other._samm_version != self._samm_version: |
| 142 | + raise ValueError("SAMM version mismatch during multiplication.") |
| 143 | + |
| 144 | + retval.set_samm_version(self._samm_version) |
| 145 | + |
| 146 | + return retval # type: ignore[return-value] |
0 commit comments