Coverage for collectra/commons/files.py: 94.20%
69 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
1import uuid
2from pathlib import Path
4import pydantic
6from ..types.base import load_artefact
7from ..utils import write_yaml
8from .results import Results, pop_header, put_header
10# The header used to be called this; the name still works.
11CollectraResultsMetadata = Results
14class CollectraFile(pydantic.BaseModel):
15 collectra_file_path: Path
16 collectra_results_metadata: CollectraResultsMetadata
17 data: dict
18 assets: dict[str, Path] = dict()
19 cleanup_on_save_failure: bool = False
21 def __getitem__(self, key):
22 item = self.data[key]
23 return item
25 def __contains__(self, key):
26 return key in self.data
28 @property
29 def results_path(self) -> Path:
30 """Return the canonical results file for this Collectra directory."""
31 return self.collectra_file_path / "results.yaml"
33 def model_dump(self, *args, **kwargs) -> dict:
34 """What is written to results.yaml: the header, then each node."""
35 data = super().model_dump(*args, **kwargs)["data"]
36 nodes = {
37 key: (
38 value
39 if not isinstance(value, list)
40 else value[0] if len(value) == 1 else value
41 )
42 for key, value in data.items()
43 }
44 return put_header(self.collectra_results_metadata, nodes)
46 @classmethod
47 def from_data(cls, collectra_file_path: Path | str):
48 import yaml
50 collectra_file_path = Path(collectra_file_path)
51 results_yaml = collectra_file_path / "results.yaml"
52 if not results_yaml.exists():
53 raise FileNotFoundError(f"results.yaml not found in {collectra_file_path}")
54 with open(results_yaml, "r") as f:
55 data = yaml.safe_load(f) or {}
56 if not isinstance(data, dict):
57 raise ValueError(f"Invalid results data in {results_yaml}")
58 metadata = pop_header(data, source=results_yaml)
59 return cls(
60 collectra_file_path=collectra_file_path,
61 collectra_results_metadata=metadata,
62 data=data,
63 )
65 @classmethod
66 def from_file(
67 cls,
68 file: Path,
69 label: str,
70 ext: str,
71 output: Path | None = None,
72 force: bool = False,
73 **kwargs,
74 ):
75 ext = ext.lstrip(".")
76 collectra_file_path = file.with_suffix(f".{ext}")
77 if output:
78 collectra_file_path = output / collectra_file_path.name
79 directory_existed = collectra_file_path.exists()
80 if directory_existed and not force:
81 raise FileExistsError(
82 f"File {collectra_file_path} already exists. To overwrite, use -f or --force option."
83 )
84 else:
85 collectra_file_path.mkdir(parents=True, exist_ok=True)
86 partition = kwargs.get("partition", None)
87 metadata = CollectraResultsMetadata(partition=partition)
88 new_data = {
89 f"{label}": {
90 "id": f"{label}",
91 "type": "collectra.Image",
92 "data": str(file.name),
93 }
94 }
95 return cls(
96 collectra_file_path=collectra_file_path,
97 collectra_results_metadata=metadata,
98 data=new_data,
99 assets={file.name: Path(file)},
100 cleanup_on_save_failure=not directory_existed,
101 )
103 def save(self):
104 import copy
105 import shutil
107 collectra_file_path = self.collectra_file_path
108 assets = copy.deepcopy(self.assets)
109 data = self.model_dump()
110 try:
111 for asset_name, asset_path in assets.items():
112 if not asset_path.exists():
113 raise FileNotFoundError(f"Asset file {asset_path} not found.")
114 shutil.copy(asset_path, collectra_file_path / asset_name)
115 write_yaml(data, self.results_path)
116 self.cleanup_on_save_failure = False
117 except Exception as e:
118 if self.cleanup_on_save_failure:
119 shutil.rmtree(collectra_file_path, ignore_errors=True)
120 raise RuntimeError(f"Failed to save Collectra file: {e}")