| 158 | |
| 159 | |
| 160 | class FileStore: |
| 161 | # TODO - make this a CAS (index by object hash itself?) |
| 162 | # NOTE - currently we pass dir_path via the FileStore, could move into the file themselves? |
| 163 | def __init__(self, fw_klass: t.Type[FileEntry], assets_dir: t.Optional[Path] = None): |
| 164 | super().__init__() |
| 165 | self.fw_klass = fw_klass |
| 166 | self.files: t.List[FileEntry] = [] |
| 167 | self.dir_path = assets_dir |
| 168 | |
| 169 | def __add__(self, other: FileStore) -> Self: |
| 170 | # TODO - ensure factory is the same for both |
| 171 | self.files.extend(other.files) |
| 172 | return self |
| 173 | |
| 174 | @property |
| 175 | def store_count(self) -> int: |
| 176 | return len(self.files) |
| 177 | |
| 178 | @property |
| 179 | def file_list(self) -> t.List[t.BinaryIO]: |
| 180 | return [f.wrapped for f in self.files] |
| 181 | |
| 182 | def get_file(self, ext: str, mime: str) -> FileEntry: |
| 183 | return self.fw_klass(ext, mime, self.dir_path) |
| 184 | |
| 185 | def add_file(self, fw: FileEntry) -> None: |
| 186 | fw.freeze() |
| 187 | self.files.append(fw) |
| 188 | |
| 189 | def load_file(self, path: Path) -> FileEntry: |
| 190 | """load a file into the store (makes a copy)""" |
| 191 | # TODO - ideally lazily-link a path to the store (rather than copy it in) |
| 192 | ext = "".join(path.suffixes) |
| 193 | dest_obj = self.fw_klass(ext=ext, dir_path=self.dir_path) |
| 194 | with path.open("rb") as src_obj: |
| 195 | copyfileobj(src_obj, dest_obj.file) |
| 196 | self.add_file(dest_obj) |
| 197 | return dest_obj |
| 198 | |
| 199 | def as_dict(self) -> dict: |
| 200 | """Build a json structure suitable for embedding in a html file, json-rpc response, etc.""" |
| 201 | x: FileEntry # noqa: F842 |
| 202 | return {x.hash: x.as_dict() for x in self.files} |
| 203 | |
| 204 | def get_entry(self, hash: str) -> t.Optional[FileEntry]: |
| 205 | # TODO - change self.files to a dict[hash, FileEntry]? |
| 206 | return next((f for f in self.files if f.hash == hash), None) |
no outgoing calls
no test coverage detected