-
Notifications
You must be signed in to change notification settings - Fork 6
Detect, Validate & Upgrade SAMM files via CLI prettyprint #60
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
0790810
Add SAMM version validation to SAMMGraph load_aspect_model
a264760
Refactor SAMM CLI, add archive extraction, update CI & version bump
22d4318
Add the capability to upgrade a .ttl file version using AdaptiveGraph
e1879a3
refactor: use default (latest) SAMM version and update tests
a4f9f59
upgrade SAMM CLI version from 2.11.1 to 2.12.0
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
131 changes: 131 additions & 0 deletions
131
core/esmf-aspect-meta-model-python/esmf_aspect_meta_model_python/adaptive_graph.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| import pathlib | ||
| import subprocess | ||
| import tempfile | ||
|
|
||
| from typing import Optional, Union | ||
|
|
||
| from rdflib import Graph | ||
|
|
||
| from esmf_aspect_meta_model_python import utils | ||
| from esmf_aspect_meta_model_python.constants import SAMM_VERSION | ||
| from esmf_aspect_meta_model_python.samm_cli import SammCli | ||
|
|
||
|
|
||
| class AdaptiveGraph(Graph): # TODO: avoid double parsing when an upgrade is not performed | ||
| """An RDF graph that can adaptively upgrade SAMM files using the SAMM CLI.""" | ||
|
|
||
| _samm_cli = SammCli() | ||
|
|
||
| def __init__(self, samm_version: str = SAMM_VERSION, *args, **kwargs) -> None: | ||
| super().__init__(*args, **kwargs) | ||
|
|
||
| self._samm_version = samm_version | ||
|
|
||
| def _upgrade_ttl_file(self, file_path: pathlib.Path) -> str: | ||
| """Run SAMM CLI prettyprint to upgrade a TTL file to the latest version.""" | ||
| try: | ||
| return self._samm_cli.prettyprint(str(file_path), capture=True) | ||
| except subprocess.CalledProcessError as e: | ||
| raise RuntimeError(f"SAMM CLI failed for {file_path}:\n{e.stdout}\n{e.stderr}") from e | ||
|
|
||
| def _upgrade_source(self, source_path: pathlib.Path) -> str: | ||
| print(f"[INFO] SAMM version mismatch detected in {source_path}. Upgrading...") | ||
|
|
||
| return self._upgrade_ttl_file(source_path) | ||
|
|
||
| def _upgrade_data(self, data: str | bytes) -> str: | ||
| print( # TODO: improve logging | ||
| f"[INFO] SAMM version mismatch detected in provided data (target v{self._samm_version}) Upgrading..." | ||
| ) | ||
|
|
||
| with tempfile.NamedTemporaryFile("wb", suffix=".ttl", delete=False) as tmp: | ||
| tmp.write(data.encode("utf-8") if isinstance(data, str) else data) | ||
| tmp_path = pathlib.Path(tmp.name) | ||
|
|
||
| try: | ||
| return self._upgrade_ttl_file(tmp_path) | ||
| finally: | ||
| tmp_path.unlink(missing_ok=True) | ||
|
|
||
| def set_samm_version(self, samm_version: str) -> None: | ||
| """Set the SAMM version for this graph.""" | ||
| self._samm_version = samm_version | ||
|
|
||
| def parse( # type: ignore[override] | ||
| self, | ||
| *, | ||
| source: Optional[str | pathlib.Path] = None, | ||
| data: Optional[str | bytes] = None, | ||
| **kwargs, | ||
| ) -> "AdaptiveGraph": | ||
| """ | ||
| Parse a TTL file into this graph, upgrading via SAMM CLI if version mismatch detected. | ||
|
|
||
| If a SAMM version mismatch is detected, the TTL file will be upgraded using the SAMM CLI prettyprint | ||
| before parsing into this graph. | ||
|
|
||
| Args: | ||
| source: Path to the TTL file as pathlib.Path or str. | ||
| data: RDF content as string or bytes. | ||
| **kwargs: Additional arguments passed to rdflib.Graph.parse(). | ||
|
|
||
| Returns: | ||
| self (AdaptiveGraph): The current graph instance with parsed data. | ||
|
|
||
| Raises: | ||
| RuntimeError: If the SAMM CLI fails during the upgrade process. | ||
| ValueError: If neither 'source' nor 'data' is provided, or if both are provided. | ||
| """ | ||
| if (source is None) == (data is None): | ||
| raise ValueError("Either 'source' or 'data' must be provided.") | ||
|
|
||
| if source: | ||
| input_source = source = pathlib.Path(source) | ||
| upgrade_method = self._upgrade_source | ||
| else: | ||
| input_source = data # type: ignore[assignment] | ||
| upgrade_method = self._upgrade_data # type: ignore[assignment] | ||
|
|
||
| if utils.has_version_mismatch_from_input(input_source, samm_version=self._samm_version): | ||
| data = upgrade_method(input_source) | ||
| source = None | ||
|
|
||
| super().parse(source=source, data=data, **kwargs) | ||
|
|
||
| return self | ||
|
|
||
| def __add__(self, other: Union["Graph", "AdaptiveGraph"]) -> "AdaptiveGraph": | ||
| """Override addition to propagate SAMM version to the resulting graph.""" | ||
| retval = super().__add__(other) | ||
|
|
||
| if isinstance(retval, AdaptiveGraph): | ||
| if isinstance(other, AdaptiveGraph) and other._samm_version != self._samm_version: | ||
| raise ValueError("SAMM version mismatch during addition.") | ||
|
|
||
| retval.set_samm_version(self._samm_version) | ||
|
|
||
| return retval # type: ignore[return-value] | ||
|
|
||
| def __sub__(self, other: Union["Graph", "AdaptiveGraph"]) -> "AdaptiveGraph": | ||
| """Override subtraction to propagate SAMM version to the resulting graph.""" | ||
| retval = super().__sub__(other) | ||
|
|
||
| if isinstance(retval, AdaptiveGraph): | ||
| if isinstance(other, AdaptiveGraph) and other._samm_version != self._samm_version: | ||
| raise ValueError("SAMM version mismatch during subtraction.") | ||
|
|
||
| retval.set_samm_version(self._samm_version) | ||
|
|
||
| return retval # type: ignore[return-value] | ||
|
|
||
| def __mul__(self, other: Union["Graph", "AdaptiveGraph"]) -> "AdaptiveGraph": | ||
| """Override multiplication to propagate SAMM version to the resulting graph.""" | ||
| retval = super().__mul__(other) | ||
|
|
||
| if isinstance(retval, AdaptiveGraph): | ||
| if isinstance(other, AdaptiveGraph) and other._samm_version != self._samm_version: | ||
| raise ValueError("SAMM version mismatch during multiplication.") | ||
|
|
||
| retval.set_samm_version(self._samm_version) | ||
|
|
||
| return retval # type: ignore[return-value] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Imact 0:
You can create a task in backlog to analyze and implement a logging.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
https://rb-tracker.bosch.com/tracker01/browse/RBS-27504
https://rb-tracker.bosch.com/tracker01/browse/RBS-27505