|
from __future__ import annotations |
|
import csv |
|
from pathlib import Path |
|
import threading |
|
from typing import Any, Protocol, runtime_checkable |
|
|
|
|
|
@runtime_checkable |
|
class Hashable(Protocol): |
|
def to_dict(self) -> dict: ... |
|
def column_names(self) -> list[str]: ... |
|
def get(self, key: str) -> str | None: ... |
|
def __getitem__(self, key: str) -> str: ... |
|
def __setitem__(self, key: str, value: Any) -> None: ... |
|
def __contains__(self, key: str) -> bool: ... |
|
|
|
@classmethod |
|
def from_dict(cls, data: dict) -> Hashable: ... |
|
|
|
|
|
class MetadataItem(Hashable): |
|
def __init__(self, **kwargs) -> None: |
|
self.data = kwargs |
|
|
|
def get(self, key: str) -> str | None: |
|
return self.data.get(key, None) |
|
|
|
def to_dict(self) -> dict: |
|
return self.data |
|
|
|
def column_names(self) -> list[str]: |
|
return list(self.data.keys()) |
|
|
|
@classmethod |
|
def from_dict(cls, data: dict) -> MetadataItem: |
|
return cls(**data) |
|
|
|
def __getitem__(self, key: str) -> str: |
|
return self.data[key] |
|
|
|
def __setitem__(self, key: str, value: str | float) -> None: |
|
self.data[key] = value |
|
|
|
def __contains__(self, key: str) -> bool: |
|
return key in self.data |
|
|
|
|
|
class LockedMetadata: |
|
def __init__( |
|
self, |
|
key_field: str, |
|
existing: list[Hashable] | None = None, |
|
) -> None: |
|
self.key_field = key_field |
|
self.lock = threading.Lock() |
|
existing = existing or [] |
|
self.metadata: dict[str, Hashable] = {} |
|
|
|
for item in existing: |
|
if not isinstance(item, Hashable): |
|
raise TypeError(f"Item must be of type {Hashable.__name__}, got {type(item).__name__}.") |
|
|
|
key = item.get(self.key_field) |
|
|
|
if key is None: |
|
raise ValueError(f"Item must have a '{self.key_field}' field.") |
|
|
|
self.metadata[key] = item |
|
|
|
def add(self, item: Hashable) -> Hashable | None: |
|
replaced: Hashable | None = None |
|
|
|
with self.lock: |
|
key = item.get(self.key_field) |
|
|
|
if key is None: |
|
raise ValueError(f"Item must have a '{self.key_field}' field.") |
|
|
|
if key in self.metadata: |
|
replaced = self.metadata[key] |
|
|
|
self.metadata[key] = item |
|
|
|
return replaced |
|
|
|
def get(self, key: str) -> Hashable | None: |
|
with self.lock: |
|
return self.metadata.get(key, None) |
|
|
|
def __contains__(self, item: str) -> bool: |
|
with self.lock: |
|
return item in self.metadata |
|
|
|
def __iter__(self): |
|
with self.lock: |
|
return iter(self.metadata.values()) |
|
|
|
def save(self, file: Path) -> None: |
|
with self.lock: |
|
items = list(self.metadata.values()) |
|
|
|
if not items: |
|
return |
|
|
|
item = items[0] |
|
|
|
with open(file, 'w', newline='', encoding='utf-8') as f: |
|
writer = csv.DictWriter(f, fieldnames=item.column_names()) |
|
writer.writeheader() |
|
writer.writerows([item.to_dict() for item in items]) |
|
|
|
@classmethod |
|
def load( |
|
cls, |
|
file: Path, |
|
key_field: str, |
|
item_type: type[Hashable] = MetadataItem, |
|
) -> LockedMetadata: |
|
items = [] |
|
|
|
with open(file, 'r', newline='', encoding='utf-8') as f: |
|
reader = csv.DictReader(f) |
|
|
|
for row in reader: |
|
items.append(item_type.from_dict(row)) |
|
|
|
return cls(existing=items, key_field=key_field) |
|
|